factor/basis/io/streams/duplex/duplex.factor

50 lines
1.6 KiB
Factor
Raw Normal View History

! Copyright (C) 2005, 2009 Slava Pestov.
2007-09-20 18:09:08 -04:00
! See http://factorcode.org/license.txt for BSD license.
2008-05-15 00:23:12 -04:00
USING: kernel continuations destructors io io.encodings
io.encodings.private io.timeouts io.ports io.styles summary
accessors delegate delegate.protocols ;
2007-09-20 18:09:08 -04:00
IN: io.streams.duplex
2008-05-15 00:23:12 -04:00
TUPLE: duplex-stream in out ;
2007-09-20 18:09:08 -04:00
2008-05-15 00:23:12 -04:00
C: <duplex-stream> duplex-stream
2007-09-20 18:09:08 -04:00
2008-05-15 00:23:12 -04:00
CONSULT: input-stream-protocol duplex-stream in>> ;
CONSULT: output-stream-protocol duplex-stream out>> ;
CONSULT: formatted-output-stream-protocol duplex-stream out>> ;
INSTANCE: duplex-stream input-stream
INSTANCE: duplex-stream output-stream
: >duplex-stream< ( stream -- in out ) [ in>> ] [ out>> ] bi ; inline
2009-03-15 18:11:18 -04:00
M: duplex-stream stream-element-type
[ in>> ] [ out>> ] bi
[ stream-element-type ] bi@
2dup eq? [ drop ] [ "Cannot determine element type" throw ] if ;
M: duplex-stream set-timeout
>duplex-stream< [ set-timeout ] bi-curry@ bi ;
M: duplex-stream dispose
2007-09-20 18:09:08 -04:00
#! The output stream is closed first, in case both streams
#! are attached to the same file descriptor, the output
#! buffer needs to be flushed before we close the fd.
[ >duplex-stream< [ &dispose drop ] bi@ ] with-destructors ;
: <encoder-duplex> ( stream-in stream-out encoding -- duplex )
[ re-decode ] [ re-encode ] bi-curry bi* <duplex-stream> ;
: with-stream* ( stream quot -- )
[ >duplex-stream< ] dip with-streams* ; inline
: with-stream ( stream quot -- )
[ >duplex-stream< ] dip with-streams ; inline
ERROR: invalid-duplex-stream ;
M: duplex-stream underlying-handle
>duplex-stream<
[ underlying-handle ] bi@
[ = [ invalid-duplex-stream ] when ] keep ;