factor/extra/io/streams/duplex/duplex.factor

57 lines
1.6 KiB
Factor
Raw Normal View History

2008-04-13 01:21:48 -04:00
! Copyright (C) 2005, 2008 Slava Pestov.
2007-09-20 18:09:08 -04:00
! See http://factorcode.org/license.txt for BSD license.
USING: kernel continuations io io.encodings io.encodings.private
2008-05-05 04:51:41 -04:00
io.timeouts debugger inspector listener accessors delegate
delegate.protocols ;
2007-09-20 18:09:08 -04:00
IN: io.streams.duplex
! We ensure that the stream can only be closed once, to preserve
! integrity of duplex I/O ports.
2008-04-13 01:21:48 -04:00
TUPLE: duplex-stream in out closed ;
2007-09-20 18:09:08 -04:00
: <duplex-stream> ( in out -- stream )
f duplex-stream boa ;
2007-09-20 18:09:08 -04:00
2008-03-20 16:00:49 -04:00
ERROR: stream-closed-twice ;
2007-09-20 18:09:08 -04:00
M: stream-closed-twice summary
drop "Attempt to perform I/O on closed stream" ;
2008-04-13 04:22:51 -04:00
<PRIVATE
2008-04-13 01:21:48 -04:00
: check-closed ( stream -- stream )
dup closed>> [ stream-closed-twice ] when ; inline
: in ( duplex -- stream ) check-closed in>> ;
2007-09-20 18:09:08 -04:00
2008-04-13 01:21:48 -04:00
: out ( duplex -- stream ) check-closed out>> ;
2007-09-20 18:09:08 -04:00
2008-04-13 01:21:48 -04:00
PRIVATE>
2007-09-20 18:09:08 -04:00
2008-05-05 04:51:41 -04:00
CONSULT: input-stream-protocol duplex-stream in ;
2007-09-20 18:09:08 -04:00
2008-05-05 04:51:41 -04:00
CONSULT: output-stream-protocol duplex-stream out ;
M: duplex-stream set-timeout
[ in set-timeout ] [ out set-timeout ] 2bi ;
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.
2008-04-13 01:21:48 -04:00
dup closed>> [
t >>closed
[ dup out>> dispose ]
[ dup in>> dispose ] [ ] cleanup
2007-09-20 18:09:08 -04:00
] unless drop ;
: <encoder-duplex> ( stream-in stream-out encoding -- duplex )
tuck re-encode >r re-decode r> <duplex-stream> ;
: with-stream* ( stream quot -- )
>r [ in>> ] [ out>> ] bi r> with-streams* ; inline
: with-stream ( stream quot -- )
>r [ in>> ] [ out>> ] bi r> with-streams ; inline