|
3 | 3 |
|
4 | 4 |
|
5 | 5 | (def fopen (ffi-fn libc "fopen" [CCharP CCharP] CVoidP)) |
| 6 | +(def fseek (ffi-fn libc "fseek" [CVoidP CInt CInt] CInt)) |
| 7 | +(def ftell (ffi-fn libc "ftell" [CVoidP] CInt)) |
| 8 | +(def -rewind (ffi-fn libc "rewind" [CVoidP] CVoidP)) |
6 | 9 | (def fread (ffi-fn libc "fread" [CVoidP CInt CInt CVoidP] CInt)) |
7 | 10 | (def fgetc (ffi-fn libc "fgetc" [CVoidP] CInt)) |
8 | 11 | (def fputc (ffi-fn libc "fputc" [CInt CVoidP] CInt)) |
|
15 | 18 |
|
16 | 19 | (def DEFAULT-BUFFER-SIZE 1024) |
17 | 20 |
|
| 21 | +(defn default-stream-reducer [this f init] |
| 22 | + (let [buf (buffer DEFAULT-BUFFER-SIZE) |
| 23 | + rrf (preserving-reduced f)] |
| 24 | + (loop [acc init] |
| 25 | + (let [read-count (read this buf DEFAULT-BUFFER-SIZE)] |
| 26 | + (if (> read-count 0) |
| 27 | + (let [result (reduce rrf acc buf)] |
| 28 | + (if (not (reduced? result)) |
| 29 | + (recur result) |
| 30 | + @result)) |
| 31 | + acc))))) |
| 32 | + |
18 | 33 | (deftype FileStream [fp] |
19 | 34 | IInputStream |
20 | 35 | (read [this buffer len] |
|
25 | 40 | read-count)) |
26 | 41 | (read-byte [this] |
27 | 42 | (fgetc buffer)) |
| 43 | + ISeekableStream |
| 44 | + (seek [this pos] |
| 45 | + (fseek fp pos 0)) |
| 46 | + (rewind [this] |
| 47 | + (-rewind fp)) |
28 | 48 | IDisposable |
29 | 49 | (-dispose! [this] |
30 | 50 | (fclose fp)) |
31 | 51 | IReduce |
32 | 52 | (-reduce [this f init] |
33 | | - (let [buf (buffer DEFAULT-BUFFER-SIZE) |
34 | | - rrf (preserving-reduced f)] |
35 | | - (loop [acc init] |
36 | | - (let [read-count (read this buf DEFAULT-BUFFER-SIZE)] |
37 | | - (if (> read-count 0) |
38 | | - (let [result (reduce rrf acc buf)] |
39 | | - (if (not (reduced? result)) |
40 | | - (recur result) |
41 | | - @result)) |
42 | | - acc)))))) |
| 53 | + (default-stream-reducer this f init))) |
43 | 54 |
|
44 | 55 | (defn open-read |
45 | 56 | {:doc "Open a file for reading, returning a IInputStream" |
|
109 | 120 | (dispose! c) |
110 | 121 | result)) |
111 | 122 |
|
| 123 | +(defn slurp-stream [stream] |
| 124 | + (let [c stream |
| 125 | + result (transduce |
| 126 | + (map char) |
| 127 | + string-builder |
| 128 | + c)] |
| 129 | + (dispose! c) |
| 130 | + result)) |
| 131 | + |
112 | 132 | (deftype ProcessInputStream [fp] |
113 | 133 | IInputStream |
114 | 134 | (read [this buffer len] |
|
124 | 144 | (pclose fp)) |
125 | 145 | IReduce |
126 | 146 | (-reduce [this f init] |
127 | | - (let [buf (buffer DEFAULT-BUFFER-SIZE) |
128 | | - rrf (preserving-reduced f)] |
129 | | - (loop [acc init] |
130 | | - (let [read-count (read this buf DEFAULT-BUFFER-SIZE)] |
131 | | - (if (> read-count 0) |
132 | | - (let [result (reduce rrf acc buf)] |
133 | | - (if (not (reduced? result)) |
134 | | - (recur result) |
135 | | - @result)) |
136 | | - acc)))))) |
| 147 | + (default-stream-reducer this f init))) |
137 | 148 |
|
138 | 149 |
|
139 | 150 | (defn popen-read |
|
0 commit comments