]> gitweb.factorcode.org Git - factor.git/blob - core/io/io.factor
Merge branch 'master' into experimental
[factor.git] / core / io / io.factor
1 ! Copyright (C) 2003, 2009 Slava Pestov.
2 ! See http://factorcode.org/license.txt for BSD license.
3 USING: hashtables generic kernel math namespaces make sequences
4 continuations destructors assocs ;
5 IN: io
6
7 GENERIC: stream-read1 ( stream -- elt )
8 GENERIC: stream-read ( n stream -- seq )
9 GENERIC: stream-read-until ( seps stream -- seq sep/f )
10 GENERIC: stream-read-partial ( n stream -- seq )
11 GENERIC: stream-readln ( stream -- str/f )
12
13 GENERIC: stream-write1 ( elt stream -- )
14 GENERIC: stream-write ( seq stream -- )
15 GENERIC: stream-flush ( stream -- )
16 GENERIC: stream-nl ( stream -- )
17
18 : stream-print ( str stream -- ) [ stream-write ] keep stream-nl ;
19
20 ! Default streams
21 SYMBOL: input-stream
22 SYMBOL: output-stream
23 SYMBOL: error-stream
24
25 : readln ( -- str/f ) input-stream get stream-readln ;
26 : read1 ( -- elt ) input-stream get stream-read1 ;
27 : read ( n -- seq ) input-stream get stream-read ;
28 : read-until ( seps -- seq sep/f ) input-stream get stream-read-until ;
29 : read-partial ( n -- seq ) input-stream get stream-read-partial ;
30
31 : write1 ( elt -- ) output-stream get stream-write1 ;
32 : write ( seq -- ) output-stream get stream-write ;
33 : flush ( -- ) output-stream get stream-flush ;
34
35 : nl ( -- ) output-stream get stream-nl ;
36
37 : with-input-stream* ( stream quot -- )
38     input-stream swap with-variable ; inline
39
40 : with-input-stream ( stream quot -- )
41     [ with-input-stream* ] curry with-disposal ; inline
42
43 : with-output-stream* ( stream quot -- )
44     output-stream swap with-variable ; inline
45
46 : with-output-stream ( stream quot -- )
47     [ with-output-stream* ] curry with-disposal ; inline
48
49 : with-streams* ( input output quot -- )
50     [ output-stream set input-stream set ] prepose with-scope ; inline
51
52 : with-streams ( input output quot -- )
53     [ [ with-streams* ] 3curry ]
54     [ [ drop dispose dispose ] 3curry ] 3bi
55     [ ] cleanup ; inline
56
57 : print ( str -- ) output-stream get stream-print ;
58
59 : bl ( -- ) " " write ;
60
61 : lines ( stream -- seq )
62     [ [ readln dup ] [ ] [ drop ] produce ] with-input-stream ;
63
64 <PRIVATE
65
66 : each-morsel ( handler: ( data -- ) reader: ( -- data ) -- )
67     [ dup ] compose swap [ drop ] while ; inline
68
69 PRIVATE>
70
71 : each-line ( quot -- )
72     [ readln ] each-morsel ; inline
73
74 : contents ( stream -- seq )
75     [
76         [ 65536 read-partial dup ]
77         [ ] [ drop ] produce concat f like
78     ] with-input-stream ;
79
80 : each-block ( quot: ( block -- ) -- )
81     [ 8192 read-partial ] each-morsel ; inline
82
83 : stream-copy ( in out -- )
84     [ [ [ write ] each-block ] with-output-stream ]
85     curry with-input-stream ;