]> gitweb.factorcode.org Git - factor.git/blob - basis/io/streams/duplex/duplex.factor
Fix comments to be ! not #!.
[factor.git] / basis / io / streams / duplex / duplex.factor
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 ;
6 IN: io.streams.duplex
7
8 TUPLE: duplex-stream in out ;
9
10 C: <duplex-stream> duplex-stream
11
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>> ;
15
16 INSTANCE: duplex-stream input-stream
17 INSTANCE: duplex-stream output-stream
18
19 : >duplex-stream< ( stream -- in out ) [ in>> ] [ out>> ] bi ; inline
20
21 M: duplex-stream stream-element-type
22     [ in>> ] [ out>> ] bi
23     [ stream-element-type ] bi@
24     2dup eq? [ drop ] [ "Cannot determine element type" throw ] if ;
25
26 M: duplex-stream set-timeout
27     >duplex-stream< [ set-timeout ] bi-curry@ bi ;
28
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 ;
34
35 : <encoder-duplex> ( stream-in stream-out encoding -- duplex )
36     [ re-decode ] [ re-encode ] bi-curry bi* <duplex-stream> ;
37
38 : with-stream* ( stream quot -- )
39     [ >duplex-stream< ] dip with-streams* ; inline
40
41 : with-stream ( stream quot -- )
42     [ >duplex-stream< ] dip with-streams ; inline
43
44 ERROR: invalid-duplex-stream ;
45
46 M: duplex-stream underlying-handle
47     >duplex-stream<
48     [ underlying-handle ] bi@
49     [ = [ invalid-duplex-stream ] when ] keep ;