diff options
author | Aki <please@ignore.pl> | 2021-02-24 21:20:17 +0100 |
---|---|---|
committer | Aki <please@ignore.pl> | 2021-02-24 21:20:17 +0100 |
commit | 0cbe8c24b3f870d91084b3612dba8b4478b64a32 (patch) | |
tree | 38284c38206f8346272b42b2b99e0a036f5a5530 | |
parent | d6a54f904957d34f12361d5d8a7e515562cda3d5 (diff) | |
download | plop-0cbe8c24b3f870d91084b3612dba8b4478b64a32.zip plop-0cbe8c24b3f870d91084b3612dba8b4478b64a32.tar.gz plop-0cbe8c24b3f870d91084b3612dba8b4478b64a32.tar.bz2 |
Added strub for stream read function
-rw-r--r-- | stream.c | 58 | ||||
-rw-r--r-- | stream.h | 1 |
2 files changed, 55 insertions, 4 deletions
@@ -19,6 +19,13 @@ int stream_push_new(lua_State * L, const int fd) lua_pushstring(L, "__gc"); lua_pushcfunction(L, stream_gc); lua_rawset(L, -3); + + lua_pushstring(L, "__index"); + lua_createtable(L, 0, 1); + lua_pushstring(L, "read"); + lua_pushcfunction(L, stream_read); + lua_rawset(L, -3); + lua_rawset(L, -3); } lua_setmetatable(L, -2); @@ -28,17 +35,60 @@ int stream_push_new(lua_State * L, const int fd) /// Metamethod to handle garbage collection of Stream userdata. /// \param L Lua state in which Stream resides -/// \return Always zero, which is the number of the results pushed to the stack +/// \return Number of the results pushed to the stack; always zero in this case int stream_gc(lua_State * L) { + int n = lua_gettop(L); + + if (1 != n) + { + lua_pushliteral(L, "Invalid number of arguments received"); + return lua_error(L); + } + + struct stream * s = lua_touserdata(L, -1); + + if (NULL == s) + { + lua_pushliteral(L, "Missing stream argument"); + return lua_error(L); + } + + if (NULL != s->in.data) + { + free(s->in.data); + } + + lua_pop(L, 1); + + return 0; +} + +/// Starts reading operation from a stream. +/// \param L Lua state in which Stream resides +/// \return Number of the results pushed to the stack +int stream_read(lua_State * L) +{ struct stream * s = lua_touserdata(L, -1); - if (NULL != s) + if (NULL == s) + { + // TODO: Improve error handling and raising in steam_* lua_CFunctions + lua_pushliteral(L, "Missing stream argument"); + return lua_error(L); + } + + if (NULL == s->in.data) { - if (NULL != s->in.data) + void * buffer = malloc(1024); + + if (NULL == buffer) { - free(s->in.data); + lua_pushliteral(L, "Could not allocate buffer for stream"); + return lua_error(L); } + + s->in.data = buffer; } return 0; @@ -17,3 +17,4 @@ struct stream int stream_push_new(lua_State *, const int); int stream_gc(lua_State *); +int stream_read(lua_State *); |