xref: /freebsd/sys/contrib/openzfs/module/lua/lzio.c (revision b51f459a2098622c31ed54f5c1bf0e03efce403b)
1 /* BEGIN CSTYLED */
2 /*
3 ** $Id: lzio.c,v 1.35.1.1 2013/04/12 18:48:47 roberto Exp $
4 ** Buffered streams
5 ** See Copyright Notice in lua.h
6 */
7 
8 
9 #define lzio_c
10 #define LUA_CORE
11 
12 #include <sys/lua/lua.h>
13 
14 #include "llimits.h"
15 #include "lmem.h"
16 #include "lstate.h"
17 #include "lzio.h"
18 
19 
20 int luaZ_fill (ZIO *z) {
21   size_t size;
22   lua_State *L = z->L;
23   const char *buff;
24   lua_unlock(L);
25   buff = z->reader(L, z->data, &size);
26   lua_lock(L);
27   if (buff == NULL || size == 0)
28     return EOZ;
29   z->n = size - 1;  /* discount char being returned */
30   z->p = buff;
31   return cast_uchar(*(z->p++));
32 }
33 
34 
35 void luaZ_init (lua_State *L, ZIO *z, lua_Reader reader, void *data) {
36   z->L = L;
37   z->reader = reader;
38   z->data = data;
39   z->n = 0;
40   z->p = NULL;
41 }
42 
43 
44 /* --------------------------------------------------------------- read --- */
45 size_t luaZ_read (ZIO *z, void *b, size_t n) {
46   while (n) {
47     size_t m;
48     if (z->n == 0) {  /* no bytes in buffer? */
49       if (luaZ_fill(z) == EOZ)  /* try to read more */
50         return n;  /* no more input; return number of missing bytes */
51       else {
52         z->n++;  /* luaZ_fill consumed first byte; put it back */
53         z->p--;
54       }
55     }
56     m = (n <= z->n) ? n : z->n;  /* min. between n and z->n */
57     memcpy(b, z->p, m);
58     z->n -= m;
59     z->p += m;
60     b = (char *)b + m;
61     n -= m;
62   }
63   return 0;
64 }
65 
66 /* ------------------------------------------------------------------------ */
67 char *luaZ_openspace (lua_State *L, Mbuffer *buff, size_t n) {
68   if (n > buff->buffsize) {
69     if (n < LUA_MINBUFFER) n = LUA_MINBUFFER;
70     luaZ_resizebuffer(L, buff, n);
71   }
72   return buff->buffer;
73 }
74 /* END CSTYLED */
75