18e3e3a7aSWarner Losh /*
2*0495ed39SKyle Evans ** $Id: lzio.c $
38e3e3a7aSWarner Losh ** Buffered streams
48e3e3a7aSWarner Losh ** See Copyright Notice in lua.h
58e3e3a7aSWarner Losh */
68e3e3a7aSWarner Losh
78e3e3a7aSWarner Losh #define lzio_c
88e3e3a7aSWarner Losh #define LUA_CORE
98e3e3a7aSWarner Losh
108e3e3a7aSWarner Losh #include "lprefix.h"
118e3e3a7aSWarner Losh
128e3e3a7aSWarner Losh
138e3e3a7aSWarner Losh #include <string.h>
148e3e3a7aSWarner Losh
158e3e3a7aSWarner Losh #include "lua.h"
168e3e3a7aSWarner Losh
178e3e3a7aSWarner Losh #include "llimits.h"
188e3e3a7aSWarner Losh #include "lmem.h"
198e3e3a7aSWarner Losh #include "lstate.h"
208e3e3a7aSWarner Losh #include "lzio.h"
218e3e3a7aSWarner Losh
228e3e3a7aSWarner Losh
luaZ_fill(ZIO * z)238e3e3a7aSWarner Losh int luaZ_fill (ZIO *z) {
248e3e3a7aSWarner Losh size_t size;
258e3e3a7aSWarner Losh lua_State *L = z->L;
268e3e3a7aSWarner Losh const char *buff;
278e3e3a7aSWarner Losh lua_unlock(L);
288e3e3a7aSWarner Losh buff = z->reader(L, z->data, &size);
298e3e3a7aSWarner Losh lua_lock(L);
308e3e3a7aSWarner Losh if (buff == NULL || size == 0)
318e3e3a7aSWarner Losh return EOZ;
328e3e3a7aSWarner Losh z->n = size - 1; /* discount char being returned */
338e3e3a7aSWarner Losh z->p = buff;
348e3e3a7aSWarner Losh return cast_uchar(*(z->p++));
358e3e3a7aSWarner Losh }
368e3e3a7aSWarner Losh
378e3e3a7aSWarner Losh
luaZ_init(lua_State * L,ZIO * z,lua_Reader reader,void * data)388e3e3a7aSWarner Losh void luaZ_init (lua_State *L, ZIO *z, lua_Reader reader, void *data) {
398e3e3a7aSWarner Losh z->L = L;
408e3e3a7aSWarner Losh z->reader = reader;
418e3e3a7aSWarner Losh z->data = data;
428e3e3a7aSWarner Losh z->n = 0;
438e3e3a7aSWarner Losh z->p = NULL;
448e3e3a7aSWarner Losh }
458e3e3a7aSWarner Losh
468e3e3a7aSWarner Losh
478e3e3a7aSWarner Losh /* --------------------------------------------------------------- read --- */
luaZ_read(ZIO * z,void * b,size_t n)488e3e3a7aSWarner Losh size_t luaZ_read (ZIO *z, void *b, size_t n) {
498e3e3a7aSWarner Losh while (n) {
508e3e3a7aSWarner Losh size_t m;
518e3e3a7aSWarner Losh if (z->n == 0) { /* no bytes in buffer? */
528e3e3a7aSWarner Losh if (luaZ_fill(z) == EOZ) /* try to read more */
538e3e3a7aSWarner Losh return n; /* no more input; return number of missing bytes */
548e3e3a7aSWarner Losh else {
558e3e3a7aSWarner Losh z->n++; /* luaZ_fill consumed first byte; put it back */
568e3e3a7aSWarner Losh z->p--;
578e3e3a7aSWarner Losh }
588e3e3a7aSWarner Losh }
598e3e3a7aSWarner Losh m = (n <= z->n) ? n : z->n; /* min. between n and z->n */
608e3e3a7aSWarner Losh memcpy(b, z->p, m);
618e3e3a7aSWarner Losh z->n -= m;
628e3e3a7aSWarner Losh z->p += m;
638e3e3a7aSWarner Losh b = (char *)b + m;
648e3e3a7aSWarner Losh n -= m;
658e3e3a7aSWarner Losh }
668e3e3a7aSWarner Losh return 0;
678e3e3a7aSWarner Losh }
688e3e3a7aSWarner Losh
69