1 # This file is part of NIT ( http://www.nitlanguage.org ).
3 # This file is free software, which comes along with NIT. This software is
4 # distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
5 # without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
6 # PARTICULAR PURPOSE. You can modify it is you want, provided this header
7 # is kept unaltered, and a notification of the changes is added.
8 # You are allowed to redistribute it and sell it, alone or is a part of
11 # Input and output streams of characters
24 # Abstract stream class
30 # Abstract input streams
33 # Read a character. Return its ASCII value, -1 on EOF or timeout
34 fun read_char
: Int is abstract
36 # Read at most i bytes
37 fun read
(i
: Int): String
39 var s
= new FlatBuffer.with_capacity
(i
)
40 while i
> 0 and not eof
do
50 # Read a string until the end of the line.
52 # The line terminator '\n', if any, is preserved in each line.
53 # Use the method `Text::chomp` to safely remove it.
56 # var txt = "Hello\n\nWorld\n"
57 # var i = new StringIStream(txt)
58 # assert i.read_line == "Hello\n"
59 # assert i.read_line == "\n"
60 # assert i.read_line == "World\n"
64 # If `\n` is not present at the end of the result, it means that
65 # a non-eol terminated last line was returned.
68 # var i2 = new StringIStream("hello")
70 # assert i2.read_line == "hello"
74 # NOTE: Only LINE FEED (`\n`) is considered to delimit the end of lines.
78 var s
= new FlatBuffer
83 # Read all the lines until the eof.
85 # The line terminator '\n' is removed in each line,
88 # var txt = "Hello\n\nWorld\n"
89 # var i = new StringIStream(txt)
90 # assert i.read_lines == ["Hello", "", "World"]
93 # This method is more efficient that splitting
94 # the result of `read_all`.
96 # NOTE: Only LINE FEED (`\n`) is considered to delimit the end of lines.
97 fun read_lines
: Array[String]
99 var res
= new Array[String]
101 res
.add read_line
.chomp
106 # Read all the stream until the eof.
109 var s
= new FlatBuffer
112 if c
>= 0 then s
.add
(c
.ascii
)
117 # Read a string until the end of the line and append it to `s`.
119 # SEE: `read_line` for details.
120 fun append_line_to
(s
: Buffer)
129 if c
== '\n' then return
134 # Is there something to read.
135 # This function returns 'false' if there is something to read.
136 fun eof
: Bool is abstract
139 # IStream capable of declaring if readable without blocking
140 interface PollableIStream
143 # Is there something to read? (without blocking)
144 fun poll_in
: Bool is abstract
148 # Abstract output stream
152 fun write
(s
: Text) is abstract
154 # Can the stream be used to write
155 fun is_writable
: Bool is abstract
158 # Things that can be efficienlty writen to a OStream
160 # The point of this interface it to allow is instance to be efficenty
161 # writen into a OStream without having to allocate a big String object
163 # ready-to-save documents usually provide this interface.
165 # Write itself to a `stream`
166 # The specific logic it let to the concrete subclasses
167 fun write_to
(stream
: OStream) is abstract
169 # Like `write_to` but return a new String (may be quite large)
171 # This funtionnality is anectodical, since the point
172 # of streamable object to to be efficienlty written to a
173 # stream without having to allocate and concatenate strings
174 fun write_to_string
: String
176 var stream
= new StringOStream
184 redef fun write_to
(stream
) do stream
.write
(self)
187 # Input streams with a buffer
188 abstract class BufferedIStream
193 if _buffer_pos
>= _buffer
.length
then
196 if _buffer_pos
>= _buffer
.length
then
199 var c
= _buffer
.chars
[_buffer_pos
]
206 if _buffer
.length
== _buffer_pos
then
213 if _buffer_pos
+ i
>= _buffer
.length
then
214 var from
= _buffer_pos
215 _buffer_pos
= _buffer
.length
216 return _buffer
.substring_from
(from
).to_s
219 return _buffer
.substring
(_buffer_pos
- i
, i
).to_s
224 var s
= new FlatBuffer
227 var k
= _buffer
.length
238 redef fun append_line_to
(s
)
241 # First phase: look for a '\n'
243 while i
< _buffer
.length
and _buffer
.chars
[i
] != '\n' do i
+= 1
245 # if there is something to append
246 if i
> _buffer_pos
then
247 # Enlarge the string (if needed)
248 s
.enlarge
(s
.length
+ i
- _buffer_pos
)
250 # Copy from the buffer to the string
253 s
.add
(_buffer
.chars
[j
])
258 if i
< _buffer
.length
then
259 # so \n is in _buffer[i]
260 _buffer_pos
= i
+ 1 # skip \n
274 redef fun eof
do return _buffer_pos
>= _buffer
.length
and end_reached
277 private var buffer
: nullable FlatBuffer = null
279 # The current position in the buffer
280 private var buffer_pos
: Int = 0
283 protected fun fill_buffer
is abstract
285 # Is the last fill_buffer reach the end
286 protected fun end_reached
: Bool is abstract
288 # Allocate a `_buffer` for a given `capacity`.
289 protected fun prepare_buffer
(capacity
: Int)
291 _buffer
= new FlatBuffer.with_capacity
(capacity
)
292 _buffer_pos
= 0 # need to read
296 # An Input/Output Stream
302 ##############################################################"
304 # A File Descriptor Stream.
305 abstract class FDStream
310 redef fun close
do native_close
(fd
)
312 private fun native_close
(i
: Int): Int is extern "stream_FDStream_FDStream_native_close_1"
313 private fun native_read_char
(i
: Int): Int is extern "stream_FDStream_FDStream_native_read_char_1"
314 private fun native_read
(i
: Int, buf
: NativeString, len
: Int): Int is extern "stream_FDStream_FDStream_native_read_3"
315 private fun native_write
(i
: Int, buf
: NativeString, len
: Int): Int is extern "stream_FDStream_FDStream_native_write_3"
316 private fun native_write_char
(i
: Int, c
: Char): Int is extern "stream_FDStream_FDStream_native_write_char_2"
319 # An Input File Descriptor Stream.
323 redef var eof
: Bool = false
327 var nb
= native_read_char
(fd
)
328 if nb
== -1 then eof
= true
333 # An Output File Descriptor Stream.
337 redef var is_writable
= true
341 var nb
= native_write
(fd
, s
.to_cstring
, s
.length
)
342 if nb
< s
.length
then is_writable
= false
346 # An Input/Output File Descriptor Stream.
353 redef interface Object
354 # returns first available stream to read or write to
355 # return null on interruption (possibly a signal)
356 protected fun poll
( streams
: Sequence[FDStream] ) : nullable FDStream
358 var in_fds
= new Array[Int]
359 var out_fds
= new Array[Int]
360 var fd_to_stream
= new HashMap[Int,FDStream]
363 if s
isa FDIStream then in_fds
.add
( fd
)
364 if s
isa FDOStream then out_fds
.add
( fd
)
369 var polled_fd
= intern_poll
( in_fds
, out_fds
)
371 if polled_fd
== null then
374 return fd_to_stream
[polled_fd
]
378 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) `{
379 int in_len, out_len, total_len;
380 struct pollfd *c_fds;
383 int first_polled_fd = -1;
386 in_len = Array_of_Int_length( in_fds );
387 out_len = Array_of_Int_length( out_fds );
388 total_len = in_len + out_len;
389 c_fds = malloc( sizeof(struct pollfd) * total_len );
392 for ( i=0; i<in_len; i ++ ) {
394 fd = Array_of_Int__index( in_fds, i );
397 c_fds[i].events = POLLIN;
401 for ( i=0; i<out_len; i ++ ) {
403 fd = Array_of_Int__index( out_fds, i );
406 c_fds[i].events = POLLOUT;
409 /* poll all fds, unlimited timeout */
410 result = poll( c_fds, total_len, -1 );
413 /* analyse results */
414 for ( i=0; i<total_len; i++ )
415 if ( c_fds[i].revents & c_fds[i].events || /* awaited event */
416 c_fds[i].revents & POLLHUP ) /* closed */
418 first_polled_fd = c_fds[i].fd;
422 return Int_as_nullable( first_polled_fd );
424 else if ( result < 0 )
425 fprintf( stderr, "Error in Stream:poll: %s\n", strerror( errno ) );
431 # Stream to a String.
433 # Mainly used for compatibility with OStream type and tests.
437 private var content
= new Array[String]
438 redef fun to_s
do return content
.to_s
439 redef fun is_writable
do return not closed
443 content
.add
(str
.to_s
)
446 # Is the stream closed?
447 protected var closed
= false
449 redef fun close
do closed
= true
452 # Stream from a String.
454 # Mainly used for compatibility with IStream type and tests.
458 # The string to read from.
461 # The current position in the string.
462 private var cursor
: Int = 0
464 redef fun read_char
do
465 if cursor
< source
.length
then
466 var c
= source
[cursor
].ascii
479 redef fun eof
do return cursor
>= source
.length