]> gitweb.factorcode.org Git - factor.git/blob - basis/io/streams/duplex/duplex.factor
Solution to Project Euler problem 65
[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 : >duplex-stream< ( stream -- in out ) [ in>> ] [ out>> ] bi ; inline
17
18 M: duplex-stream stream-element-type
19     [ in>> ] [ out>> ] bi
20     [ stream-element-type ] bi@
21     2dup eq? [ drop ] [ "Cannot determine element type" throw ] if ;
22
23 M: duplex-stream set-timeout
24     >duplex-stream< [ set-timeout ] bi-curry@ bi ;
25
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 ;
31
32 : <encoder-duplex> ( stream-in stream-out encoding -- duplex )
33     [ re-decode ] [ re-encode ] bi-curry bi* <duplex-stream> ;
34
35 : with-stream* ( stream quot -- )
36     [ >duplex-stream< ] dip with-streams* ; inline
37
38 : with-stream ( stream quot -- )
39     [ >duplex-stream< ] dip with-streams ; inline
40
41 ERROR: invalid-duplex-stream ;
42
43 M: duplex-stream underlying-handle
44     >duplex-stream<
45     [ underlying-handle ] bi@
46     [ = [ invalid-duplex-stream ] when ] keep ;
47