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 byte-vectors
4 destructors io io.backend io.encodings.utf8 io.files kernel
5 kernel.private 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
22 check-disposed handle>> fputc ;
24 M: c-writer stream-write
26 [ binary-object ] [ handle>> ] bi* fwrite ;
28 M: c-writer stream-flush
29 check-disposed handle>> fflush ;
31 TUPLE: c-reader < c-stream ;
32 INSTANCE: c-reader input-stream
33 INSTANCE: c-reader file-reader
35 : <c-reader> ( handle -- stream ) c-reader new-c-stream ;
37 M: c-reader stream-read-unsafe
38 check-disposed handle>> fread-unsafe ;
40 M: c-reader stream-read1
41 check-disposed handle>> fgetc ;
43 : read-until-loop ( handle seps accum -- accum ch )
46 [ [ 2drop ] 2dip ] [ suffix! read-until-loop ] if
49 ] if ; inline recursive
51 M: c-reader stream-read-until
52 check-disposed handle>> swap
53 32 <byte-vector> read-until-loop [ B{ } like ] dip
54 over empty? over not and [ 2drop f f ] when ;
56 M: c-io-backend init-io ;
58 : stdin-handle ( -- alien ) OBJ-STDIN special-object ;
59 : stdout-handle ( -- alien ) OBJ-STDOUT special-object ;
60 : stderr-handle ( -- alien ) OBJ-STDERR special-object ;
63 stdin-handle <c-reader>
64 stdout-handle <c-writer>
65 stderr-handle <c-writer>
68 M: c-io-backend init-stdio init-c-stdio ;
70 M: c-io-backend io-multiplex
71 dup 0 = [ drop ] [ 60 60 * 1000 * 1000 * or (sleep) ] if ;
73 : fopen ( path mode -- alien )
74 [ utf8 string>alien ] bi@ (fopen) ;
76 M: c-io-backend (file-reader)
77 "rb" fopen <c-reader> ;
79 M: c-io-backend (file-writer)
80 "wb" fopen <c-writer> ;
82 M: c-io-backend (file-appender)
83 "ab" fopen <c-writer> ;
86 #! A word which directly calls primitives. It is used to
87 #! print stuff from contexts where the I/O system would
88 #! otherwise not work (tools.deploy.shaker, the I/O
89 #! multiplexer thread).
90 "\n" append >byte-array dup length
92 stdout-handle fflush ;