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