]> gitweb.factorcode.org Git - factor.git/blob - core/io/streams/c/c.factor
vm: dispatch signal handlers through subprimitive
[factor.git] / core / io / streams / c / c.factor
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 ;
7 IN: io.streams.c
8
9 TUPLE: c-stream < disposable handle ;
10
11 : new-c-stream ( handle class -- c-stream )
12     new-disposable swap >>handle ; inline
13
14 M: c-stream dispose* handle>> fclose ;
15
16 TUPLE: c-writer < c-stream ;
17 INSTANCE: c-writer output-stream
18
19 : <c-writer> ( handle -- stream ) c-writer new-c-stream ;
20
21 M: c-writer stream-element-type drop +byte+ ;
22
23 M: c-writer stream-write1 dup check-disposed handle>> fputc ;
24
25 M: c-writer stream-write
26     dup check-disposed
27     [ [ >c-ptr ] [ byte-length ] bi ] [ handle>> ] bi* fwrite ;
28
29 M: c-writer stream-flush dup check-disposed handle>> fflush ;
30
31 TUPLE: c-reader < c-stream ;
32 INSTANCE: c-reader input-stream
33
34 : <c-reader> ( handle -- stream ) c-reader new-c-stream ;
35
36 M: c-reader stream-element-type drop +byte+ ;
37
38 M: c-reader stream-read-unsafe dup check-disposed handle>> fread-unsafe ;
39
40 M: c-reader stream-read1 dup check-disposed handle>> fgetc ;
41
42 : read-until-loop ( stream delim -- ch )
43     over stream-read1 dup [
44         dup pick member-eq? [ 2nip ] [ , read-until-loop ] if
45     ] [
46         2nip
47     ] if ;
48
49 M: c-reader stream-read-until
50     dup check-disposed
51     [ swap read-until-loop ] B{ } make swap
52     over empty? over not and [ 2drop f f ] when ;
53
54 M: c-io-backend init-io ;
55
56 : stdin-handle ( -- alien ) 11 special-object ;
57 : stdout-handle ( -- alien ) 12 special-object ;
58 : stderr-handle ( -- alien ) 63 special-object ;
59
60 : init-c-stdio ( -- )
61     stdin-handle <c-reader>
62     stdout-handle <c-writer>
63     stderr-handle <c-writer>
64     set-stdio ;
65
66 M: c-io-backend init-stdio init-c-stdio ;
67
68 M: c-io-backend io-multiplex
69     dup 0 = [ drop ] [ 60 60 * 1000 * 1000 * or (sleep) ] if ;
70
71 : fopen ( path mode -- alien )
72     [ utf8 string>alien ] bi@ (fopen) ;
73
74 M: c-io-backend (file-reader)
75     "rb" fopen <c-reader> ;
76
77 M: c-io-backend (file-writer)
78     "wb" fopen <c-writer> ;
79
80 M: c-io-backend (file-appender)
81     "ab" fopen <c-writer> ;
82
83 : show ( msg -- )
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
89     stdout-handle fwrite
90     stdout-handle fflush ;