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
23 # Any kind of error that could be produced by an operation on Streams
28 # Any kind of stream to read/write/both to or from a source
30 # Error produced by the file stream
32 # var ifs = new FileReader.open("donotmakethisfile.binx")
35 # assert ifs.last_error != null
36 var last_error
: nullable IOError = null
42 # A `Stream` that can be read from
45 # Read a character. Return its ASCII value, -1 on EOF or timeout
46 fun read_char
: Int is abstract
48 # Read at most i bytes
49 fun read
(i
: Int): String
51 if last_error
!= null then return ""
52 var s
= new FlatBuffer.with_capacity
(i
)
53 while i
> 0 and not eof
do
63 # Read a string until the end of the line.
65 # The line terminator '\n' and '\r\n', if any, is removed in each line.
68 # var txt = "Hello\n\nWorld\n"
69 # var i = new StringReader(txt)
70 # assert i.read_line == "Hello"
71 # assert i.read_line == ""
72 # assert i.read_line == "World"
76 # Only LINE FEED (`\n`), CARRIAGE RETURN & LINE FEED (`\r\n`), and
77 # the end or file (EOF) is considered to delimit the end of lines.
78 # CARRIAGE RETURN (`\r`) alone is not used for the end of line.
81 # var txt2 = "Hello\r\n\n\rWorld"
82 # var i2 = new StringReader(txt2)
83 # assert i2.read_line == "Hello"
84 # assert i2.read_line == ""
85 # assert i2.read_line == "\rWorld"
89 # NOTE: Use `append_line_to` if the line terminator needs to be preserved.
92 if last_error
!= null then return ""
94 var s
= new FlatBuffer
99 # Read all the lines until the eof.
101 # The line terminator '\n' and `\r\n` is removed in each line,
104 # var txt = "Hello\n\nWorld\n"
105 # var i = new StringReader(txt)
106 # assert i.read_lines == ["Hello", "", "World"]
109 # This method is more efficient that splitting
110 # the result of `read_all`.
112 # NOTE: SEE `read_line` for details.
113 fun read_lines
: Array[String]
115 var res
= new Array[String]
122 # Return an iterator that read each line.
124 # The line terminator '\n' and `\r\n` is removed in each line,
125 # The line are read with `read_line`. See this method for details.
128 # var txt = "Hello\n\nWorld\n"
129 # var i = new StringReader(txt)
130 # assert i.each_line.to_a == ["Hello", "", "World"]
133 # Unlike `read_lines` that read all lines at the call, `each_line` is lazy.
134 # Therefore, the stream should no be closed until the end of the stream.
137 # i = new StringReader(txt)
138 # var el = i.each_line
140 # assert el.item == "Hello"
142 # assert el.item == ""
147 # assert not el.is_ok
148 # # closed before "world" is read
150 fun each_line
: LineIterator do return new LineIterator(self)
152 # Read all the stream until the eof.
154 # The content of the file is returned verbatim.
157 # var txt = "Hello\n\nWorld\n"
158 # var i = new StringReader(txt)
159 # assert i.read_all == txt
163 if last_error
!= null then return ""
164 var s
= new FlatBuffer
167 if c
>= 0 then s
.add
(c
.ascii
)
172 # Read a string until the end of the line and append it to `s`.
174 # Unlike `read_line` and other related methods,
175 # the line terminator '\n', if any, is preserved in each line.
176 # Use the method `Text::chomp` to safely remove it.
179 # var txt = "Hello\n\nWorld\n"
180 # var i = new StringReader(txt)
181 # var b = new FlatBuffer
182 # i.append_line_to(b)
183 # assert b == "Hello\n"
184 # i.append_line_to(b)
185 # assert b == "Hello\n\n"
186 # i.append_line_to(b)
191 # If `\n` is not present at the end of the result, it means that
192 # a non-eol terminated last line was returned.
195 # var i2 = new StringReader("hello")
197 # var b2 = new FlatBuffer
198 # i2.append_line_to(b2)
199 # assert b2 == "hello"
203 # NOTE: The single character LINE FEED (`\n`) delimits the end of lines.
204 # Therefore CARRIAGE RETURN & LINE FEED (`\r\n`) is also recognized.
205 fun append_line_to
(s
: Buffer)
207 if last_error
!= null then return
215 if c
== '\n' then return
220 # Is there something to read.
221 # This function returns 'false' if there is something to read.
222 fun eof
: Bool is abstract
224 # Read the next sequence of non whitespace characters.
226 # Leading whitespace characters are skipped.
227 # The first whitespace character that follows the result is consumed.
229 # An empty string is returned if the end of the file or an error is encounter.
232 # var w = new StringReader(" Hello, \n\t World!")
233 # assert w.read_word == "Hello,"
234 # assert w.read_char == '\n'.ascii
235 # assert w.read_word == "World!"
236 # assert w.read_word == ""
239 # `Char::is_whitespace` determines what is a whitespace.
240 fun read_word
: String
242 var buf
= new FlatBuffer
243 var c
= read_nonwhitespace
250 if a
.is_whitespace
then break
258 # Skip whitespace characters (if any) then return the following non-whitespace character.
260 # Returns the code point of the character.
261 # Return -1 on end of file or error.
263 # In fact, this method works like `read_char` except it skips whitespace.
266 # var w = new StringReader(" \nab\tc")
267 # assert w.read_nonwhitespace == 'a'.ascii
268 # assert w.read_nonwhitespace == 'b'.ascii
269 # assert w.read_nonwhitespace == 'c'.ascii
270 # assert w.read_nonwhitespace == -1
273 # `Char::is_whitespace` determines what is a whitespace.
274 fun read_nonwhitespace
: Int
279 if c
< 0 or not c
.ascii
.is_whitespace
then break
285 # Iterator returned by `Reader::each_line`.
286 # See the aforementioned method for details.
288 super Iterator[String]
290 # The original stream
295 var res
= not stream
.eof
296 if not res
and close_on_finish
then stream
.close
304 line
= stream
.read_line
310 # The last line read (cache)
311 private var line
: nullable String = null
316 if line
== null then item
321 # Close the stream when the stream is at the EOF.
324 var close_on_finish
= false is writable
328 if close_on_finish
then stream
.close
332 # `Reader` capable of declaring if readable without blocking
333 abstract class PollableReader
336 # Is there something to read? (without blocking)
337 fun poll_in
: Bool is abstract
341 # A `Stream` that can be written to
342 abstract class Writer
345 fun write
(s
: Text) is abstract
347 # Can the stream be used to write
348 fun is_writable
: Bool is abstract
351 # Things that can be efficienlty written to a `Writer`
353 # The point of this interface is to allow the instance to be efficiently
354 # written into a `Writer`.
356 # Ready-to-save documents usually provide this interface.
358 # Write itself to a `stream`
359 # The specific logic it let to the concrete subclasses
360 fun write_to
(stream
: Writer) is abstract
362 # Like `write_to` but return a new String (may be quite large)
364 # This funtionnality is anectodical, since the point
365 # of streamable object to to be efficienlty written to a
366 # stream without having to allocate and concatenate strings
367 fun write_to_string
: String
369 var stream
= new StringWriter
377 redef fun write_to
(stream
) do stream
.write
(self)
380 # Input streams with a buffered input for efficiency purposes
381 abstract class BufferedReader
385 if last_error
!= null then return -1
387 last_error
= new IOError("Stream has reached eof")
390 var c
= _buffer
.chars
[_buffer_pos
]
395 # Peeks up to `n` bytes in the buffer, returns an empty string on EOF
397 # The operation does not consume the buffer
400 # var x = new FileReader("File.txt")
401 # assert x.peek(5) == x.read(5)
403 fun peek
(i
: Int): String do
404 if eof
then return ""
405 var b
= new FlatBuffer.with_capacity
(i
)
406 while i
> 0 and not eof
do
407 b
.add _buffer
[_buffer_pos
]
411 var nbuflen
= b
.length
+ (_buffer
.length
- _buffer_pos
)
412 var nbuf
= new FlatBuffer.with_capacity
(nbuflen
)
414 while _buffer_pos
< _buffer
.length
do
415 nbuf
.add
(_buffer
[_buffer_pos
])
425 if last_error
!= null then return ""
426 if eof
then return ""
428 var bufsp
= _buffer
.length
- p
431 return _buffer
.substring
(p
, i
).to_s
433 _buffer_pos
= _buffer
.length
434 var readln
= _buffer
.length
- p
435 var s
= _buffer
.substring
(p
, readln
).to_s
437 return s
+ read
(i
- readln
)
442 if last_error
!= null then return ""
443 var s
= new FlatBuffer
446 var k
= _buffer
.length
457 redef fun append_line_to
(s
)
460 # First phase: look for a '\n'
462 while i
< _buffer
.length
and _buffer
.chars
[i
] != '\n' do i
+= 1
465 if i
< _buffer
.length
then
466 assert _buffer
.chars
[i
] == '\n'
473 # if there is something to append
474 if i
> _buffer_pos
then
475 # Enlarge the string (if needed)
476 s
.enlarge
(s
.length
+ i
- _buffer_pos
)
478 # Copy from the buffer to the string
481 s
.add
(_buffer
.chars
[j
])
495 if end_reached
then return
503 if _buffer_pos
< _buffer
.length
then return false
504 if end_reached
then return true
506 return _buffer_pos
>= _buffer
.length
and end_reached
510 private var buffer
: nullable FlatBuffer = null
512 # The current position in the buffer
513 private var buffer_pos
: Int = 0
516 protected fun fill_buffer
is abstract
518 # Is the last fill_buffer reach the end
519 protected fun end_reached
: Bool is abstract
521 # Allocate a `_buffer` for a given `capacity`.
522 protected fun prepare_buffer
(capacity
: Int)
524 _buffer
= new FlatBuffer.with_capacity
(capacity
)
525 _buffer_pos
= 0 # need to read
529 # A `Stream` that can be written to and read from
530 abstract class Duplex
535 # `Stream` that can be used to write to a `String`
537 # Mainly used for compatibility with Writer type and tests.
541 private var content
= new Array[String]
542 redef fun to_s
do return content
.to_s
543 redef fun is_writable
do return not closed
547 content
.add
(str
.to_s
)
550 # Is the stream closed?
551 protected var closed
= false
553 redef fun close
do closed
= true
556 # `Stream` used to read from a `String`
558 # Mainly used for compatibility with Reader type and tests.
562 # The string to read from.
565 # The current position in the string.
566 private var cursor
: Int = 0
568 redef fun read_char
do
569 if cursor
< source
.length
then
570 var c
= source
[cursor
].ascii
583 redef fun read_all
do
585 cursor
= source
.length
586 if c
== 0 then return source
587 return source
.substring_from
(c
)
590 redef fun eof
do return cursor
>= source
.length