]> gitweb.factorcode.org Git - factor.git/blob - basis/io/backend/unix/multiplexers/select/select.factor
use radix literals
[factor.git] / basis / io / backend / unix / multiplexers / select / select.factor
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
6 unix.time layouts ;
7 IN: io.backend.unix.multiplexers.select
8
9 TUPLE: select-mx < mx read-fdset write-fdset ;
10
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
14 : munge ( i -- i' )
15     little-endian? [
16       cell 4 = [ 0b11000 ] [ 0b111000 ] if
17       bitxor ] unless ; inline
18
19 : <select-mx> ( -- mx )
20     select-mx new-mx
21         FD_SETSIZE 8 * <bit-array> >>read-fdset
22         FD_SETSIZE 8 * <bit-array> >>write-fdset ;
23
24 : clear-nth ( n seq -- ? )
25     [ nth ] [ [ f ] 2dip set-nth ] 2bi ;
26
27 :: check-fd ( fd fdset mx quot -- )
28     fd munge fdset clear-nth [ fd mx quot call ] when ; inline
29
30 : check-fdset ( fds fdset mx quot -- )
31     [ check-fd ] 3curry each ; inline
32
33 : init-fdset ( fds fdset -- )
34     '[ t swap munge _ set-nth ] each ;
35
36 : read-fdset/tasks ( mx -- seq fdset )
37     [ reads>> keys ] [ read-fdset>> ] bi ;
38
39 : write-fdset/tasks ( mx -- seq fdset )
40     [ writes>> keys ] [ write-fdset>> ] bi ;
41
42 : max-fd ( assoc -- n )
43     dup assoc-empty? [ drop 0 ] [ keys supremum ] if ;
44
45 : num-fds ( mx -- n )
46     [ reads>> max-fd ] [ writes>> max-fd ] bi max 1 + ;
47
48 : init-fdsets ( mx -- nfds read write except )
49     [ num-fds ]
50     [ read-fdset/tasks [ init-fdset ] keep ]
51     [ write-fdset/tasks [ init-fdset ] keep ] tri
52     f ;
53
54 M:: select-mx wait-for-events ( nanos mx -- )
55     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 ]
59     tri ;