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
132 fun read_char
: nullable Char is abstract
134 # Reads a byte. Returns a negative value on error
135 fun read_byte
: Int do
136 var llen
= lookahead_length
137 if llen
== 0 then return raw_read_byte
143 lk
.lshift
(1, llen
- 1, 1)
144 lookahead_length
-= 1
149 # Reads a String of at most `i` length
150 fun read
(i
: Int): String do
151 var cs
= new CString(i
)
152 var rd
= read_bytes_to_cstring
(cs
, i
)
153 return codec
.decode_string
(cs
, rd
)
156 # Reads up to `max` bytes from source
157 fun read_bytes
(max
: Int): Bytes do
158 var cs
= new CString(max
)
159 var rd
= read_bytes_to_cstring
(cs
, max
)
160 return new Bytes(cs
, rd
, max
)
163 # Reads up to `max` bytes from source and stores them in `bytes`
164 fun read_bytes_to_cstring
(bytes
: CString, max
: Int): Int do
165 var llen
= lookahead_length
166 if llen
== 0 then return raw_read_bytes
(bytes
, max
)
167 var rd
= max
.min
(llen
)
169 lk
.copy_to
(bytes
, rd
, 0, 0)
171 lk
.lshift
(rd
, llen
- rd
, rd
)
172 lookahead_length
-= rd
176 return rd
+ raw_read_bytes
(bytes
, max
- rd
)
179 # Read a string until the end of the line.
181 # The line terminator '\n' and '\r\n', if any, is removed in each line.
184 # var txt = "Hello\n\nWorld\n"
185 # var i = new StringReader(txt)
186 # assert i.read_line == "Hello"
187 # assert i.read_line == ""
188 # assert i.read_line == "World"
192 # Only LINE FEED (`\n`), CARRIAGE RETURN & LINE FEED (`\r\n`), and
193 # the end or file (EOF) is considered to delimit the end of lines.
194 # CARRIAGE RETURN (`\r`) alone is not used for the end of line.
197 # var txt2 = "Hello\r\n\n\rWorld"
198 # var i2 = new StringReader(txt2)
199 # assert i2.read_line == "Hello"
200 # assert i2.read_line == ""
201 # assert i2.read_line == "\rWorld"
205 # NOTE: Use `append_line_to` if the line terminator needs to be preserved.
206 fun read_line
: String
208 if last_error
!= null then return ""
209 if eof
then return ""
210 var s
= new FlatBuffer
215 # Read all the lines until the eof.
217 # The line terminator '\n' and `\r\n` is removed in each line,
220 # var txt = "Hello\n\nWorld\n"
221 # var i = new StringReader(txt)
222 # assert i.read_lines == ["Hello", "", "World"]
225 # This method is more efficient that splitting
226 # the result of `read_all`.
228 # NOTE: SEE `read_line` for details.
229 fun read_lines
: Array[String]
231 var res
= new Array[String]
238 # Return an iterator that read each line.
240 # The line terminator '\n' and `\r\n` is removed in each line,
241 # The line are read with `read_line`. See this method for details.
244 # var txt = "Hello\n\nWorld\n"
245 # var i = new StringReader(txt)
246 # assert i.each_line.to_a == ["Hello", "", "World"]
249 # Unlike `read_lines` that read all lines at the call, `each_line` is lazy.
250 # Therefore, the stream should no be closed until the end of the stream.
253 # i = new StringReader(txt)
254 # var el = i.each_line
256 # assert el.item == "Hello"
258 # assert el.item == ""
263 # assert not el.is_ok
264 # # closed before "world" is read
266 fun each_line
: LineIterator do return new LineIterator(self)
268 # Read all the stream until the eof.
270 # The content of the file is returned as a String.
273 # var txt = "Hello\n\nWorld\n"
274 # var i = new StringReader(txt)
275 # assert i.read_all == txt
277 fun read_all
: String do
278 var s
= read_all_bytes
280 if slen
== 0 then return ""
281 return codec
.decode_string
(s
.items
, s
.length
)
284 # Read all the stream until the eof.
286 # The content of the file is returned verbatim.
287 fun read_all_bytes
: Bytes
289 if last_error
!= null then return new Bytes.empty
290 var s
= new Bytes.empty
291 var buf
= new CString(4096)
293 var rd
= read_bytes_to_cstring
(buf
, 4096)
299 # Read a string until the end of the line and append it to `s`.
301 # Unlike `read_line` and other related methods,
302 # the line terminator '\n', if any, is preserved in each line.
303 # Use the method `Text::chomp` to safely remove it.
306 # var txt = "Hello\n\nWorld\n"
307 # var i = new StringReader(txt)
308 # var b = new FlatBuffer
309 # i.append_line_to(b)
310 # assert b == "Hello\n"
311 # i.append_line_to(b)
312 # assert b == "Hello\n\n"
313 # i.append_line_to(b)
318 # If `\n` is not present at the end of the result, it means that
319 # a non-eol terminated last line was returned.
322 # var i2 = new StringReader("hello")
324 # var b2 = new FlatBuffer
325 # i2.append_line_to(b2)
326 # assert b2 == "hello"
330 # NOTE: The single character LINE FEED (`\n`) delimits the end of lines.
331 # Therefore CARRIAGE RETURN & LINE FEED (`\r\n`) is also recognized.
332 fun append_line_to
(s
: Buffer)
334 if last_error
!= null then return
341 if x
== '\n' then return
346 # Is there something to read.
347 # This function returns 'false' if there is something to read.
348 fun eof
: Bool is abstract
350 # Read the next sequence of non whitespace characters.
352 # Leading whitespace characters are skipped.
353 # The first whitespace character that follows the result is consumed.
355 # An empty string is returned if the end of the file or an error is encounter.
358 # var w = new StringReader(" Hello, \n\t World!")
359 # assert w.read_word == "Hello,"
360 # assert w.read_char == '\n'
361 # assert w.read_word == "World!"
362 # assert w.read_word == ""
365 # `Char::is_whitespace` determines what is a whitespace.
366 fun read_word
: String
368 var buf
= new FlatBuffer
369 var c
= read_nonwhitespace
374 if c
== null then break
375 if c
.is_whitespace
then break
383 # Skip whitespace characters (if any) then return the following non-whitespace character.
385 # Returns the code point of the character.
386 # Returns `null` on end of file or error.
388 # In fact, this method works like `read_char` except it skips whitespace.
391 # var w = new StringReader(" \nab\tc")
392 # assert w.read_nonwhitespace == 'a'
393 # assert w.read_nonwhitespace == 'b'
394 # assert w.read_nonwhitespace == 'c'
395 # assert w.read_nonwhitespace == null
398 # `Char::is_whitespace` determines what is a whitespace.
399 fun read_nonwhitespace
: nullable Char
401 var c
: nullable Char = null
404 if c
== null or not c
.is_whitespace
then break
410 # Iterator returned by `Reader::each_line`.
411 # See the aforementioned method for details.
413 super Iterator[String]
415 # The original stream
420 var res
= not stream
.eof
421 if not res
and close_on_finish
then stream
.close
429 line
= stream
.read_line
435 # The last line read (cache)
436 private var line
: nullable String = null
441 if line
== null then item
446 # Close the stream when the stream is at the EOF.
449 var close_on_finish
= false is writable
453 if close_on_finish
then stream
.close
457 # `Reader` capable of declaring if readable without blocking
458 abstract class PollableReader
461 # Is there something to read? (without blocking)
462 fun poll_in
: Bool is abstract
466 # A `Stream` that can be written to
467 abstract class Writer
470 # Writes bytes from `s`
471 fun write_bytes
(s
: Bytes) is abstract
474 fun write
(s
: Text) is abstract
476 # Write a single byte
477 fun write_byte
(value
: Byte) is abstract
479 # Writes a single char
480 fun write_char
(c
: Char) do write
(c
.to_s
)
482 # Can the stream be used to write
483 fun is_writable
: Bool is abstract
486 # Things that can be efficienlty written to a `Writer`
488 # The point of this interface is to allow the instance to be efficiently
489 # written into a `Writer`.
491 # Ready-to-save documents usually provide this interface.
493 # Write itself to a `stream`
494 # The specific logic it let to the concrete subclasses
495 fun write_to
(stream
: Writer) is abstract
497 # Like `write_to` but return a new String (may be quite large)
499 # This funtionality is anectodical, since the point
500 # of streamable object to to be efficienlty written to a
501 # stream without having to allocate and concatenate strings
502 fun write_to_string
: String
504 var stream
= new StringWriter
512 redef fun write_to
(s
) do s
.write_bytes
(self)
514 redef fun write_to_string
do return to_s
519 redef fun write_to
(stream
) do stream
.write
(self)
522 # Input streams with a buffered input for efficiency purposes
523 abstract class BufferedReader
527 if last_error
!= null then return null
529 last_error
= new IOError("Stream has reached eof")
532 # TODO: Fix when supporting UTF-8
533 var c
= _buffer
[_buffer_pos
].to_i
.code_point
540 if last_error
!= null then return -1
542 last_error
= new IOError("Stream has reached eof")
545 var c
= _buffer
[_buffer_pos
]
550 # Resets the internal buffer
556 # Peeks up to `n` bytes in the buffer
558 # The operation does not consume the buffer
561 # var x = new FileReader.open("File.txt")
562 # assert x.peek(5) == x.read(5)
564 fun peek
(i
: Int): Bytes do
565 if eof
then return new Bytes.empty
566 var remsp
= _buffer_length
- _buffer_pos
568 var bf
= new Bytes.with_capacity
(i
)
569 bf
.append_ns_from
(_buffer
, i
, _buffer_pos
)
572 var bf
= new Bytes.with_capacity
(i
)
573 bf
.append_ns_from
(_buffer
, remsp
, _buffer_pos
)
574 _buffer_pos
= _buffer_length
575 read_intern
(i
- bf
.length
, bf
)
576 remsp
= _buffer_length
- _buffer_pos
577 var full_len
= bf
.length
+ remsp
578 if full_len
> _buffer_capacity
then
579 var c
= _buffer_capacity
580 while c
< full_len
do c
= c
* 2 + 2
583 var nns
= new CString(_buffer_capacity
)
584 bf
.items
.copy_to
(nns
, bf
.length
, 0, 0)
585 _buffer
.copy_to
(nns
, remsp
, _buffer_pos
, bf
.length
)
588 _buffer_length
= full_len
592 redef fun read_bytes_to_cstring
(buf
, i
)
594 if last_error
!= null then return 0
595 var bbf
= new Bytes(buf
, 0, i
)
596 return read_intern
(i
, bbf
)
599 # Fills `buf` with at most `i` bytes read from `self`
600 private fun read_intern
(i
: Int, buf
: Bytes): Int do
603 var bufsp
= _buffer_length
- p
606 buf
.append_ns_from
(_buffer
, i
, p
)
609 _buffer_pos
= _buffer_length
610 var readln
= _buffer_length
- p
611 buf
.append_ns_from
(_buffer
, readln
, p
)
612 var rd
= read_intern
(i
- readln
, buf
)
616 redef fun read_all_bytes
618 if last_error
!= null then return new Bytes.empty
619 var s
= new Bytes.with_capacity
(10)
623 var k
= _buffer_length
625 s
.append_ns_from
(b
, rd_sz
, j
)
632 redef fun append_line_to
(s
)
634 var lb
= new Bytes.with_capacity
(10)
636 # First phase: look for a '\n'
638 while i
< _buffer_length
and _buffer
[i
] != 0xAu
8 do
643 if i
< _buffer_length
then
644 assert _buffer
[i
] == 0xAu
8
651 # if there is something to append
652 if i
> _buffer_pos
then
653 # Copy from the buffer to the string
683 if _buffer_pos
< _buffer_length
then return false
684 if end_reached
then return true
686 return _buffer_pos
>= _buffer_length
and end_reached
690 private var buffer
: CString = new CString(0)
692 # The current position in the buffer
693 private var buffer_pos
= 0
695 # Length of the current buffer (i.e. nuber of bytes in the buffer)
696 private var buffer_length
= 0
698 # Capacity of the buffer
699 private var buffer_capacity
= 0
702 protected fun fill_buffer
is abstract
704 # Has the last fill_buffer reached the end
705 protected fun end_reached
: Bool is abstract
707 # Allocate a `_buffer` for a given `capacity`.
708 protected fun prepare_buffer
(capacity
: Int)
710 _buffer
= new CString(capacity
)
711 _buffer_pos
= 0 # need to read
713 _buffer_capacity
= capacity
717 # A `Stream` that can be written to and read from
718 abstract class Duplex
723 # Write to `bytes` in memory
726 # var writer = new BytesWriter
728 # writer.write "Strings "
729 # writer.write_char '&'
730 # writer.write_byte 0x20u8
731 # writer.write_bytes "bytes".to_bytes
733 # assert writer.to_s == "\\x53\\x74\\x72\\x69\\x6E\\x67\\x73\\x20\\x26\\x20\\x62\\x79\\x74\\x65\\x73"
734 # assert writer.bytes.to_s == "Strings & bytes"
737 # As with any binary data, UTF-8 code points encoded on two bytes or more
738 # can be constructed byte by byte.
741 # writer = new BytesWriter
743 # # Write just the character first half
744 # writer.write_byte 0xC2u8
745 # assert writer.to_s == "\\xC2"
746 # assert writer.bytes.to_s == "�"
748 # # Complete the character
749 # writer.write_byte 0xA2u8
750 # assert writer.to_s == "\\xC2\\xA2"
751 # assert writer.bytes.to_s == "¢"
757 var bytes
= new Bytes.empty
759 redef fun to_s
do return bytes
.chexdigest
763 if closed
then return
764 str
.append_to_bytes bytes
767 redef fun write_char
(c
)
769 if closed
then return
773 redef fun write_byte
(value
)
775 if closed
then return
779 redef fun write_bytes
(b
)
781 if closed
then return
785 # Is the stream closed?
786 protected var closed
= false
788 redef fun close
do closed
= true
789 redef fun is_writable
do return not closed
792 # `Stream` writing to a `String`
794 # This class has the same behavior as `BytesWriter`
795 # except for `to_s` which decodes `bytes` to a string.
798 # var writer = new StringWriter
800 # writer.write "Strings "
801 # writer.write_char '&'
802 # writer.write_byte 0x20u8
803 # writer.write_bytes "bytes".to_bytes
805 # assert writer.to_s == "Strings & bytes"
810 redef fun to_s
do return bytes
.to_s
813 # Read from `bytes` in memory
816 # var reader = new BytesReader(b"a…b")
817 # assert reader.read_char == 'a'
818 # assert reader.read_byte == 0xE2 # 1st byte of '…'
819 # assert reader.read_byte == 0x80 # 2nd byte of '…'
820 # assert reader.read_char == '�' # Reads the last byte as an invalid char
821 # assert reader.read_all_bytes == b"b"
826 # Source data to read
829 # The current position in `bytes`
830 private var cursor
= 0
834 if cursor
>= bytes
.length
then return null
836 var len
= bytes
.items
.length_of_char_at
(cursor
)
837 var char
= bytes
.items
.char_at
(cursor
)
844 if cursor
>= bytes
.length
then return -1
846 var c
= bytes
[cursor
]
851 redef fun close
do bytes
= new Bytes.empty
853 redef fun read_all_bytes
855 var res
= bytes
.slice_from
(cursor
)
856 cursor
= bytes
.length
860 redef fun raw_read_bytes
(ns
, max
) do
861 if cursor
>= bytes
.length
then return 0
863 var copy
= max
.min
(bytes
.length
- cursor
)
864 bytes
.items
.copy_to
(ns
, copy
, cursor
, 0)
869 redef fun eof
do return cursor
>= bytes
.length
872 # `Stream` reading from a `String` source
874 # This class has the same behavior as `BytesReader`
875 # except for its constructor accepting a `String`.
878 # var reader = new StringReader("a…b")
879 # assert reader.read_char == 'a'
880 # assert reader.read_byte == 0xE2 # 1st byte of '…'
881 # assert reader.read_byte == 0x80 # 2nd byte of '…'
882 # assert reader.read_char == '�' # Reads the last byte as an invalid char
883 # assert reader.read_all == "b"
890 # Source data to read
893 init do bytes
= source
.to_bytes