1 ! Copyright (C) 2004, 2008 Slava Pestov.
2 ! See http://factorcode.org/license.txt for BSD license.
3 USING: alien.data kernel bit-arrays sequences assocs math
4 namespaces accessors math.order locals fry io.ports
5 io.backend.unix io.backend.unix.multiplexers unix unix.ffi
7 IN: io.backend.unix.multiplexers.select
9 TUPLE: select-mx < mx read-fdset write-fdset ;
11 ! Factor's bit-arrays are an array of bytes, OS X expects
12 ! FD_SET to be an array of cells, so we have to account for
13 ! byte order differences on big endian platforms
15 little-endian? [ BIN: 11000 bitxor ] unless ; inline
17 : <select-mx> ( -- mx )
19 FD_SETSIZE 8 * <bit-array> >>read-fdset
20 FD_SETSIZE 8 * <bit-array> >>write-fdset ;
22 : clear-nth ( n seq -- ? )
23 [ nth ] [ [ f ] 2dip set-nth ] 2bi ;
25 :: check-fd ( fd fdset mx quot -- )
26 fd munge fdset clear-nth [ fd mx quot call ] when ; inline
28 : check-fdset ( fds fdset mx quot -- )
29 [ check-fd ] 3curry each ; inline
31 : init-fdset ( fds fdset -- )
32 '[ t swap munge _ set-nth ] each ;
34 : read-fdset/tasks ( mx -- seq fdset )
35 [ reads>> keys ] [ read-fdset>> ] bi ;
37 : write-fdset/tasks ( mx -- seq fdset )
38 [ writes>> keys ] [ write-fdset>> ] bi ;
40 : max-fd ( assoc -- n )
41 dup assoc-empty? [ drop 0 ] [ keys supremum ] if ;
44 [ reads>> max-fd ] [ writes>> max-fd ] bi max 1 + ;
46 : init-fdsets ( mx -- nfds read write except )
48 [ read-fdset/tasks [ init-fdset ] keep ]
49 [ write-fdset/tasks [ init-fdset ] keep ] tri
52 M:: select-mx wait-for-events ( nanos mx -- )
54 [ init-fdsets nanos dup [ 1000 /i make-timeval ] when select multiplexer-error drop ]
55 [ [ read-fdset/tasks ] keep [ input-available ] check-fdset ]
56 [ [ write-fdset/tasks ] keep [ output-available ] check-fdset ]