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 byte-vectors ;
7 TUPLE: limited-stream stream count limit ;
9 : <limited-stream> ( stream limit -- stream' )
15 GENERIC# limit 1 ( stream limit -- stream' )
17 M: decoder limit [ clone ] dip [ limit ] curry change-stream ;
19 M: object limit <limited-stream> ;
21 : limit-input ( limit -- ) input-stream [ swap limit ] change ;
23 ERROR: limit-exceeded ;
25 : check-limit ( n stream -- )
27 [ count>> ] [ limit>> ] bi >=
28 [ limit-exceeded ] when ; inline
30 M: limited-stream stream-read1
31 1 over check-limit stream>> stream-read1 ;
33 M: limited-stream stream-read
34 2dup check-limit stream>> stream-read ;
36 M: limited-stream stream-read-partial
37 2dup check-limit stream>> stream-read-partial ;
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 ;
43 M: limited-stream stream-read-until
44 swap BV{ } clone (read-until) [ 2nip B{ } like ] dip ;
46 M: limited-stream dispose