1 ! Copyright (C) 2005, 2009 Slava Pestov.
2 ! See http://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 : >duplex-stream< ( stream -- in out ) [ in>> ] [ out>> ] bi ; inline
18 M: duplex-stream set-timeout
19 >duplex-stream< [ set-timeout ] bi-curry@ bi ;
21 M: duplex-stream dispose
22 #! The output stream is closed first, in case both streams
23 #! are attached to the same file descriptor, the output
24 #! buffer needs to be flushed before we close the fd.
25 [ >duplex-stream< [ &dispose drop ] bi@ ] with-destructors ;
27 : <encoder-duplex> ( stream-in stream-out encoding -- duplex )
28 [ re-decode ] [ re-encode ] bi-curry bi* <duplex-stream> ;
30 : with-stream* ( stream quot -- )
31 [ >duplex-stream< ] dip with-streams* ; inline
33 : with-stream ( stream quot -- )
34 [ >duplex-stream< ] dip with-streams ; inline
36 ERROR: invalid-duplex-stream ;
38 M: duplex-stream underlying-handle
40 [ underlying-handle ] bi@
41 [ = [ invalid-duplex-stream ] when ] keep ;