1 /*
2 ** $Id: lzio.c,v 1.35.1.1 2013/04/12 18:48:47 roberto Exp $
3 ** Buffered streams
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 
luaZ_fill(ZIO * z)21 int 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)
29     return EOZ;
30   z->n = size - 1;  /* discount char being returned */
31   z->p = buff;
32   return cast_uchar(*(z->p++));
33 }
34 
35 
luaZ_init(lua_State * L,ZIO * z,lua_Reader reader,void * data)36 void luaZ_init (lua_State *L, ZIO *z, lua_Reader reader, void *data) {
37   z->L = L;
38   z->reader = reader;
39   z->data = data;
40   z->n = 0;
41   z->p = NULL;
42 }
43 
44 
45 /* --------------------------------------------------------------- read --- */
luaZ_read(ZIO * z,void * b,size_t n)46 size_t luaZ_read (ZIO *z, void *b, size_t n) {
47   while (n) {
48     size_t m;
49     if (z->n == 0) {  /* no bytes in buffer? */
50       if (luaZ_fill(z) == EOZ)  /* try to read more */
51         return n;  /* no more input; return number of missing bytes */
52       else {
53         z->n++;  /* luaZ_fill consumed first byte; put it back */
54         z->p--;
55       }
56     }
57     m = (n <= z->n) ? n : z->n;  /* min. between n and z->n */
58     memcpy(b, z->p, m);
59     z->n -= m;
60     z->p += m;
61     b = (char *)b + m;
62     n -= m;
63   }
64   return 0;
65 }
66 
67 /* ------------------------------------------------------------------------ */
luaZ_openspace(lua_State * L,Mbuffer * buff,size_t n)68 char *luaZ_openspace (lua_State *L, Mbuffer *buff, size_t n) {
69   if (n > buff->buffsize) {
70     if (n < LUA_MINBUFFER) n = LUA_MINBUFFER;
71     luaZ_resizebuffer(L, buff, n);
72   }
73   return buff->buffer;
74 }
75 
76 
77