etc/protocols - sync with NetBSD-8
[minix.git] / external / mit / lua / dist / src / lzio.c
blob38c4ecf101493a0bd710839de6aa6387cd53784a
1 /* $NetBSD: lzio.c,v 1.3 2015/02/02 14:03:05 lneto Exp $ */
3 /*
4 ** Id: lzio.c,v 1.36 2014/11/02 19:19:04 roberto Exp
5 ** Buffered streams
6 ** See Copyright Notice in lua.h
7 */
9 #define lzio_c
10 #define LUA_CORE
12 #include "lprefix.h"
15 #ifndef _KERNEL
16 #include <string.h>
17 #endif
19 #include "lua.h"
21 #include "llimits.h"
22 #include "lmem.h"
23 #include "lstate.h"
24 #include "lzio.h"
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++));
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;
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--;
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;
70 return 0;
73 /* ------------------------------------------------------------------------ */
74 char *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);
79 return buff->buffer;