Merge: nitg: add support for unary - as an extern method
[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 if _buffer.length == _buffer_pos then
159 if not eof then
160 fill_buffer
161 return read(i)
162 end
163 return ""
164 end
165 if _buffer_pos + i >= _buffer.length then
166 var from = _buffer_pos
167 _buffer_pos = _buffer.length
168 return _buffer.substring_from(from).to_s
169 end
170 _buffer_pos += i
171 return _buffer.substring(_buffer_pos - i, i).to_s
172 end
173
174 redef fun read_all
175 do
176 var s = new FlatBuffer
177 while not eof do
178 var j = _buffer_pos
179 var k = _buffer.length
180 while j < k do
181 s.add(_buffer.chars[j])
182 j += 1
183 end
184 _buffer_pos = j
185 fill_buffer
186 end
187 return s.to_s
188 end
189
190 redef fun append_line_to(s)
191 do
192 loop
193 # First phase: look for a '\n'
194 var i = _buffer_pos
195 while i < _buffer.length and _buffer.chars[i] != '\n' do i += 1
196
197 # if there is something to append
198 if i > _buffer_pos then
199 # Enlarge the string (if needed)
200 s.enlarge(s.length + i - _buffer_pos)
201
202 # Copy from the buffer to the string
203 var j = _buffer_pos
204 while j < i do
205 s.add(_buffer.chars[j])
206 j += 1
207 end
208 end
209
210 if i < _buffer.length then
211 # so \n is in _buffer[i]
212 _buffer_pos = i + 1 # skip \n
213 return
214 else
215 # so \n is not found
216 _buffer_pos = i
217 if end_reached then
218 return
219 else
220 fill_buffer
221 end
222 end
223 end
224 end
225
226 redef fun eof do return _buffer_pos >= _buffer.length and end_reached
227
228 # The buffer
229 var _buffer: nullable FlatBuffer = null
230
231 # The current position in the buffer
232 var _buffer_pos: Int = 0
233
234 # Fill the buffer
235 protected fun fill_buffer is abstract
236
237 # Is the last fill_buffer reach the end
238 protected fun end_reached: Bool is abstract
239
240 # Allocate a `_buffer` for a given `capacity`.
241 protected fun prepare_buffer(capacity: Int)
242 do
243 _buffer = new FlatBuffer.with_capacity(capacity)
244 _buffer_pos = 0 # need to read
245 end
246 end
247
248 interface IOStream
249 super IStream
250 super OStream
251 end
252
253 ##############################################################"
254
255 abstract class FDStream
256 super IOS
257 # File description
258 var fd: Int
259
260 redef fun close do native_close(fd)
261
262 private fun native_close(i: Int): Int is extern "stream_FDStream_FDStream_native_close_1"
263 private fun native_read_char(i: Int): Int is extern "stream_FDStream_FDStream_native_read_char_1"
264 private fun native_read(i: Int, buf: NativeString, len: Int): Int is extern "stream_FDStream_FDStream_native_read_3"
265 private fun native_write(i: Int, buf: NativeString, len: Int): Int is extern "stream_FDStream_FDStream_native_write_3"
266 private fun native_write_char(i: Int, c: Char): Int is extern "stream_FDStream_FDStream_native_write_char_2"
267
268 init(fd: Int) do self.fd = fd
269 end
270
271 class FDIStream
272 super FDStream
273 super IStream
274 redef var eof: Bool = false
275
276 redef fun read_char
277 do
278 var nb = native_read_char(fd)
279 if nb == -1 then eof = true
280 return nb
281 end
282
283 init(fd: Int) do end
284 end
285
286 class FDOStream
287 super FDStream
288 super OStream
289 redef var is_writable: Bool
290
291 redef fun write(s)
292 do
293 var nb = native_write(fd, s.to_cstring, s.length)
294 if nb < s.length then is_writable = false
295 end
296
297 init(fd: Int)
298 do
299 is_writable = true
300 end
301 end
302
303 class FDIOStream
304 super FDIStream
305 super FDOStream
306 super IOStream
307 init(fd: Int)
308 do
309 self.fd = fd
310 is_writable = true
311 end
312 end
313
314 redef interface Object
315 # returns first available stream to read or write to
316 # return null on interruption (possibly a signal)
317 protected fun poll( streams : Sequence[FDStream] ) : nullable FDStream
318 do
319 var in_fds = new Array[Int]
320 var out_fds = new Array[Int]
321 var fd_to_stream = new HashMap[Int,FDStream]
322 for s in streams do
323 var fd = s.fd
324 if s isa FDIStream then in_fds.add( fd )
325 if s isa FDOStream then out_fds.add( fd )
326
327 fd_to_stream[fd] = s
328 end
329
330 var polled_fd = intern_poll( in_fds, out_fds )
331
332 if polled_fd == null then
333 return null
334 else
335 return fd_to_stream[polled_fd]
336 end
337 end
338
339 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) `{
340 int in_len, out_len, total_len;
341 struct pollfd *c_fds;
342 sigset_t sigmask;
343 int i;
344 int first_polled_fd = -1;
345 int result;
346
347 in_len = Array_of_Int_length( in_fds );
348 out_len = Array_of_Int_length( out_fds );
349 total_len = in_len + out_len;
350 c_fds = malloc( sizeof(struct pollfd) * total_len );
351
352 /* input streams */
353 for ( i=0; i<in_len; i ++ ) {
354 int fd;
355 fd = Array_of_Int__index( in_fds, i );
356
357 c_fds[i].fd = fd;
358 c_fds[i].events = POLLIN;
359 }
360
361 /* output streams */
362 for ( i=0; i<out_len; i ++ ) {
363 int fd;
364 fd = Array_of_Int__index( out_fds, i );
365
366 c_fds[i].fd = fd;
367 c_fds[i].events = POLLOUT;
368 }
369
370 /* poll all fds, unlimited timeout */
371 result = poll( c_fds, total_len, -1 );
372
373 if ( result > 0 ) {
374 /* analyse results */
375 for ( i=0; i<total_len; i++ )
376 if ( c_fds[i].revents & c_fds[i].events || /* awaited event */
377 c_fds[i].revents & POLLHUP ) /* closed */
378 {
379 first_polled_fd = c_fds[i].fd;
380 break;
381 }
382
383 return Int_as_nullable( first_polled_fd );
384 }
385 else if ( result < 0 )
386 fprintf( stderr, "Error in Stream:poll: %s\n", strerror( errno ) );
387
388 return null_Int();
389 `}
390 end
391
392 # Stream to a String. Mainly used for compatibility with OStream type and tests.
393 class StringOStream
394 super OStream
395
396 private var content = new Array[String]
397 redef fun to_s do return content.to_s
398 redef fun is_writable do return true
399 redef fun write(str) do content.add(str.to_s)
400 end