1 ! Copyright (C) 2004, 2010 Slava Pestov.
2 ! See http://factorcode.org/license.txt for BSD license.
3 USING: accessors alien alien.strings byte-arrays destructors io
4 io.backend io.encodings.utf8 io.files kernel kernel.private
5 make math sequences threads.private ;
8 TUPLE: c-stream < disposable handle ;
10 : new-c-stream ( handle class -- c-stream )
11 new-disposable swap >>handle ; inline
13 M: c-stream dispose* handle>> fclose ;
15 TUPLE: c-writer < c-stream ;
16 INSTANCE: c-writer output-stream
17 INSTANCE: c-writer file-writer
19 : <c-writer> ( handle -- stream ) c-writer new-c-stream ;
21 M: c-writer stream-write1 dup check-disposed handle>> fputc ;
23 M: c-writer stream-write
25 [ [ >c-ptr ] [ byte-length ] bi ] [ handle>> ] bi* fwrite ;
27 M: c-writer stream-flush dup check-disposed handle>> fflush ;
29 TUPLE: c-reader < c-stream ;
30 INSTANCE: c-reader input-stream
31 INSTANCE: c-reader file-reader
33 : <c-reader> ( handle -- stream ) c-reader new-c-stream ;
35 M: c-reader stream-read-unsafe dup check-disposed handle>> fread-unsafe ;
37 M: c-reader stream-read1 dup check-disposed handle>> fgetc ;
39 : read-until-loop ( stream delim -- ch )
40 over stream-read1 dup [
41 dup pick member-eq? [ 2nip ] [ , read-until-loop ] if
44 ] if ; inline recursive
46 M: c-reader stream-read-until
48 [ swap read-until-loop ] B{ } make swap
49 over empty? over not and [ 2drop f f ] when ;
51 M: c-io-backend init-io ;
53 : stdin-handle ( -- alien ) OBJ-STDIN special-object ;
54 : stdout-handle ( -- alien ) OBJ-STDOUT special-object ;
55 : stderr-handle ( -- alien ) OBJ-STDERR special-object ;
58 stdin-handle <c-reader>
59 stdout-handle <c-writer>
60 stderr-handle <c-writer>
63 M: c-io-backend init-stdio init-c-stdio ;
65 M: c-io-backend io-multiplex
66 dup 0 = [ drop ] [ 60 60 * 1000 * 1000 * or (sleep) ] if ;
68 : fopen ( path mode -- alien )
69 [ utf8 string>alien ] bi@ (fopen) ;
71 M: c-io-backend (file-reader)
72 "rb" fopen <c-reader> ;
74 M: c-io-backend (file-writer)
75 "wb" fopen <c-writer> ;
77 M: c-io-backend (file-appender)
78 "ab" fopen <c-writer> ;
81 #! A word which directly calls primitives. It is used to
82 #! print stuff from contexts where the I/O system would
83 #! otherwise not work (tools.deploy.shaker, the I/O
84 #! multiplexer thread).
85 "\n" append >byte-array dup length
87 stdout-handle fflush ;