lib/core: add protocols for decorator streams
authorLucas Bajolet <lucas.bajolet@gmail.com>
Wed, 9 May 2018 17:18:51 +0000 (13:18 -0400)
committerLucas Bajolet <lucas.bajolet@gmail.com>
Fri, 11 May 2018 14:26:43 +0000 (10:26 -0400)
Protocol are a class of streams designed to be decorators over others
and provide a high-level interface to protocols.

Signed-off-by: Lucas Bajolet <lucas.bajolet@gmail.com>

lib/core/core.nit
lib/core/protocol.nit [new file with mode: 0644]

index 97a4271..54f2550 100644 (file)
@@ -33,3 +33,4 @@ import error
 import re
 import bytes
 import fixed_ints
+import protocol
diff --git a/lib/core/protocol.nit b/lib/core/protocol.nit
new file mode 100644 (file)
index 0000000..62a5f8a
--- /dev/null
@@ -0,0 +1,63 @@
+# This file is part of NIT ( http://www.nitlanguage.org ).
+#
+# This file is free software, which comes along with NIT. This software is
+# distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
+# without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
+# PARTICULAR PURPOSE. You can modify it is you want, provided this header
+# is kept unaltered, and a notification of the changes is added.
+# You are allowed to redistribute it and sell it, alone or is a part of
+# another product.
+
+import stream
+
+# Stream class used as a Decorator over a stream
+class Protocol
+       super Stream
+
+       type STREAM: Stream
+
+       var origin: STREAM
+
+       redef fun close do origin.close
+end
+
+# Reader decorator over a read-capable stream
+class ReaderProtocol
+       super Reader
+       super Protocol
+
+       redef type STREAM: Reader
+
+       redef fun raw_read_byte do
+               return origin.read_byte
+       end
+
+       redef fun raw_read_bytes(ns, len) do
+               return origin.read_bytes_to_cstring(ns, len)
+       end
+end
+
+# Writer decorator over a write-capable stream
+class WriterProtocol
+       super Writer
+       super Protocol
+
+       redef type STREAM: Writer
+
+       redef fun write_byte(b) do
+               origin.write_byte(b)
+       end
+
+       redef fun write_bytes_from_cstring(ns, len) do
+               origin.write_bytes_from_cstring(ns, len)
+       end
+end
+
+# Reader/Writer decorator over a duplex-capable stream
+class DuplexProtocol
+       super Duplex
+       super WriterProtocol
+       super ReaderProtocol
+
+       redef type STREAM: Duplex
+end