1 ! Copyright (C) 2004, 2010 Slava Pestov.
2 ! See http://factorcode.org/license.txt for BSD license.
3 USING: alien alien.strings kernel kernel.private namespaces make
4 io io.encodings sequences math generic threads.private classes
5 io.backend io.files io.encodings.utf8 continuations destructors
6 byte-arrays accessors combinators ;
9 TUPLE: c-stream < disposable handle ;
11 : new-c-stream ( handle class -- c-stream )
12 new-disposable swap >>handle ; inline
14 M: c-stream dispose* handle>> fclose ;
16 TUPLE: c-writer < c-stream ;
17 INSTANCE: c-writer output-stream
19 : <c-writer> ( handle -- stream ) c-writer new-c-stream ;
21 M: c-writer stream-element-type drop +byte+ ;
23 M: c-writer stream-write1 dup check-disposed handle>> fputc ;
25 M: c-writer stream-write
27 [ [ >c-ptr ] [ byte-length ] bi ] [ handle>> ] bi* fwrite ;
29 M: c-writer stream-flush dup check-disposed handle>> fflush ;
31 TUPLE: c-reader < c-stream ;
32 INSTANCE: c-reader input-stream
34 : <c-reader> ( handle -- stream ) c-reader new-c-stream ;
36 M: c-reader stream-element-type drop +byte+ ;
38 M: c-reader stream-read-unsafe dup check-disposed handle>> fread-unsafe ;
40 M: c-reader stream-read1 dup check-disposed handle>> fgetc ;
42 : read-until-loop ( stream delim -- ch )
43 over stream-read1 dup [
44 dup pick member-eq? [ 2nip ] [ , read-until-loop ] if
49 M: c-reader stream-read-until
51 [ swap read-until-loop ] B{ } make swap
52 over empty? over not and [ 2drop f f ] when ;
54 M: c-io-backend init-io ;
56 : stdin-handle ( -- alien ) 11 special-object ;
57 : stdout-handle ( -- alien ) 12 special-object ;
58 : stderr-handle ( -- alien ) 63 special-object ;
61 stdin-handle <c-reader>
62 stdout-handle <c-writer>
63 stderr-handle <c-writer>
66 M: c-io-backend init-stdio init-c-stdio ;
68 M: c-io-backend io-multiplex
69 dup 0 = [ drop ] [ 60 60 * 1000 * 1000 * or (sleep) ] if ;
71 : fopen ( path mode -- alien )
72 [ utf8 string>alien ] bi@ (fopen) ;
74 M: c-io-backend (file-reader)
75 "rb" fopen <c-reader> ;
77 M: c-io-backend (file-writer)
78 "wb" fopen <c-writer> ;
80 M: c-io-backend (file-appender)
81 "ab" fopen <c-writer> ;
84 #! A word which directly calls primitives. It is used to
85 #! print stuff from contexts where the I/O system would
86 #! otherwise not work (tools.deploy.shaker, the I/O
87 #! multiplexer thread).
88 "\n" append >byte-array dup length
90 stdout-handle fflush ;