1 ! Copyright (C) 2009 Daniel Ehrenberg
2 ! See http://factorcode.org/license.txt for BSD license.
3 USING: accessors byte-arrays classes combinators destructors
4 growable io io.private io.streams.plain kernel math math.order
5 sequences sequences.private strings ;
6 IN: io.streams.sequence
12 : >sequence-stream< ( stream -- i underlying )
13 [ i>> ] [ underlying>> ] bi ; inline
15 : sequence-read1 ( stream -- elt/f )
16 dup >sequence-stream< dupd ?nth [ 1 + swap i<< ] dip ; inline
20 : (sequence-read-length) ( n buf stream -- buf count )
21 [ underlying>> length ] [ i>> ] bi - rot min ; inline
23 : <sequence-copy> ( dst n src-i src dst-i -- n copy )
24 [ ] curry 3curry dip <copier> ; inline
26 : sequence-copy-unsafe ( n buf stream offset -- count )
28 [ (sequence-read-length) ]
29 [ [ dup pick + ] change-i underlying>> ] bi
30 ] dip [ <sequence-copy> (copy) drop ] 3curry keep ; inline
32 : (sequence-read-unsafe) ( n buf stream -- count )
34 [ dup slice? [ [ seq>> ] [ from>> ] bi ] [ 0 ] if ]
36 tuck stream-element-type +byte+ eq?
37 [ [ byte-array check-instance ] 2dip sequence-copy-unsafe ]
38 [ [ string check-instance ] 2dip sequence-copy-unsafe ] if
43 : sequence-read-unsafe ( n buf stream -- count )
44 dup >sequence-stream< bounds-check?
45 [ (sequence-read-unsafe) ] [ 3drop 0 ] if ; inline
49 : find-separator ( seps stream -- sep/f n )
50 >sequence-stream< rot [ member? ] curry
51 [ find-from swap ] curry 2keep pick
52 [ drop - ] [ length swap - nip ] if ; inline
54 : (sequence-read-until) ( seps stream -- seq sep/f )
55 [ find-separator ] keep
56 [ [ (sequence-read-unsafe) ] (read-into-new) ]
57 [ [ 1 + ] change-i drop ]
58 [ stream-exemplar or ] tri swap ; inline
62 : sequence-read-until ( seps stream -- seq sep/f )
63 dup >sequence-stream< bounds-check?
64 [ (sequence-read-until) ] [ 2drop f f ] if ; inline
67 M: growable dispose drop ;
69 M: growable stream-write1 push ;
70 M: growable stream-write push-all ;
71 M: growable stream-flush drop ;
73 INSTANCE: growable output-stream
74 INSTANCE: growable plain-writer
77 : sequence-seek ( n seek-type stream -- )
79 { seek-absolute [ i<< ] }
80 { seek-relative [ [ + ] change-i drop ] }
81 { seek-end [ [ underlying>> length + ] [ i<< ] bi ] }