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
14 intrude import text
::ropes
25 # Any kind of error that could be produced by an operation on Streams
30 # Any kind of stream to read/write/both to or from a source
32 # Error produced by the file stream
34 # var ifs = new FileReader.open("donotmakethisfile.binx")
37 # assert ifs.last_error != null
38 var last_error
: nullable IOError = null
44 # A `Stream` that can be read from
48 # Decoder used to transform input bytes to UTF-8
49 var decoder
: Decoder = utf8_decoder
is writable
51 # Reads a character. Returns `null` on EOF or timeout
52 fun read_char
: nullable Char is abstract
54 # Reads a byte. Returns `null` on EOF or timeout
55 fun read_byte
: nullable Byte is abstract
57 # Reads a String of at most `i` length
58 fun read
(i
: Int): String do return read_bytes
(i
).to_s
60 # Read at most i bytes
61 fun read_bytes
(i
: Int): Bytes
63 if last_error
!= null then return new Bytes.empty
64 var s
= new NativeString(i
)
65 var buf
= new Bytes(s
, 0, 0)
66 while i
> 0 and not eof
do
76 # Read a string until the end of the line.
78 # The line terminator '\n' and '\r\n', if any, is removed in each line.
81 # var txt = "Hello\n\nWorld\n"
82 # var i = new StringReader(txt)
83 # assert i.read_line == "Hello"
84 # assert i.read_line == ""
85 # assert i.read_line == "World"
89 # Only LINE FEED (`\n`), CARRIAGE RETURN & LINE FEED (`\r\n`), and
90 # the end or file (EOF) is considered to delimit the end of lines.
91 # CARRIAGE RETURN (`\r`) alone is not used for the end of line.
94 # var txt2 = "Hello\r\n\n\rWorld"
95 # var i2 = new StringReader(txt2)
96 # assert i2.read_line == "Hello"
97 # assert i2.read_line == ""
98 # assert i2.read_line == "\rWorld"
102 # NOTE: Use `append_line_to` if the line terminator needs to be preserved.
103 fun read_line
: String
105 if last_error
!= null then return ""
106 if eof
then return ""
107 var s
= new FlatBuffer
112 # Read all the lines until the eof.
114 # The line terminator '\n' and `\r\n` is removed in each line,
117 # var txt = "Hello\n\nWorld\n"
118 # var i = new StringReader(txt)
119 # assert i.read_lines == ["Hello", "", "World"]
122 # This method is more efficient that splitting
123 # the result of `read_all`.
125 # NOTE: SEE `read_line` for details.
126 fun read_lines
: Array[String]
128 var res
= new Array[String]
135 # Return an iterator that read each line.
137 # The line terminator '\n' and `\r\n` is removed in each line,
138 # The line are read with `read_line`. See this method for details.
141 # var txt = "Hello\n\nWorld\n"
142 # var i = new StringReader(txt)
143 # assert i.each_line.to_a == ["Hello", "", "World"]
146 # Unlike `read_lines` that read all lines at the call, `each_line` is lazy.
147 # Therefore, the stream should no be closed until the end of the stream.
150 # i = new StringReader(txt)
151 # var el = i.each_line
153 # assert el.item == "Hello"
155 # assert el.item == ""
160 # assert not el.is_ok
161 # # closed before "world" is read
163 fun each_line
: LineIterator do return new LineIterator(self)
165 # Read all the stream until the eof.
167 # The content of the file is returned as a String.
170 # var txt = "Hello\n\nWorld\n"
171 # var i = new StringReader(txt)
172 # assert i.read_all == txt
174 fun read_all
: String do
175 var s
= read_all_bytes
177 if slen
== 0 then return ""
180 var str
= s
.items
.clean_utf8
(slen
)
185 # The 129 size was decided more or less arbitrarily
186 # It will require some more benchmarking to compute
187 # if this is the best size or not
189 if chunksz
> remsp
then
190 rets
+= new FlatString.with_infos
(sits
, remsp
, pos
, pos
+ remsp
- 1)
193 var st
= sits
.find_beginning_of_char_at
(pos
+ chunksz
- 1)
194 var bytelen
= st
- pos
195 rets
+= new FlatString.with_infos
(sits
, bytelen
, pos
, st
- 1)
199 if rets
isa Concat then return rets
.balance
203 # Read all the stream until the eof.
205 # The content of the file is returned verbatim.
206 fun read_all_bytes
: Bytes
208 if last_error
!= null then return new Bytes.empty
209 var s
= new Bytes.empty
212 if c
!= null then s
.add
(c
)
217 # Read a string until the end of the line and append it to `s`.
219 # Unlike `read_line` and other related methods,
220 # the line terminator '\n', if any, is preserved in each line.
221 # Use the method `Text::chomp` to safely remove it.
224 # var txt = "Hello\n\nWorld\n"
225 # var i = new StringReader(txt)
226 # var b = new FlatBuffer
227 # i.append_line_to(b)
228 # assert b == "Hello\n"
229 # i.append_line_to(b)
230 # assert b == "Hello\n\n"
231 # i.append_line_to(b)
236 # If `\n` is not present at the end of the result, it means that
237 # a non-eol terminated last line was returned.
240 # var i2 = new StringReader("hello")
242 # var b2 = new FlatBuffer
243 # i2.append_line_to(b2)
244 # assert b2 == "hello"
248 # NOTE: The single character LINE FEED (`\n`) delimits the end of lines.
249 # Therefore CARRIAGE RETURN & LINE FEED (`\r\n`) is also recognized.
250 fun append_line_to
(s
: Buffer)
252 if last_error
!= null then return
259 if x
== '\n' then return
264 # Is there something to read.
265 # This function returns 'false' if there is something to read.
266 fun eof
: Bool is abstract
268 # Read the next sequence of non whitespace characters.
270 # Leading whitespace characters are skipped.
271 # The first whitespace character that follows the result is consumed.
273 # An empty string is returned if the end of the file or an error is encounter.
276 # var w = new StringReader(" Hello, \n\t World!")
277 # assert w.read_word == "Hello,"
278 # assert w.read_char == '\n'.ascii
279 # assert w.read_word == "World!"
280 # assert w.read_word == ""
283 # `Char::is_whitespace` determines what is a whitespace.
284 fun read_word
: String
286 var buf
= new FlatBuffer
287 var c
= read_nonwhitespace
292 if c
== null then break
293 if c
.is_whitespace
then break
301 # Skip whitespace characters (if any) then return the following non-whitespace character.
303 # Returns the code point of the character.
304 # Returns `null` on end of file or error.
306 # In fact, this method works like `read_char` except it skips whitespace.
309 # var w = new StringReader(" \nab\tc")
310 # assert w.read_nonwhitespace == 'a'
311 # assert w.read_nonwhitespace == 'b'
312 # assert w.read_nonwhitespace == 'c'
313 # assert w.read_nonwhitespace == null
316 # `Char::is_whitespace` determines what is a whitespace.
317 fun read_nonwhitespace
: nullable Char
319 var c
: nullable Char = null
322 if c
== null or not c
.is_whitespace
then break
328 # Iterator returned by `Reader::each_line`.
329 # See the aforementioned method for details.
331 super Iterator[String]
333 # The original stream
338 var res
= not stream
.eof
339 if not res
and close_on_finish
then stream
.close
347 line
= stream
.read_line
353 # The last line read (cache)
354 private var line
: nullable String = null
359 if line
== null then item
364 # Close the stream when the stream is at the EOF.
367 var close_on_finish
= false is writable
371 if close_on_finish
then stream
.close
375 # `Reader` capable of declaring if readable without blocking
376 abstract class PollableReader
379 # Is there something to read? (without blocking)
380 fun poll_in
: Bool is abstract
384 # A `Stream` that can be written to
385 abstract class Writer
388 # The coder from a nit UTF-8 String to the output file
389 var coder
: Coder = utf8_coder
is writable
391 # Writes bytes from `s`
392 fun write_bytes
(s
: Bytes) is abstract
395 fun write
(s
: Text) is abstract
397 # Write a single byte
398 fun write_byte
(value
: Byte) is abstract
400 # Can the stream be used to write
401 fun is_writable
: Bool is abstract
404 # Things that can be efficienlty written to a `Writer`
406 # The point of this interface is to allow the instance to be efficiently
407 # written into a `Writer`.
409 # Ready-to-save documents usually provide this interface.
411 # Write itself to a `stream`
412 # The specific logic it let to the concrete subclasses
413 fun write_to
(stream
: Writer) is abstract
415 # Like `write_to` but return a new String (may be quite large)
417 # This funtionality is anectodical, since the point
418 # of streamable object to to be efficienlty written to a
419 # stream without having to allocate and concatenate strings
420 fun write_to_string
: String
422 var stream
= new StringWriter
430 redef fun write_to
(stream
) do stream
.write
(self)
433 # Input streams with a buffered input for efficiency purposes
434 abstract class BufferedReader
438 if last_error
!= null then return null
440 last_error
= new IOError("Stream has reached eof")
443 # TODO: Fix when supporting UTF-8
444 var c
= _buffer
[_buffer_pos
].to_i
.ascii
451 if last_error
!= null then return null
453 last_error
= new IOError("Stream has reached eof")
456 var c
= _buffer
[_buffer_pos
]
461 # Resets the internal buffer
467 # Peeks up to `n` bytes in the buffer
469 # The operation does not consume the buffer
472 # var x = new FileReader.open("File.txt")
473 # assert x.peek(5) == x.read(5)
475 fun peek
(i
: Int): Bytes do
476 if eof
then return new Bytes.empty
477 var remsp
= _buffer_length
- _buffer_pos
479 var bf
= new Bytes.with_capacity
(i
)
480 bf
.append_ns_from
(_buffer
, i
, _buffer_pos
)
483 var bf
= new Bytes.with_capacity
(i
)
484 bf
.append_ns_from
(_buffer
, remsp
, _buffer_pos
)
485 _buffer_pos
= _buffer_length
486 read_intern
(i
- bf
.length
, bf
)
487 remsp
= _buffer_length
- _buffer_pos
488 var full_len
= bf
.length
+ remsp
489 if full_len
> _buffer_capacity
then
490 var c
= _buffer_capacity
491 while c
< full_len
do c
= c
* 2 + 2
494 var nns
= new NativeString(_buffer_capacity
)
495 bf
.items
.copy_to
(nns
, bf
.length
, 0, 0)
496 _buffer
.copy_to
(nns
, remsp
, _buffer_pos
, bf
.length
)
499 _buffer_length
= full_len
503 redef fun read_bytes
(i
)
505 if last_error
!= null then return new Bytes.empty
506 var buf
= new Bytes.with_capacity
(i
)
511 # Fills `buf` with at most `i` bytes read from `self`
512 private fun read_intern
(i
: Int, buf
: Bytes): Int do
515 var bufsp
= _buffer_length
- p
518 buf
.append_ns_from
(_buffer
, i
, p
)
521 _buffer_pos
= _buffer_length
522 var readln
= _buffer_length
- p
523 buf
.append_ns_from
(_buffer
, readln
, p
)
524 var rd
= read_intern
(i
- readln
, buf
)
528 redef fun read_all_bytes
530 if last_error
!= null then return new Bytes.empty
531 var s
= new Bytes.with_capacity
(10)
535 var k
= _buffer_length
537 s
.append_ns_from
(b
, rd_sz
, j
)
544 redef fun append_line_to
(s
)
546 var lb
= new Bytes.with_capacity
(10)
548 # First phase: look for a '\n'
550 while i
< _buffer_length
and _buffer
[i
] != 0xAu
8 do
555 if i
< _buffer_length
then
556 assert _buffer
[i
] == 0xAu
8
563 # if there is something to append
564 if i
> _buffer_pos
then
565 # Copy from the buffer to the string
595 if _buffer_pos
< _buffer_length
then return false
596 if end_reached
then return true
598 return _buffer_pos
>= _buffer_length
and end_reached
602 private var buffer
: NativeString = new NativeString(0)
604 # The current position in the buffer
605 private var buffer_pos
= 0
607 # Length of the current buffer (i.e. nuber of bytes in the buffer)
608 private var buffer_length
= 0
610 # Capacity of the buffer
611 private var buffer_capacity
= 0
614 protected fun fill_buffer
is abstract
616 # Has the last fill_buffer reached the end
617 protected fun end_reached
: Bool is abstract
619 # Allocate a `_buffer` for a given `capacity`.
620 protected fun prepare_buffer
(capacity
: Int)
622 _buffer
= new NativeString(capacity
)
623 _buffer_pos
= 0 # need to read
625 _buffer_capacity
= capacity
629 # A `Stream` that can be written to and read from
630 abstract class Duplex
635 # `Stream` that can be used to write to a `String`
637 # Mainly used for compatibility with Writer type and tests.
641 private var content
= new Array[String]
642 redef fun to_s
do return content
.plain_to_s
643 redef fun is_writable
do return not closed
645 redef fun write_bytes
(b
) do
652 content
.add
(str
.to_s
)
655 # Is the stream closed?
656 protected var closed
= false
658 redef fun close
do closed
= true
661 # `Stream` used to read from a `String`
663 # Mainly used for compatibility with Reader type and tests.
667 # The string to read from.
670 # The current position in the string (bytewise).
671 private var cursor
: Int = 0
673 redef fun read_char
do
674 if cursor
< source
.length
then
675 # Fix when supporting UTF-8
676 var c
= source
[cursor
]
684 redef fun read_byte
do
685 if cursor
< source
.length
then
686 var c
= source
.bytes
[cursor
]
698 redef fun read_all_bytes
do
699 var nslen
= source
.length
- cursor
700 var nns
= new NativeString(nslen
)
701 source
.copy_to_native
(nns
, nslen
, cursor
, 0)
702 return new Bytes(nns
, nslen
, nslen
)
705 redef fun eof
do return cursor
>= source
.bytelen