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 # Any kind of error that could be produced by an operation on Streams
29 # Any kind of stream to read/write/both to or from a source
31 # Codec used to transform raw data to text
33 # Note: defaults to UTF-8
34 var codec
: Codec = utf8_codec
is protected writable(set_codec
)
36 # Lookahead buffer for codecs
38 # Since some codecs are multibyte, a lookahead may be required
39 # to store the next bytes and consume them only if a valid character
41 protected var lookahead
: CString is noinit
43 # Capacity of the lookahead
44 protected var lookahead_capacity
= 0
46 # Current occupation of the lookahead
47 protected var lookahead_length
= 0
49 # Buffer for writing data to a stream
50 protected var write_buffer
: CString is noinit
53 var lcap
= codec
.max_lookahead
54 lookahead
= new CString(lcap
)
55 write_buffer
= new CString(lcap
)
57 lookahead_capacity
= lcap
60 # Change the codec for this stream.
61 fun codec
=(c
: Codec) do
62 if c
.max_lookahead
> lookahead_capacity
then
63 var lcap
= codec
.max_lookahead
64 var lk
= new CString(lcap
)
65 var llen
= lookahead_length
67 lookahead
.copy_to
(lk
, llen
, 0, 0)
70 lookahead_capacity
= lcap
71 write_buffer
= new CString(lcap
)
76 # Error produced by the file stream
78 # var ifs = new FileReader.open("donotmakethisfile.binx")
81 # assert ifs.last_error != null
82 var last_error
: nullable IOError = null
89 # Used to inform `self` that operations will start.
90 # Specific streams can use this to prepare some resources.
92 # Is automatically invoked at the beginning of `with` structures.
94 # Do nothing by default.
99 # Used to inform `self` that the operations are over.
100 # Specific streams can use this to free some resources.
102 # Is automatically invoked at the end of `with` structures.
104 # call `close` by default.
108 # A `Stream` that can be read from
109 abstract class Reader
112 # Read a byte directly from the underlying stream, without
113 # considering any eventual buffer
114 protected fun raw_read_byte
: Int is abstract
116 # Read at most `max` bytes from the underlying stream into `buf`,
117 # without considering any eventual buffer
119 # Returns how many bytes were read
120 protected fun raw_read_bytes
(buf
: CString, max
: Int): Int do
122 for i
in [0 .. max
[ do
123 var b
= raw_read_byte
131 # Reads a character. Returns `null` on EOF or timeout
133 # Returns unicode replacement character '�' if an
134 # invalid byte sequence is read.
136 # `read_char` may block if:
138 # * No byte could be read from the current buffer
139 # * An incomplete char is partially read, and more bytes are
140 # required for full decoding.
141 fun read_char
: nullable Char do
142 if eof
then return null
144 var codet_sz
= cod
.codet_size
146 var llen
= lookahead_length
147 if llen
< codet_sz
then
148 llen
+= raw_read_bytes
(lk
.fast_cstring
(llen
), codet_sz
- llen
)
150 if llen
< codet_sz
then
152 return 0xFFFD.code_point
154 var ret
= cod
.is_valid_char
(lk
, codet_sz
)
155 var max_llen
= cod
.max_lookahead
156 while ret
== 1 and llen
< max_llen
do
157 var rd
= raw_read_bytes
(lk
.fast_cstring
(llen
), codet_sz
)
158 if rd
< codet_sz
then
161 lookahead
.lshift
(codet_sz
, llen
, codet_sz
)
163 lookahead_length
= llen
.max
(0)
164 return 0xFFFD.code_point
167 ret
= cod
.is_valid_char
(lk
, llen
)
170 var c
= cod
.decode_char
(lk
)
171 var clen
= c
.u8char_len
174 lookahead
.lshift
(clen
, llen
, clen
)
176 lookahead_length
= llen
179 if ret
== 2 or ret
== 1 then
182 lookahead
.lshift
(codet_sz
, llen
, codet_sz
)
184 lookahead_length
= llen
185 return 0xFFFD.code_point
187 # Should not happen if the decoder works properly
188 var arr
= new Array[Object]
189 arr
.push
"Decoder error: could not decode nor recover from byte sequence ["
190 for i
in [0 .. llen
[ do
195 var err
= new IOError(arr
.plain_to_s
)
196 err
.cause
= last_error
198 return 0xFFFD.code_point
201 # Reads a byte. Returns a negative value on error
202 fun read_byte
: Int do
203 var llen
= lookahead_length
204 if llen
== 0 then return raw_read_byte
210 lk
.lshift
(1, llen
- 1, 1)
211 lookahead_length
-= 1
216 # Reads a String of at most `i` length
217 fun read
(i
: Int): String do
218 var cs
= new CString(i
)
219 var rd
= read_bytes_to_cstring
(cs
, i
)
220 return codec
.decode_string
(cs
, rd
)
223 # Reads up to `max` bytes from source
224 fun read_bytes
(max
: Int): Bytes do
225 var cs
= new CString(max
)
226 var rd
= read_bytes_to_cstring
(cs
, max
)
227 return new Bytes(cs
, rd
, max
)
230 # Reads up to `max` bytes from source and stores them in `bytes`
231 fun read_bytes_to_cstring
(bytes
: CString, max
: Int): Int do
232 var llen
= lookahead_length
233 if llen
== 0 then return raw_read_bytes
(bytes
, max
)
234 var rd
= max
.min
(llen
)
236 lk
.copy_to
(bytes
, rd
, 0, 0)
238 lk
.lshift
(rd
, llen
- rd
, rd
)
239 lookahead_length
-= rd
243 return rd
+ raw_read_bytes
(bytes
, max
- rd
)
246 # Read a string until the end of the line.
248 # The line terminator '\n' and '\r\n', if any, is removed in each line.
251 # var txt = "Hello\n\nWorld\n"
252 # var i = new StringReader(txt)
253 # assert i.read_line == "Hello"
254 # assert i.read_line == ""
255 # assert i.read_line == "World"
259 # Only LINE FEED (`\n`), CARRIAGE RETURN & LINE FEED (`\r\n`), and
260 # the end or file (EOF) is considered to delimit the end of lines.
261 # CARRIAGE RETURN (`\r`) alone is not used for the end of line.
264 # var txt2 = "Hello\r\n\n\rWorld"
265 # var i2 = new StringReader(txt2)
266 # assert i2.read_line == "Hello"
267 # assert i2.read_line == ""
268 # assert i2.read_line == "\rWorld"
272 # NOTE: Use `append_line_to` if the line terminator needs to be preserved.
273 fun read_line
: String
275 if last_error
!= null then return ""
276 if eof
then return ""
277 var s
= new FlatBuffer
282 # Read all the lines until the eof.
284 # The line terminator '\n' and `\r\n` is removed in each line,
287 # var txt = "Hello\n\nWorld\n"
288 # var i = new StringReader(txt)
289 # assert i.read_lines == ["Hello", "", "World"]
292 # This method is more efficient that splitting
293 # the result of `read_all`.
295 # NOTE: SEE `read_line` for details.
296 fun read_lines
: Array[String]
298 var res
= new Array[String]
305 # Return an iterator that read each line.
307 # The line terminator '\n' and `\r\n` is removed in each line,
308 # The line are read with `read_line`. See this method for details.
311 # var txt = "Hello\n\nWorld\n"
312 # var i = new StringReader(txt)
313 # assert i.each_line.to_a == ["Hello", "", "World"]
316 # Unlike `read_lines` that read all lines at the call, `each_line` is lazy.
317 # Therefore, the stream should no be closed until the end of the stream.
320 # i = new StringReader(txt)
321 # var el = i.each_line
323 # assert el.item == "Hello"
325 # assert el.item == ""
330 # assert not el.is_ok
331 # # closed before "world" is read
333 fun each_line
: LineIterator do return new LineIterator(self)
335 # Read all the stream until the eof.
337 # The content of the file is returned as a String.
340 # var txt = "Hello\n\nWorld\n"
341 # var i = new StringReader(txt)
342 # assert i.read_all == txt
344 fun read_all
: String do
345 var s
= read_all_bytes
347 if slen
== 0 then return ""
348 return codec
.decode_string
(s
.items
, s
.length
)
351 # Read all the stream until the eof.
353 # The content of the file is returned verbatim.
354 fun read_all_bytes
: Bytes
356 if last_error
!= null then return new Bytes.empty
357 var s
= new Bytes.empty
358 var buf
= new CString(4096)
360 var rd
= read_bytes_to_cstring
(buf
, 4096)
366 # Read a string until the end of the line and append it to `s`.
368 # Unlike `read_line` and other related methods,
369 # the line terminator '\n', if any, is preserved in each line.
370 # Use the method `Text::chomp` to safely remove it.
373 # var txt = "Hello\n\nWorld\n"
374 # var i = new StringReader(txt)
375 # var b = new FlatBuffer
376 # i.append_line_to(b)
377 # assert b == "Hello\n"
378 # i.append_line_to(b)
379 # assert b == "Hello\n\n"
380 # i.append_line_to(b)
385 # If `\n` is not present at the end of the result, it means that
386 # a non-eol terminated last line was returned.
389 # var i2 = new StringReader("hello")
391 # var b2 = new FlatBuffer
392 # i2.append_line_to(b2)
393 # assert b2 == "hello"
397 # NOTE: The single character LINE FEED (`\n`) delimits the end of lines.
398 # Therefore CARRIAGE RETURN & LINE FEED (`\r\n`) is also recognized.
399 fun append_line_to
(s
: Buffer)
401 if last_error
!= null then return
408 if x
== '\n' then return
413 # Is there something to read.
414 # This function returns 'false' if there is something to read.
415 fun eof
: Bool is abstract
417 # Read the next sequence of non whitespace characters.
419 # Leading whitespace characters are skipped.
420 # The first whitespace character that follows the result is consumed.
422 # An empty string is returned if the end of the file or an error is encounter.
425 # var w = new StringReader(" Hello, \n\t World!")
426 # assert w.read_word == "Hello,"
427 # assert w.read_char == '\n'
428 # assert w.read_word == "World!"
429 # assert w.read_word == ""
432 # `Char::is_whitespace` determines what is a whitespace.
433 fun read_word
: String
435 var buf
= new FlatBuffer
436 var c
= read_nonwhitespace
441 if c
== null then break
442 if c
.is_whitespace
then break
450 # Skip whitespace characters (if any) then return the following non-whitespace character.
452 # Returns the code point of the character.
453 # Returns `null` on end of file or error.
455 # In fact, this method works like `read_char` except it skips whitespace.
458 # var w = new StringReader(" \nab\tc")
459 # assert w.read_nonwhitespace == 'a'
460 # assert w.read_nonwhitespace == 'b'
461 # assert w.read_nonwhitespace == 'c'
462 # assert w.read_nonwhitespace == null
465 # `Char::is_whitespace` determines what is a whitespace.
466 fun read_nonwhitespace
: nullable Char
468 var c
: nullable Char = null
471 if c
== null or not c
.is_whitespace
then break
477 # Iterator returned by `Reader::each_line`.
478 # See the aforementioned method for details.
480 super Iterator[String]
482 # The original stream
487 var res
= not stream
.eof
488 if not res
and close_on_finish
then stream
.close
496 line
= stream
.read_line
502 # The last line read (cache)
503 private var line
: nullable String = null
508 if line
== null then item
513 # Close the stream when the stream is at the EOF.
516 var close_on_finish
= false is writable
520 if close_on_finish
then stream
.close
524 # `Reader` capable of declaring if readable without blocking
525 abstract class PollableReader
528 # Is there something to read? (without blocking)
529 fun poll_in
: Bool is abstract
533 # A `Stream` that can be written to
534 abstract class Writer
537 # Write bytes from `s`
538 fun write_bytes
(s
: Bytes) do write_bytes_from_cstring
(s
.items
, s
.length
)
540 # Write `len` bytes from `ns`
541 fun write_bytes_from_cstring
(ns
: CString, len
: Int) is abstract
544 fun write
(s
: Text) is abstract
546 # Write a single byte
547 fun write_byte
(value
: Byte) is abstract
549 # Write a single char
550 fun write_char
(c
: Char) do
551 var ln
= codec
.add_char_to
(c
, write_buffer
)
552 write_bytes_from_cstring
(write_buffer
, ln
)
555 # Can the stream be used to write
556 fun is_writable
: Bool is abstract
559 # Things that can be efficienlty written to a `Writer`
561 # The point of this interface is to allow the instance to be efficiently
562 # written into a `Writer`.
564 # Ready-to-save documents usually provide this interface.
566 # Write itself to a `stream`
567 # The specific logic it let to the concrete subclasses
568 fun write_to
(stream
: Writer) is abstract
570 # Like `write_to` but return a new String (may be quite large)
572 # This funtionality is anectodical, since the point
573 # of streamable object to to be efficienlty written to a
574 # stream without having to allocate and concatenate strings
575 fun write_to_string
: String
577 var stream
= new StringWriter
585 redef fun write_to
(s
) do s
.write_bytes
(self)
587 redef fun write_to_string
do return to_s
592 redef fun write_to
(stream
) do stream
.write
(self)
595 # Input streams with a buffered input for efficiency purposes
596 abstract class BufferedReader
599 redef fun raw_read_byte
601 if last_error
!= null then return -1
603 last_error
= new IOError("Stream has reached eof")
606 var c
= _buffer
[_buffer_pos
]
611 # Resets the internal buffer
617 # Peeks up to `n` bytes in the buffer
619 # The operation does not consume the buffer
622 # var x = new FileReader.open("File.txt")
623 # assert x.peek(5) == x.read(5)
625 fun peek
(i
: Int): Bytes do
626 if eof
then return new Bytes.empty
627 var remsp
= _buffer_length
- _buffer_pos
629 var bf
= new Bytes.with_capacity
(i
)
630 bf
.append_ns_from
(_buffer
, i
, _buffer_pos
)
633 var bf
= new Bytes.with_capacity
(i
)
634 bf
.append_ns_from
(_buffer
, remsp
, _buffer_pos
)
635 _buffer_pos
= _buffer_length
636 read_intern
(i
- bf
.length
, bf
)
637 remsp
= _buffer_length
- _buffer_pos
638 var full_len
= bf
.length
+ remsp
639 if full_len
> _buffer_capacity
then
640 var c
= _buffer_capacity
641 while c
< full_len
do c
= c
* 2 + 2
644 var nns
= new CString(_buffer_capacity
)
645 bf
.items
.copy_to
(nns
, bf
.length
, 0, 0)
646 _buffer
.copy_to
(nns
, remsp
, _buffer_pos
, bf
.length
)
649 _buffer_length
= full_len
653 redef fun read_bytes_to_cstring
(buf
, i
)
655 if last_error
!= null then return 0
656 var bbf
= new Bytes(buf
, 0, i
)
657 return read_intern
(i
, bbf
)
660 # Fills `buf` with at most `i` bytes read from `self`
661 private fun read_intern
(i
: Int, buf
: Bytes): Int do
664 var bufsp
= _buffer_length
- p
667 buf
.append_ns_from
(_buffer
, i
, p
)
670 _buffer_pos
= _buffer_length
671 var readln
= _buffer_length
- p
672 buf
.append_ns_from
(_buffer
, readln
, p
)
673 var rd
= read_intern
(i
- readln
, buf
)
677 redef fun read_all_bytes
679 if last_error
!= null then return new Bytes.empty
680 var s
= new Bytes.with_capacity
(10)
684 var k
= _buffer_length
686 s
.append_ns_from
(b
, rd_sz
, j
)
693 redef fun append_line_to
(s
)
695 var lb
= new Bytes.with_capacity
(10)
697 # First phase: look for a '\n'
699 while i
< _buffer_length
and _buffer
[i
] != 0xAu
8 do
704 if i
< _buffer_length
then
705 assert _buffer
[i
] == 0xAu
8
712 # if there is something to append
713 if i
> _buffer_pos
then
714 # Copy from the buffer to the string
744 if _buffer_pos
< _buffer_length
then return false
745 if end_reached
then return true
747 return _buffer_pos
>= _buffer_length
and end_reached
751 private var buffer
: CString = new CString(0)
753 # The current position in the buffer
754 private var buffer_pos
= 0
756 # Length of the current buffer (i.e. nuber of bytes in the buffer)
757 private var buffer_length
= 0
759 # Capacity of the buffer
760 private var buffer_capacity
= 0
763 protected fun fill_buffer
is abstract
765 # Has the last fill_buffer reached the end
766 protected fun end_reached
: Bool is abstract
768 # Allocate a `_buffer` for a given `capacity`.
769 protected fun prepare_buffer
(capacity
: Int)
771 _buffer
= new CString(capacity
)
772 _buffer_pos
= 0 # need to read
774 _buffer_capacity
= capacity
778 # A `Stream` that can be written to and read from
779 abstract class Duplex
784 # Write to `bytes` in memory
787 # var writer = new BytesWriter
789 # writer.write "Strings "
790 # writer.write_char '&'
791 # writer.write_byte 0x20u8
792 # writer.write_bytes "bytes".to_bytes
794 # assert writer.to_s == "\\x53\\x74\\x72\\x69\\x6E\\x67\\x73\\x20\\x26\\x20\\x62\\x79\\x74\\x65\\x73"
795 # assert writer.bytes.to_s == "Strings & bytes"
798 # As with any binary data, UTF-8 code points encoded on two bytes or more
799 # can be constructed byte by byte.
802 # writer = new BytesWriter
804 # # Write just the character first half
805 # writer.write_byte 0xC2u8
806 # assert writer.to_s == "\\xC2"
807 # assert writer.bytes.to_s == "�"
809 # # Complete the character
810 # writer.write_byte 0xA2u8
811 # assert writer.to_s == "\\xC2\\xA2"
812 # assert writer.bytes.to_s == "¢"
818 var bytes
= new Bytes.empty
820 redef fun to_s
do return bytes
.chexdigest
824 if closed
then return
825 str
.append_to_bytes bytes
828 redef fun write_char
(c
)
830 if closed
then return
834 redef fun write_byte
(value
)
836 if closed
then return
840 redef fun write_bytes_from_cstring
(ns
, len
) do
841 if closed
then return
842 bytes
.append_ns
(ns
, len
)
845 # Is the stream closed?
846 protected var closed
= false
848 redef fun close
do closed
= true
849 redef fun is_writable
do return not closed
852 # `Stream` writing to a `String`
854 # This class has the same behavior as `BytesWriter`
855 # except for `to_s` which decodes `bytes` to a string.
858 # var writer = new StringWriter
860 # writer.write "Strings "
861 # writer.write_char '&'
862 # writer.write_byte 0x20u8
863 # writer.write_bytes "bytes".to_bytes
865 # assert writer.to_s == "Strings & bytes"
870 redef fun to_s
do return bytes
.to_s
873 # Read from `bytes` in memory
876 # var reader = new BytesReader(b"a…b")
877 # assert reader.read_char == 'a'
878 # assert reader.read_byte == 0xE2 # 1st byte of '…'
879 # assert reader.read_byte == 0x80 # 2nd byte of '…'
880 # assert reader.read_char == '�' # Reads the last byte as an invalid char
881 # assert reader.read_all_bytes == b"b"
886 # Source data to read
889 # The current position in `bytes`
890 private var cursor
= 0
892 redef fun raw_read_byte
894 if cursor
>= bytes
.length
then return -1
896 var c
= bytes
[cursor
]
901 redef fun close
do bytes
= new Bytes.empty
903 redef fun read_all_bytes
905 var res
= bytes
.slice_from
(cursor
)
906 cursor
= bytes
.length
910 redef fun raw_read_bytes
(ns
, max
) do
911 if cursor
>= bytes
.length
then return 0
913 var copy
= max
.min
(bytes
.length
- cursor
)
914 bytes
.items
.copy_to
(ns
, copy
, cursor
, 0)
919 redef fun eof
do return cursor
>= bytes
.length
922 # `Stream` reading from a `String` source
924 # This class has the same behavior as `BytesReader`
925 # except for its constructor accepting a `String`.
928 # var reader = new StringReader("a…b")
929 # assert reader.read_char == 'a'
930 # assert reader.read_byte == 0xE2 # 1st byte of '…'
931 # assert reader.read_byte == 0x80 # 2nd byte of '…'
932 # assert reader.read_char == '�' # Reads the last byte as an invalid char
933 # assert reader.read_all == "b"
940 # Source data to read
943 init do bytes
= source
.to_bytes