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 stream-element-type
20 [ stream-element-type ] bi@
21 2dup eq? [ drop ] [ "Cannot determine element type" throw ] if ;
23 M: duplex-stream set-timeout
24 >duplex-stream< [ set-timeout ] bi-curry@ bi ;
26 M: duplex-stream dispose
27 #! The output stream is closed first, in case both streams
28 #! are attached to the same file descriptor, the output
29 #! buffer needs to be flushed before we close the fd.
30 [ >duplex-stream< [ &dispose drop ] bi@ ] with-destructors ;
32 : <encoder-duplex> ( stream-in stream-out encoding -- duplex )
33 [ re-decode ] [ re-encode ] bi-curry bi* <duplex-stream> ;
35 : with-stream* ( stream quot -- )
36 [ >duplex-stream< ] dip with-streams* ; inline
38 : with-stream ( stream quot -- )
39 [ >duplex-stream< ] dip with-streams ; inline
41 ERROR: invalid-duplex-stream ;
43 M: duplex-stream underlying-handle
45 [ underlying-handle ] bi@
46 [ = [ invalid-duplex-stream ] when ] keep ;