factor/library/io/string-streams.factor

49 lines
1.4 KiB
Factor
Raw Normal View History

! Copyright (C) 2003, 2005 Slava Pestov.
! See http://factor.sf.net/license.txt for BSD license.
IN: io
2005-06-19 18:31:02 -04:00
USING: io kernel math namespaces sequences strings ;
! String buffers support the stream output protocol.
M: sbuf stream-write1 push ;
2005-12-16 21:12:35 -05:00
M: sbuf stream-write swap nappend ;
2005-06-19 18:31:02 -04:00
M: sbuf stream-close drop ;
M: sbuf stream-flush drop ;
2005-12-16 21:12:35 -05:00
: <string-writer> ( -- stream )
512 <sbuf> <plain-writer> ;
2005-06-19 18:31:02 -04:00
: string-out ( quot -- str )
<string-writer> [ call stdio get >string ] with-stream* ;
inline
2005-06-19 18:31:02 -04:00
2006-06-07 23:04:37 -04:00
: format-column ( seq -- seq )
[ 0 [ length max ] reduce ] keep
[ swap CHAR: \s pad-right ] map-with ;
M: plain-writer with-stream-table ( quot grid stream -- )
-rot [ [ swap string-out ] map-with ] map-with
flip [ format-column ] map flip [ " " join ] map
[ swap stream-print ] each-with ;
2005-06-19 18:31:02 -04:00
! Reversed string buffers support the stream input protocol.
M: sbuf stream-read1 ( sbuf -- char/f )
2005-09-24 15:21:17 -04:00
dup empty? [ drop f ] [ pop ] if ;
2005-06-19 18:31:02 -04:00
M: sbuf stream-read ( count sbuf -- string )
dup empty? [
2drop f
] [
swap over length min 0 <string>
[ [ drop dup pop ] inject drop ] keep
2005-09-24 15:21:17 -04:00
] if ;
2005-06-19 18:31:02 -04:00
: <string-reader> ( string -- stream )
2005-07-16 22:16:18 -04:00
<reversed> >sbuf <line-reader> ;
2005-06-19 18:31:02 -04:00
: string-in ( str quot -- )
2005-12-16 21:12:35 -05:00
>r <string-reader> r> with-stream ; inline
: contents ( stream -- string )
#! Read the entire stream into a string.
<string-writer> [ stream-copy ] keep >string ;