From: Jean Privat Date: Thu, 14 May 2015 23:35:54 +0000 (-0400) Subject: Merge: Read char X-Git-Tag: v0.7.5~53 X-Git-Url: http://nitlanguage.org Merge: Read char Semantics have been changed, before this PR, read_char was used to read a single byte and return -1 if EOF or timeout. Since a Byte can have a value of -1, it is changed here: * `read_char` now returns a Char (which, for the moment, is a byte, but this will change once UTF-8 is properly supported), and returns null on EOF or timeout * `read_byte` has more or less the semantics of the old read_char, but returns null on EOF instead of -1 for the reasons mentioned earlier which could induce a wrong assumption about the state of the Stream Edit: Still related to #1309 Pull-Request: #1334 Reviewed-by: Alexandre Terrasa Reviewed-by: Jean Privat --- 506f4b1efdd9d548becca066036e3cd5c1456a09 diff --cc lib/standard/stream.nit index 4ad6af1,884368d..6b6d3fe --- a/lib/standard/stream.nit +++ b/lib/standard/stream.nit @@@ -382,44 -383,28 +383,56 @@@ abstract class BufferedReade super Reader redef fun read_char do - if last_error != null then return -1 + if last_error != null then return null if eof then last_error = new IOError("Stream has reached eof") - return -1 + return null end - var c = _buffer.chars[_buffer_pos] + var c = _buffer[_buffer_pos] _buffer_pos += 1 - return c.ascii + return c + end + + redef fun read_byte + do + if last_error != null then return null + if eof then + last_error = new IOError("Stream has reached eof") + return null + end + var c = _buffer[_buffer_pos].ascii + _buffer_pos += 1 + return c end + # Peeks up to `n` bytes in the buffer, returns an empty string on EOF + # + # The operation does not consume the buffer + # + # ~~~nitish + # var x = new FileReader("File.txt") + # assert x.peek(5) == x.read(5) + # ~~~ + fun peek(i: Int): String do + if eof then return "" + var b = new FlatBuffer.with_capacity(i) + while i > 0 and not eof do + b.add _buffer[_buffer_pos] + _buffer_pos += 1 + i -= 1 + end + var nbuflen = b.length + (_buffer.length - _buffer_pos) + var nbuf = new FlatBuffer.with_capacity(nbuflen) + nbuf.append(b) + while _buffer_pos < _buffer.length do + nbuf.add(_buffer[_buffer_pos]) + _buffer_pos += 1 + end + _buffer_pos = 0 + _buffer = nbuf + return b.to_s + end + redef fun read(i) do if last_error != null then return ""