no need of lookahead in Zio

This commit is contained in:
Roberto Ierusalimschy
2011-02-23 10:13:10 -03:00
parent 03b769053a
commit 7482e8f914
8 changed files with 29 additions and 41 deletions

33
lzio.c
View File

@@ -1,5 +1,5 @@
/*
** $Id: lzio.c,v 1.31 2005/06/03 20:15:29 roberto Exp roberto $
** $Id: lzio.c,v 1.32 2011/02/17 17:34:16 roberto Exp roberto $
** a generic input stream interface
** See Copyright Notice in lua.h
*/
@@ -22,40 +22,23 @@ int luaZ_fill (ZIO *z) {
size_t size;
lua_State *L = z->L;
const char *buff;
if (z->eoz) return EOZ;
lua_unlock(L);
buff = z->reader(L, z->data, &size);
lua_lock(L);
if (buff == NULL || size == 0) {
z->eoz = 1; /* avoid calling reader function next time */
if (buff == NULL || size == 0)
return EOZ;
}
z->n = size - 1;
z->n = size - 1; /* discount char being returned */
z->p = buff;
return char2int(*(z->p++));
}
int luaZ_lookahead (ZIO *z) {
if (z->n == 0) {
if (luaZ_fill(z) == EOZ)
return EOZ;
else {
z->n++; /* luaZ_fill removed first byte; put back it */
z->p--;
}
}
return char2int(*z->p);
}
void luaZ_init (lua_State *L, ZIO *z, lua_Reader reader, void *data) {
z->L = L;
z->reader = reader;
z->data = data;
z->n = 0;
z->p = NULL;
z->eoz = 0;
}
@@ -63,8 +46,14 @@ void luaZ_init (lua_State *L, ZIO *z, lua_Reader reader, void *data) {
size_t luaZ_read (ZIO *z, void *b, size_t n) {
while (n) {
size_t m;
if (luaZ_lookahead(z) == EOZ)
return n; /* return number of missing bytes */
if (z->n == 0) { /* no bytes in buffer? */
if (luaZ_fill(z) == EOZ) /* try to read more */
return n; /* no more input; return number of missing bytes */
else {
z->n++; /* luaZ_fill consumed first byte; put it back */
z->p--;
}
}
m = (n <= z->n) ? n : z->n; /* min. between n and z->n */
memcpy(b, z->p, m);
z->n -= m;