]> gitweb.factorcode.org Git - factor.git/blob - extra/io/streams/limited/limited.factor
Merge branch 'master' of git://factorcode.org/git/factor
[factor.git] / extra / io / streams / limited / limited.factor
1 ! Copyright (C) 2008 Slava Pestov
2 ! See http://factorcode.org/license.txt for BSD license.
3 USING: kernel math io io.encodings destructors accessors
4 sequences namespaces ;
5 IN: io.streams.limited
6
7 TUPLE: limited-stream stream count limit ;
8
9 : <limited-stream> ( stream limit -- stream' )
10     limited-stream new
11         swap >>limit
12         swap >>stream
13         0 >>count ;
14
15 GENERIC# limit 1 ( stream limit -- stream' )
16
17 M: decoder limit [ clone ] dip [ limit ] curry change-stream ;
18
19 M: object limit <limited-stream> ;
20
21 : limit-input ( limit -- ) input-stream [ swap limit ] change ;
22
23 ERROR: limit-exceeded ;
24
25 : check-limit ( n stream -- )
26     [ + ] change-count
27     [ count>> ] [ limit>> ] bi >=
28     [ limit-exceeded ] when ; inline
29
30 M: limited-stream stream-read1
31     1 over check-limit stream>> stream-read1 ;
32
33 M: limited-stream stream-read
34     2dup check-limit stream>> stream-read ;
35
36 M: limited-stream stream-read-partial
37     2dup check-limit stream>> stream-read-partial ;
38
39 : (read-until) ( stream seps buf -- stream seps buf sep/f )
40     3dup [ [ stream-read1 dup ] dip memq? ] dip
41     swap [ drop ] [ push (read-until) ] if ;
42
43 M: limited-stream stream-read-until
44     swap BV{ } clone (read-until) [ 2nip B{ } like ] dip ;
45
46 M: limited-stream dispose
47     stream>> dispose ;