summaryrefslogtreecommitdiffhomepage
diff options
context:
space:
mode:
authorAki <please@ignore.pl>2021-02-24 21:20:17 +0100
committerAki <please@ignore.pl>2021-02-24 21:20:17 +0100
commit0cbe8c24b3f870d91084b3612dba8b4478b64a32 (patch)
tree38284c38206f8346272b42b2b99e0a036f5a5530
parentd6a54f904957d34f12361d5d8a7e515562cda3d5 (diff)
downloadplop-0cbe8c24b3f870d91084b3612dba8b4478b64a32.zip
plop-0cbe8c24b3f870d91084b3612dba8b4478b64a32.tar.gz
plop-0cbe8c24b3f870d91084b3612dba8b4478b64a32.tar.bz2
Added strub for stream read function
-rw-r--r--stream.c58
-rw-r--r--stream.h1
2 files changed, 55 insertions, 4 deletions
diff --git a/stream.c b/stream.c
index a322e2b..8e92358 100644
--- a/stream.c
+++ b/stream.c
@@ -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;
diff --git a/stream.h b/stream.h
index f38b6ef..efa6afa 100644
--- a/stream.h
+++ b/stream.h
@@ -17,3 +17,4 @@ struct stream
int stream_push_new(lua_State *, const int);
int stream_gc(lua_State *);
+int stream_read(lua_State *);