summaryrefslogtreecommitdiffhomepage
diff options
context:
space:
mode:
authorAki <please@ignore.pl>2021-03-03 23:54:34 +0100
committerAki <please@ignore.pl>2021-03-03 23:54:34 +0100
commit9b2a36ee8da4e25d919a435f871cc1e0fee8eace (patch)
treedd40449f43695c7ce3847bf74f4bbc479692d0dc
parentd093136a39864bad7bb97b30d0244959d815ced1 (diff)
downloadplop-9b2a36ee8da4e25d919a435f871cc1e0fee8eace.zip
plop-9b2a36ee8da4e25d919a435f871cc1e0fee8eace.tar.gz
plop-9b2a36ee8da4e25d919a435f871cc1e0fee8eace.tar.bz2
Added handling for 0 length reads
-rw-r--r--stream.c33
-rw-r--r--stream.h1
2 files changed, 22 insertions, 12 deletions
diff --git a/stream.c b/stream.c
index 6e99cde..eac89a8 100644
--- a/stream.c
+++ b/stream.c
@@ -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);
}
diff --git a/stream.h b/stream.h
index a164981..f1bc32c 100644
--- a/stream.h
+++ b/stream.h
@@ -7,6 +7,7 @@ struct buffer
char * data;
int length;
int offset;
+ int next;
int allocated;
};