1/*
2** $Id: lzio.c,v 1.31.1.1 2007/12/27 13:02:25 roberto Exp $
3** a generic input stream interface
4** See Copyright Notice in lua.h
5*/
6
7
8#include <string.h>
9
10#define lzio_c
11#define LUA_CORE
12
13#include "lua.h"
14
15#include "llimits.h"
16#include "lmem.h"
17#include "lstate.h"
18#include "lzio.h"
19
20
21int luaZ_fill (ZIO *z) {
22 size_t size;
23 lua_State *L = z->L;
24 const char *buff;
25 lua_unlock(L);
26 buff = z->reader(L, z->data, &size);
27 lua_lock(L);
28 if (buff == NULL || size == 0) return EOZ;
29 z->n = size - 1;
30 z->p = buff;
31 return char2int(*(z->p++));
32}
33
34
35int luaZ_lookahead (ZIO *z) {
36 if (z->n == 0) {
37 if (luaZ_fill(z) == EOZ)
38 return EOZ;
39 else {
40 z->n++; /* luaZ_fill removed first byte; put back it */
41 z->p--;
42 }
43 }
44 return char2int(*z->p);
45}
46
47
48void luaZ_init (lua_State *L, ZIO *z, lua_Reader reader, void *data) {
49 z->L = L;
50 z->reader = reader;
51 z->data = data;
52 z->n = 0;
53 z->p = NULL;
54}
55
56
57/* --------------------------------------------------------------- read --- */
58size_t luaZ_read (ZIO *z, void *b, size_t n) {
59 while (n) {
60 size_t m;
61 if (luaZ_lookahead(z) == EOZ)
62 return n; /* return number of missing bytes */
63 m = (n <= z->n) ? n : z->n; /* min. between n and z->n */
64 memcpy(b, z->p, m);
65 z->n -= m;
66 z->p += m;
67 b = (char *)b + m;
68 n -= m;
69 }
70 return 0;
71}
72
73/* ------------------------------------------------------------------------ */
74char *luaZ_openspace (lua_State *L, Mbuffer *buff, size_t n) {
75 if (n > buff->buffsize) {
76 if (n < LUA_MINBUFFER) n = LUA_MINBUFFER;
77 luaZ_resizebuffer(L, buff, n);
78 }
79 return buff->buffer;
80}
81
82
83