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
16 cell 4 = [ 0b11000 ] [ 0b111000 ] if
17 bitxor ] unless ; inline
19 : <select-mx> ( -- mx )
21 FD_SETSIZE 8 * <bit-array> >>read-fdset
22 FD_SETSIZE 8 * <bit-array> >>write-fdset ;
24 : clear-nth ( n seq -- ? )
25 [ nth ] [ [ f ] 2dip set-nth ] 2bi ;
27 :: check-fd ( fd fdset mx quot -- )
28 fd munge fdset clear-nth [ fd mx quot call ] when ; inline
30 : check-fdset ( fds fdset mx quot -- )
31 [ check-fd ] 3curry each ; inline
33 : init-fdset ( fds fdset -- )
34 '[ t swap munge _ set-nth ] each ;
36 : read-fdset/tasks ( mx -- seq fdset )
37 [ reads>> keys ] [ read-fdset>> ] bi ;
39 : write-fdset/tasks ( mx -- seq fdset )
40 [ writes>> keys ] [ write-fdset>> ] bi ;
42 : max-fd ( assoc -- n )
43 dup assoc-empty? [ drop 0 ] [ keys supremum ] if ;
46 [ reads>> max-fd ] [ writes>> max-fd ] bi max 1 + ;
48 : init-fdsets ( mx -- nfds read write except )
50 [ read-fdset/tasks [ init-fdset ] keep ]
51 [ write-fdset/tasks [ init-fdset ] keep ] tri
54 M:: select-mx wait-for-events ( nanos mx -- )
56 [ init-fdsets nanos dup [ 1000 /i make-timeval ] when select multiplexer-error drop ]
57 [ [ read-fdset/tasks ] keep [ input-available ] check-fdset ]
58 [ [ write-fdset/tasks ] keep [ output-available ] check-fdset ]