29501ee582174bb3538f19bfb5066b27dbe85ec2
[nit.git] / lib / standard / stream.nit
1 # This file is part of NIT ( http://www.nitlanguage.org ).
2 #
3 # Copyright 2004-2008 Jean Privat <jean@pryen.org>
4 #
5 # This file is free software, which comes along with NIT. This software is
6 # distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
7 # without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
8 # PARTICULAR PURPOSE. You can modify it is you want, provided this header
9 # is kept unaltered, and a notification of the changes is added.
10 # You are allowed to redistribute it and sell it, alone or is a part of
11 # another product.
12
13 # Input and output streams of characters
14 module stream
15
16 import string
17
18 in "C" `{
19 #include <unistd.h>
20 #include <poll.h>
21 #include <errno.h>
22 #include <string.h>
23 `}
24
25 # Abstract stream class
26 interface IOS
27 # close the stream
28 fun close is abstract
29 end
30
31 # Abstract input streams
32 interface IStream
33 super IOS
34 # Read a character. Return its ASCII value, -1 on EOF or timeout
35 fun read_char: Int is abstract
36
37 # Read at most i bytes
38 fun read(i: Int): String
39 do
40 var s = new FlatBuffer.with_capacity(i)
41 while i > 0 and not eof do
42 var c = read_char
43 if c >= 0 then
44 s.add(c.ascii)
45 i -= 1
46 end
47 end
48 return s.to_s
49 end
50
51 # Read a string until the end of the line.
52 fun read_line: String
53 do
54 assert not eof
55 var s = new FlatBuffer
56 append_line_to(s)
57 return s.to_s
58 end
59
60 # Read all the stream until the eof.
61 fun read_all: String
62 do
63 var s = new FlatBuffer
64 while not eof do
65 var c = read_char
66 if c >= 0 then s.add(c.ascii)
67 end
68 return s.to_s
69 end
70
71 # Read a string until the end of the line and append it to `s`.
72 fun append_line_to(s: Buffer)
73 do
74 loop
75 var x = read_char
76 if x == -1 then
77 if eof then return
78 else
79 var c = x.ascii
80 s.chars.push(c)
81 if c == '\n' then return
82 end
83 end
84 end
85
86 # Is there something to read.
87 # This function returns 'false' if there is something to read.
88 fun eof: Bool is abstract
89 end
90
91 # IStream capable of declaring if readable without blocking
92 interface PollableIStream
93 super IStream
94
95 # Is there something to read? (without blocking)
96 fun poll_in: Bool is abstract
97
98 end
99
100 # Abstract output stream
101 interface OStream
102 super IOS
103 # write a string
104 fun write(s: Text) is abstract
105
106 # Can the stream be used to write
107 fun is_writable: Bool is abstract
108 end
109
110 # Things that can be efficienlty writen to a OStream
111 #
112 # The point of this interface it to allow is instance to be efficenty
113 # writen into a OStream without having to allocate a big String object
114 #
115 # ready-to-save documents usually provide this interface.
116 interface Streamable
117 # Write itself to a `stream`
118 # The specific logic it let to the concrete subclasses
119 fun write_to(stream: OStream) is abstract
120
121 # Like `write_to` but return a new String (may be quite large)
122 #
123 # This funtionnality is anectodical, since the point
124 # of streamable object to to be efficienlty written to a
125 # stream without having to allocate and concatenate strings
126 fun write_to_string: String
127 do
128 var stream = new StringOStream
129 write_to(stream)
130 return stream.to_s
131 end
132 end
133
134 redef class Text
135 super Streamable
136 redef fun write_to(stream) do stream.write(self)
137 end
138
139 # Input streams with a buffer
140 abstract class BufferedIStream
141 super IStream
142 redef fun read_char
143 do
144 assert not eof
145 if _buffer_pos >= _buffer.length then
146 fill_buffer
147 end
148 if _buffer_pos >= _buffer.length then
149 return -1
150 end
151 var c = _buffer.chars[_buffer_pos]
152 _buffer_pos += 1
153 return c.ascii
154 end
155
156 redef fun read(i)
157 do
158 var s = new FlatBuffer.with_capacity(i)
159 var j = _buffer_pos
160 var k = _buffer.length
161 while i > 0 do
162 if j >= k then
163 fill_buffer
164 if eof then return s.to_s
165 j = _buffer_pos
166 k = _buffer.length
167 end
168 while j < k and i > 0 do
169 s.add(_buffer.chars[j])
170 j += 1
171 i -= 1
172 end
173 end
174 _buffer_pos = j
175 return s.to_s
176 end
177
178 redef fun read_all
179 do
180 var s = new FlatBuffer
181 while not eof do
182 var j = _buffer_pos
183 var k = _buffer.length
184 while j < k do
185 s.add(_buffer.chars[j])
186 j += 1
187 end
188 _buffer_pos = j
189 fill_buffer
190 end
191 return s.to_s
192 end
193
194 redef fun append_line_to(s)
195 do
196 loop
197 # First phase: look for a '\n'
198 var i = _buffer_pos
199 while i < _buffer.length and _buffer.chars[i] != '\n' do i += 1
200
201 # if there is something to append
202 if i > _buffer_pos then
203 # Enlarge the string (if needed)
204 s.enlarge(s.length + i - _buffer_pos)
205
206 # Copy from the buffer to the string
207 var j = _buffer_pos
208 while j < i do
209 s.add(_buffer.chars[j])
210 j += 1
211 end
212 end
213
214 if i < _buffer.length then
215 # so \n is in _buffer[i]
216 _buffer_pos = i + 1 # skip \n
217 return
218 else
219 # so \n is not found
220 _buffer_pos = i
221 if end_reached then
222 return
223 else
224 fill_buffer
225 end
226 end
227 end
228 end
229
230 redef fun eof do return _buffer_pos >= _buffer.length and end_reached
231
232 # The buffer
233 var _buffer: nullable FlatBuffer = null
234
235 # The current position in the buffer
236 var _buffer_pos: Int = 0
237
238 # Fill the buffer
239 protected fun fill_buffer is abstract
240
241 # Is the last fill_buffer reach the end
242 protected fun end_reached: Bool is abstract
243
244 # Allocate a `_buffer` for a given `capacity`.
245 protected fun prepare_buffer(capacity: Int)
246 do
247 _buffer = new FlatBuffer.with_capacity(capacity)
248 _buffer_pos = 0 # need to read
249 end
250 end
251
252 interface IOStream
253 super IStream
254 super OStream
255 end
256
257 ##############################################################"
258
259 abstract class FDStream
260 super IOS
261 # File description
262 var fd: Int
263
264 redef fun close do native_close(fd)
265
266 private fun native_close(i: Int): Int is extern "stream_FDStream_FDStream_native_close_1"
267 private fun native_read_char(i: Int): Int is extern "stream_FDStream_FDStream_native_read_char_1"
268 private fun native_read(i: Int, buf: NativeString, len: Int): Int is extern "stream_FDStream_FDStream_native_read_3"
269 private fun native_write(i: Int, buf: NativeString, len: Int): Int is extern "stream_FDStream_FDStream_native_write_3"
270 private fun native_write_char(i: Int, c: Char): Int is extern "stream_FDStream_FDStream_native_write_char_2"
271
272 init(fd: Int) do self.fd = fd
273 end
274
275 class FDIStream
276 super FDStream
277 super IStream
278 redef var eof: Bool = false
279
280 redef fun read_char
281 do
282 var nb = native_read_char(fd)
283 if nb == -1 then eof = true
284 return nb
285 end
286
287 init(fd: Int) do end
288 end
289
290 class FDOStream
291 super FDStream
292 super OStream
293 redef var is_writable: Bool
294
295 redef fun write(s)
296 do
297 var nb = native_write(fd, s.to_cstring, s.length)
298 if nb < s.length then is_writable = false
299 end
300
301 init(fd: Int)
302 do
303 is_writable = true
304 end
305 end
306
307 class FDIOStream
308 super FDIStream
309 super FDOStream
310 super IOStream
311 init(fd: Int)
312 do
313 self.fd = fd
314 is_writable = true
315 end
316 end
317
318 redef interface Object
319 # returns first available stream to read or write to
320 # return null on interruption (possibly a signal)
321 protected fun poll( streams : Sequence[FDStream] ) : nullable FDStream
322 do
323 var in_fds = new Array[Int]
324 var out_fds = new Array[Int]
325 var fd_to_stream = new HashMap[Int,FDStream]
326 for s in streams do
327 var fd = s.fd
328 if s isa FDIStream then in_fds.add( fd )
329 if s isa FDOStream then out_fds.add( fd )
330
331 fd_to_stream[fd] = s
332 end
333
334 var polled_fd = intern_poll( in_fds, out_fds )
335
336 if polled_fd == null then
337 return null
338 else
339 return fd_to_stream[polled_fd]
340 end
341 end
342
343 private fun intern_poll(in_fds: Array[Int], out_fds: Array[Int]) : nullable Int is extern import Array[Int].length, Array[Int].[], Int.as(nullable Int) `{
344 int in_len, out_len, total_len;
345 struct pollfd *c_fds;
346 sigset_t sigmask;
347 int i;
348 int first_polled_fd = -1;
349 int result;
350
351 in_len = Array_of_Int_length( in_fds );
352 out_len = Array_of_Int_length( out_fds );
353 total_len = in_len + out_len;
354 c_fds = malloc( sizeof(struct pollfd) * total_len );
355
356 /* input streams */
357 for ( i=0; i<in_len; i ++ ) {
358 int fd;
359 fd = Array_of_Int__index( in_fds, i );
360
361 c_fds[i].fd = fd;
362 c_fds[i].events = POLLIN;
363 }
364
365 /* output streams */
366 for ( i=0; i<out_len; i ++ ) {
367 int fd;
368 fd = Array_of_Int__index( out_fds, i );
369
370 c_fds[i].fd = fd;
371 c_fds[i].events = POLLOUT;
372 }
373
374 /* poll all fds, unlimited timeout */
375 result = poll( c_fds, total_len, -1 );
376
377 if ( result > 0 ) {
378 /* analyse results */
379 for ( i=0; i<total_len; i++ )
380 if ( c_fds[i].revents & c_fds[i].events || /* awaited event */
381 c_fds[i].revents & POLLHUP ) /* closed */
382 {
383 first_polled_fd = c_fds[i].fd;
384 break;
385 }
386
387 return Int_as_nullable( first_polled_fd );
388 }
389 else if ( result < 0 )
390 fprintf( stderr, "Error in Stream:poll: %s\n", strerror( errno ) );
391
392 return null_Int();
393 `}
394 end
395
396 # Stream to a String. Mainly used for compatibility with OStream type and tests.
397 class StringOStream
398 super OStream
399
400 private var content = new Array[String]
401 redef fun to_s do return content.to_s
402 redef fun is_writable do return true
403 redef fun write(str) do content.add(str.to_s)
404 end