]> gitweb.factorcode.org Git - factor.git/blob - core/io/streams/string/string.factor
Fix permission bits
[factor.git] / core / io / streams / string / string.factor
1 ! Copyright (C) 2003, 2008 Slava Pestov.
2 ! See http://factorcode.org/license.txt for BSD license.
3 USING: accessors io kernel math namespaces sequences sbufs
4 strings generic splitting continuations destructors
5 io.streams.plain io.encodings math.order growable ;
6 IN: io.streams.string
7
8 M: growable dispose drop ;
9
10 M: growable stream-write1 push ;
11 M: growable stream-write push-all ;
12 M: growable stream-flush drop ;
13
14 : <string-writer> ( -- stream )
15     512 <sbuf> ;
16
17 : with-string-writer ( quot -- str )
18     <string-writer> swap [ output-stream get ] compose with-output-stream*
19     >string ; inline
20
21 M: growable stream-read1 [ f ] [ pop ] if-empty ;
22
23 : harden-as ( seq growble-exemplar -- newseq )
24     underlying>> like ;
25
26 : growable-read-until ( growable n -- str )
27     >fixnum dupd tail-slice swap harden-as dup reverse-here ;
28
29 : find-last-sep ( seq seps -- n )
30     swap [ memq? ] curry find-last drop ;
31
32 M: growable stream-read-until
33     [ find-last-sep ] keep over [
34         [ swap 1+ growable-read-until ] 2keep [ nth ] 2keep
35         set-length
36     ] [
37         [ swap drop 0 growable-read-until f like f ] keep
38         delete-all
39     ] if ;
40
41 M: growable stream-read
42     [
43         drop f
44     ] [
45         [ length swap - 0 max ] keep
46         [ swap growable-read-until ] 2keep
47         set-length
48     ] if-empty ;
49
50 M: growable stream-read-partial
51     stream-read ;
52
53 SINGLETON: null
54 M: null decode-char drop stream-read1 ;
55
56 : <string-reader> ( str -- stream )
57     >sbuf dup reverse-here null <decoder> ;
58
59 : with-string-reader ( str quot -- )
60     >r <string-reader> r> with-input-stream ; inline
61
62 INSTANCE: growable plain-writer
63
64 : format-column ( seq ? -- seq )
65     [
66         [ 0 [ length max ] reduce ] keep
67         swap [ CHAR: \s pad-right ] curry map
68     ] unless ;
69
70 : map-last ( seq quot -- seq )
71     >r dup length <reversed> [ zero? ] r> compose 2map ; inline
72
73 : format-table ( table -- seq )
74     flip [ format-column ] map-last
75     flip [ " " join ] map ;
76
77 M: plain-writer stream-write-table
78     [ drop format-table [ print ] each ] with-output-stream* ;
79
80 M: plain-writer make-cell-stream 2drop <string-writer> ;