1 ! Copyright (C) 2009 Daniel Ehrenberg
2 ! See https://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-unsafe ( n buf stream offset -- count )
25 [ (sequence-read-length) ]
26 [ [ dup pick + ] change-i underlying>> ] bi
27 ] dip [ -roll spin dupd + copy-loop drop ] 3curry keep ; inline
29 : (sequence-read-unsafe) ( n buf stream -- count )
31 [ dup slice? [ [ seq>> ] [ from>> ] bi ] [ 0 ] if ]
33 tuck stream-element-type +byte+ eq?
34 [ [ byte-array check-instance ] 2dip sequence-copy-unsafe ]
35 [ [ string check-instance ] 2dip sequence-copy-unsafe ] if
40 : sequence-read-unsafe ( n buf stream -- count )
41 dup >sequence-stream< bounds-check?
42 [ (sequence-read-unsafe) ] [ 3drop 0 ] if ; inline
46 : find-separator ( seps stream -- sep/f n )
47 >sequence-stream< rot [ member? ] curry
48 [ find-from swap ] curry 2keep pick
49 [ drop - ] [ length swap - nip ] if ; inline
51 : (sequence-read-until) ( seps stream -- seq sep/f )
52 [ find-separator ] keep
53 [ [ (sequence-read-unsafe) ] (read-into-new) ]
54 [ [ 1 + ] change-i drop ]
55 [ stream-exemplar or ] tri swap ; inline
59 : sequence-read-until ( seps stream -- seq sep/f )
60 dup >sequence-stream< bounds-check?
61 [ (sequence-read-until) ] [ 2drop f f ] if ; inline
64 M: growable dispose drop ;
66 M: growable stream-write1 push ;
67 M: growable stream-write push-all ;
68 M: growable stream-flush drop ;
70 INSTANCE: growable output-stream
71 INSTANCE: growable plain-writer
74 : sequence-seek ( n seek-type stream -- )
76 { seek-absolute [ i<< ] }
77 { seek-relative [ [ + ] change-i drop ] }
78 { seek-end [ [ underlying>> length + ] [ i<< ] bi ] }