From f4a46ba6ea39d23226e6d2e512fdce8a5f24fa4a Mon Sep 17 00:00:00 2001 From: Calvin Rose Date: Wed, 12 Feb 2020 09:32:41 -0600 Subject: [PATCH] Add methods to streams. This makes streams polymorphic with files in many cases. printf family functions still need porting. --- examples/tcpclient.janet | 13 ++++++------- examples/tcpserver.janet | 16 ++++++++-------- src/core/net.c | 20 ++++++++++++++++++-- 3 files changed, 32 insertions(+), 17 deletions(-) diff --git a/examples/tcpclient.janet b/examples/tcpclient.janet index 28f28af8..b042da4a 100644 --- a/examples/tcpclient.janet +++ b/examples/tcpclient.janet @@ -1,7 +1,6 @@ -(def conn (net/connect "127.0.0.1" "8000")) -(printf "Connected to %q!" conn) -(net/write conn "Echo...") -(print "Wrote to connection...") -(def res (net/read conn 1024)) -(pp res) -(net/close conn) +(with [conn (net/connect "127.0.0.1" "8000")] + (printf "Connected to %q!" conn) + (:write conn "Echo...") + (print "Wrote to connection...") + (def res (:read conn 1024)) + (pp res)) diff --git a/examples/tcpserver.janet b/examples/tcpserver.janet index a7ecd2d2..71501b8b 100644 --- a/examples/tcpserver.janet +++ b/examples/tcpserver.janet @@ -1,13 +1,13 @@ (defn handler "Simple handler for connections." [stream] - (def id (gensym)) - (def b @"") - (print "Connection " id "!") - (while (net/read stream 1024 b) - (net/write stream b) - (buffer/clear b)) - (printf "Done %v!" id) - (net/close stream)) + (defer (:close stream) + (def id (gensym)) + (def b @"") + (print "Connection " id "!") + (while (:read stream 1024 b) + (:write stream b) + (buffer/clear b)) + (printf "Done %v!" id))) (net/server "127.0.0.1" "8000" handler) diff --git a/src/core/net.c b/src/core/net.c index 0060dba2..9802daaf 100644 --- a/src/core/net.c +++ b/src/core/net.c @@ -50,12 +50,14 @@ typedef struct { static int janet_stream_close(void *p, size_t s); -static int janet_stream_getter(void *p, size_t, Janet key); +static int janet_stream_getter(void *p, Janet key, Janet *out); static const JanetAbstractType StreamAT = { "core/stream", janet_stream_close, - JANET_ATEND_GC + NULL, + janet_stream_getter, + JANET_ATEND_GET }; static int janet_stream_close(void *p, size_t s) { @@ -523,6 +525,20 @@ static Janet cfun_stream_write(int32_t argc, Janet *argv) { } } +static const JanetMethod stream_methods[] = { + {"chunk", cfun_stream_chunk}, + {"close", cfun_stream_close}, + {"read", cfun_stream_read}, + {"write", cfun_stream_write}, + {NULL, NULL} +}; + +static int janet_stream_getter(void *p, Janet key, Janet *out) { + (void) p; + if (!janet_checktype(key, JANET_KEYWORD)) return 0; + return janet_getmethod(janet_unwrap_keyword(key), stream_methods, out); +} + static const JanetReg net_cfuns[] = { { "net/server", cfun_net_server,