diff options
-rw-r--r-- | stream.c | 33 | ||||
-rw-r--r-- | stream.h | 1 |
2 files changed, 22 insertions, 12 deletions
@@ -105,6 +105,7 @@ int stream_read(lua_State * L) s->in.allocated = 1024; s->in.length = 0; s->in.offset = 0; + s->in.next = 0; } return stream_readk(L, LUA_OK, 2); // Intentionally do not remove arguments from the stack. @@ -177,29 +178,27 @@ static int read_more(lua_State * L, struct stream * s, int minimum_length, lua_K static int prepare_at_least(lua_State * L, struct stream * s, int minimum_length, lua_KContext ctx) { - const int remaining_bytes = s->in.length - s->in.offset; + const int remaining_bytes = s->in.length - s->in.next; if (remaining_bytes < minimum_length) { return read_more(L, s, minimum_length, ctx); } - return 0; + return remaining_bytes; } static int until(struct buffer * b, const char * pattern, int pattern_length) { - int offset = b->offset; - - while (offset + pattern_length <= b->length) + while (b->next + pattern_length <= b->length) { - if (0 == strncmp(&b->data[offset], pattern, pattern_length)) + if (0 == strncmp(&b->data[b->next], pattern, pattern_length)) { - return offset; + return b->next; } else { - offset++; + b->next++; } } @@ -222,15 +221,25 @@ int stream_readk(lua_State * L, int status, lua_KContext ctx) const char * pattern = lua_tolstring(L, ctx, &pattern_length); int offset; + int remaining_bytes; do { - prepare_at_least(L, s, (int) pattern_length, ctx); + remaining_bytes = prepare_at_least(L, s, (int) pattern_length, ctx); offset = until(&s->in, pattern, (int) pattern_length); } - while (-1 == offset); + while (-1 == offset && 0 < remaining_bytes); + + if (-1 != offset) + { + lua_pushlstring(L, &s->in.data[s->in.offset], offset - s->in.offset); + s->in.offset = offset + 1; + s->in.next = offset + 1; + } + else + { + lua_pushnil(L); + } - lua_pushlstring(L, &s->in.data[s->in.offset], offset - s->in.offset); - s->in.offset = offset + 1; lua_remove(L, ctx); lua_insert(L, ctx); } @@ -7,6 +7,7 @@ struct buffer char * data; int length; int offset; + int next; int allocated; }; |