1 ! Copyright (C) 2008 Slava Pestov.
2 ! See http://factorcode.org/license.txt for BSD license.
3 USING: accessors kernel arrays namespaces sequences continuations
4 destructors io.sockets alien alien.syntax ;
7 TUPLE: pool connections disposed expired ;
9 : check-pool ( pool -- )
11 dup expired>> expired? [
12 31337 <alien> >>expired
13 connections>> delete-all
16 : <pool> ( class -- pool )
19 dup check-pool ; inline
21 M: pool dispose* connections>> dispose-each ;
23 : with-pool ( pool quot -- )
24 [ pool swap with-variable ] curry with-disposal ; inline
26 TUPLE: return-connection conn pool ;
28 : return-connection ( conn pool -- )
29 dup check-pool connections>> push ;
31 GENERIC: make-connection ( pool -- conn )
33 : new-connection ( pool -- )
34 dup check-pool [ make-connection ] keep return-connection ;
36 : acquire-connection ( pool -- conn )
38 [ dup connections>> empty? ] [ dup new-connection ] [ ] while
41 : (with-pooled-connection) ( conn pool quot -- )
42 [ nip call ] [ drop return-connection ] 3bi ; inline
44 : with-pooled-connection ( pool quot -- )
45 [ [ acquire-connection ] keep ] dip
46 [ (with-pooled-connection) ] [ ] [ 2drop dispose ] cleanup ; inline
48 M: return-connection dispose
49 [ conn>> ] [ pool>> ] bi return-connection ;
51 : return-connection-later ( db pool -- )
52 \ return-connection boa &dispose drop ;
54 TUPLE: datagram-pool < pool addrspec ;
56 : <datagram-pool> ( addrspec -- pool )
57 datagram-pool <pool> swap >>addrspec ;
59 M: datagram-pool make-connection addrspec>> <datagram> ;