factor/extra/io/pipes/pipes.factor

57 lines
1.6 KiB
Factor
Raw Normal View History

! Copyright (C) 2008 Slava Pestov.
! See http://factorcode.org/license.txt for BSD license.
USING: io.encodings io.backend io.nonblocking io.streams.duplex
io splitting sequences sequences.lib namespaces kernel
2008-05-05 04:15:24 -04:00
destructors math concurrency.combinators accessors
arrays continuations quotations ;
IN: io.pipes
TUPLE: pipe in out ;
2008-05-05 03:32:35 -04:00
M: pipe dispose ( pipe -- )
[ in>> close-handle ] [ out>> close-handle ] bi ;
HOOK: (pipe) io-backend ( -- pipe )
2008-05-05 04:15:24 -04:00
: <pipe> ( encoding -- stream )
[
2008-05-05 04:15:24 -04:00
>r (pipe)
2008-05-05 03:32:35 -04:00
[ add-error-destructor ]
2008-05-05 04:15:24 -04:00
[ in>> <reader> ]
[ out>> <writer> ]
2008-05-05 03:32:35 -04:00
tri
2008-05-05 04:15:24 -04:00
r> <encoder-duplex>
] with-destructors ;
2008-05-05 04:15:24 -04:00
: with-fds ( input-fd output-fd quot -- )
>r >r [ <reader> dup add-always-destructor ] [ input-stream get ] if* r> r> [
>r [ <writer> dup add-always-destructor ] [ output-stream get ] if* r>
with-output-stream*
] 2curry with-input-stream* ; inline
: <pipes> ( n -- pipes )
2008-05-05 04:15:24 -04:00
[ (pipe) dup add-always-destructor ] replicate
2008-05-05 03:32:35 -04:00
f f pipe boa [ prefix ] [ suffix ] bi
2008-05-05 18:31:46 -04:00
2 <clumps> ;
: with-pipe-fds ( seq -- results )
[
[ length dup zero? [ drop { } ] [ 1- <pipes> ] if ] keep
[ >r [ first in>> ] [ second out>> ] bi r> 2curry ] 2map
[ call ] parallel-map
] with-destructors ;
2008-05-05 04:15:24 -04:00
GENERIC: pipeline-element-quot ( obj -- quot )
M: callable pipeline-element-quot
[ with-fds ] curry ;
GENERIC: wait-for-pipeline-element ( obj -- result )
M: object wait-for-pipeline-element ;
: with-pipeline ( seq -- results )
[ pipeline-element-quot ] map
with-pipe-fds
[ wait-for-pipeline-element ] map ;