1 /* $NetBSD: lzio.c,v 1.8 2018/08/04 17:30:01 alnsn Exp $ */ 2 3 /* 4 ** Id: lzio.c,v 1.37.1.1 2017/04/19 17:20:42 roberto Exp 5 ** Buffered streams 6 ** See Copyright Notice in lua.h 7 */ 8 9 #define lzio_c 10 #define LUA_CORE 11 12 #include "lprefix.h" 13 14 15 #ifndef _KERNEL 16 #include <string.h> 17 #endif /* _KERNEL */ 18 19 #include "lua.h" 20 21 #include "llimits.h" 22 #include "lmem.h" 23 #include "lstate.h" 24 #include "lzio.h" 25 26 27 int luaZ_fill (ZIO *z) { 28 size_t size; 29 lua_State *L = z->L; 30 const char *buff; 31 lua_unlock(L); 32 buff = z->reader(L, z->data, &size); 33 lua_lock(L); 34 if (buff == NULL || size == 0) 35 return EOZ; 36 z->n = size - 1; /* discount char being returned */ 37 z->p = buff; 38 return cast_uchar(*(z->p++)); 39 } 40 41 42 void luaZ_init (lua_State *L, ZIO *z, lua_Reader reader, void *data) { 43 z->L = L; 44 z->reader = reader; 45 z->data = data; 46 z->n = 0; 47 z->p = NULL; 48 } 49 50 51 /* --------------------------------------------------------------- read --- */ 52 size_t luaZ_read (ZIO *z, void *b, size_t n) { 53 while (n) { 54 size_t m; 55 if (z->n == 0) { /* no bytes in buffer? */ 56 if (luaZ_fill(z) == EOZ) /* try to read more */ 57 return n; /* no more input; return number of missing bytes */ 58 else { 59 z->n++; /* luaZ_fill consumed first byte; put it back */ 60 z->p--; 61 } 62 } 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