diff options
Diffstat (limited to 'util-src/ringbuffer.c')
-rw-r--r-- | util-src/ringbuffer.c | 42 |
1 files changed, 42 insertions, 0 deletions
diff --git a/util-src/ringbuffer.c b/util-src/ringbuffer.c index 8d9e49e6..8f9013f7 100644 --- a/util-src/ringbuffer.c +++ b/util-src/ringbuffer.c @@ -39,10 +39,12 @@ int find(ringbuffer *b, const char *s, size_t l) { return 0; } + /* look for a matching first byte */ for(i = 0; i <= b->blen - l; i++) { if(b->buffer[(b->rpos + i) % b->alen] == *s) { m = 1; + /* check if the following byte also match */ for(j = 1; j < l; j++) if(b->buffer[(b->rpos + i + j) % b->alen] != s[j]) { m = 0; @@ -58,6 +60,10 @@ int find(ringbuffer *b, const char *s, size_t l) { return 0; } +/* + * Find first position of a substring in buffer + * (buffer, string) -> number + */ int rb_find(lua_State *L) { size_t l, m; ringbuffer *b = luaL_checkudata(L, 1, "ringbuffer_mt"); @@ -72,6 +78,31 @@ int rb_find(lua_State *L) { return 0; } +/* + * Move read position forward without returning the data + * (buffer, number) -> boolean + */ +int rb_discard(lua_State *L) { + ringbuffer *b = luaL_checkudata(L, 1, "ringbuffer_mt"); + size_t r = luaL_checkinteger(L, 2); + + if(r > b->blen) { + lua_pushboolean(L, 0); + return 1; + } + + b->blen -= r; + b->rpos += r; + modpos(b); + + lua_pushboolean(L, 1); + return 1; +} + +/* + * Read bytes from buffer + * (buffer, number, boolean?) -> string + */ int rb_read(lua_State *L) { ringbuffer *b = luaL_checkudata(L, 1, "ringbuffer_mt"); size_t r = luaL_checkinteger(L, 2); @@ -83,6 +114,7 @@ int rb_read(lua_State *L) { } if((b->rpos + r) > b->alen) { + /* Substring wraps around to the beginning of the buffer */ lua_pushlstring(L, &b->buffer[b->rpos], b->alen - b->rpos); lua_pushlstring(L, b->buffer, r - (b->alen - b->rpos)); lua_concat(L, 2); @@ -99,6 +131,10 @@ int rb_read(lua_State *L) { return 1; } +/* + * Read buffer until first occurrence of a substring + * (buffer, string) -> string + */ int rb_readuntil(lua_State *L) { size_t l, m; ringbuffer *b = luaL_checkudata(L, 1, "ringbuffer_mt"); @@ -114,6 +150,10 @@ int rb_readuntil(lua_State *L) { return 0; } +/* + * Write bytes into the buffer + * (buffer, string) -> integer + */ int rb_write(lua_State *L) { size_t l, w = 0; ringbuffer *b = luaL_checkudata(L, 1, "ringbuffer_mt"); @@ -191,6 +231,8 @@ int luaopen_util_ringbuffer(lua_State *L) { { lua_pushcfunction(L, rb_find); lua_setfield(L, -2, "find"); + lua_pushcfunction(L, rb_discard); + lua_setfield(L, -2, "discard"); lua_pushcfunction(L, rb_read); lua_setfield(L, -2, "read"); lua_pushcfunction(L, rb_readuntil); |