summaryrefslogtreecommitdiffhomepage
diff options
context:
space:
mode:
-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 *);