1 ! Copyright (C) 2005, 2009 Slava Pestov.
2 ! See https://factorcode.org/license.txt for BSD license.
3 USING: kernel continuations destructors io io.encodings
4 io.encodings.private io.timeouts io.ports io.styles summary
5 accessors delegate delegate.protocols ;
8 TUPLE: duplex-stream in out ;
10 C: <duplex-stream> duplex-stream
12 CONSULT: input-stream-protocol duplex-stream in>> ;
13 CONSULT: output-stream-protocol duplex-stream out>> ;
14 CONSULT: formatted-output-stream-protocol duplex-stream out>> ;
16 INSTANCE: duplex-stream input-stream
17 INSTANCE: duplex-stream output-stream
19 : >duplex-stream< ( stream -- in out ) [ in>> ] [ out>> ] bi ; inline
21 M: duplex-stream stream-element-type
23 [ stream-element-type ] bi@
24 2dup eq? [ drop ] [ "Cannot determine element type" throw ] if ;
26 M: duplex-stream set-timeout
27 >duplex-stream< [ set-timeout ] bi-curry@ bi ;
29 M: duplex-stream dispose
30 ! The output stream is closed first, in case both streams
31 ! are attached to the same file descriptor, the output
32 ! buffer needs to be flushed before we close the fd.
33 [ >duplex-stream< [ &dispose drop ] bi@ ] with-destructors ;
35 : <encoder-duplex> ( stream-in stream-out encoding -- duplex )
36 [ re-decode ] [ re-encode ] bi-curry bi* <duplex-stream> ;
38 : with-stream* ( stream quot -- )
39 [ >duplex-stream< ] dip with-streams* ; inline
41 : with-stream ( stream quot -- )
42 [ >duplex-stream< ] dip with-streams ; inline
44 ERROR: invalid-duplex-stream ;
46 M: duplex-stream underlying-handle
48 [ underlying-handle ] bi@
49 [ = [ invalid-duplex-stream ] when ] keep ;