factor/basis/io/streams/string/string.factor

68 lines
1.6 KiB
Factor
Raw Normal View History

! Copyright (C) 2003, 2009 Slava Pestov.
2007-09-20 18:09:08 -04:00
! See http://factorcode.org/license.txt for BSD license.
USING: accessors io kernel math namespaces sequences sbufs
strings generic splitting continuations destructors
io.streams.plain io.encodings math.order growable ;
2008-03-14 04:09:51 -04:00
IN: io.streams.string
<PRIVATE
: harden-as ( seq growble-exemplar -- newseq )
underlying>> like ;
: growable-read-until ( growable n -- str )
>fixnum dupd tail-slice swap harden-as dup reverse-here ;
SINGLETON: null-encoding
M: null-encoding decode-char drop stream-read1 ;
PRIVATE>
2008-02-15 22:49:53 -05:00
M: growable dispose drop ;
2007-09-20 18:09:08 -04:00
2008-02-15 22:49:53 -05:00
M: growable stream-write1 push ;
M: growable stream-write push-all ;
M: growable stream-flush drop ;
2007-09-20 18:09:08 -04:00
: <string-writer> ( -- stream )
2008-02-21 16:22:49 -05:00
512 <sbuf> ;
2007-09-20 18:09:08 -04:00
: with-string-writer ( quot -- str )
<string-writer> swap [ output-stream get ] compose with-output-stream*
2008-02-15 22:49:53 -05:00
>string ; inline
2008-09-06 18:10:32 -04:00
M: growable stream-read1 [ f ] [ pop ] if-empty ;
2007-09-20 18:09:08 -04:00
2008-06-08 16:32:55 -04:00
: find-last-sep ( seq seps -- n )
swap [ memq? ] curry find-last drop ;
2007-09-20 18:09:08 -04:00
2008-02-15 22:49:53 -05:00
M: growable stream-read-until
2007-09-20 18:09:08 -04:00
[ find-last-sep ] keep over [
[ swap 1+ growable-read-until ] 2keep [ nth ] 2keep
2007-09-20 18:09:08 -04:00
set-length
] [
[ swap drop 0 growable-read-until f like f ] keep
2007-09-20 18:09:08 -04:00
delete-all
] if ;
2008-02-15 22:49:53 -05:00
M: growable stream-read
2008-09-06 18:10:32 -04:00
[
drop f
2007-09-20 18:09:08 -04:00
] [
[ length swap - 0 max ] keep
[ swap growable-read-until ] 2keep
2007-09-20 18:09:08 -04:00
set-length
2008-09-06 18:10:32 -04:00
] if-empty ;
2007-09-20 18:09:08 -04:00
2008-02-15 22:49:53 -05:00
M: growable stream-read-partial
2007-09-20 18:09:08 -04:00
stream-read ;
: <string-reader> ( str -- stream )
>sbuf dup reverse-here null-encoding <decoder> ;
2007-09-20 18:09:08 -04:00
: with-string-reader ( str quot -- )
[ <string-reader> ] dip with-input-stream ; inline
2008-02-21 16:22:49 -05:00
INSTANCE: growable plain-writer