#! @file reader.sakura #! @author John Christman (sorakatadzuma@gmail.com) #! @copyright Malunal Studios, LLC. #! @license MIT #! #! Contains `reader`, which reads any stream through a buffer a line or a number #! of bytes at a time, the standard input's reader, and `lines`, which walks #! what a reader reads line by line. import system; module std::io; # Bytes a reader asks what it reads for at a time. const reader_bytes: u64 = 16384; #! Reads any stream through a buffer, a line or a number of bytes at a time, and #! is closed where its scope ends. #! #! A reader is made by `reader_of`, which owns or borrows what it reads as it is #! given it: `reader_of(move(f))` owns the file `f` and closes it, #! `reader_of(&mut f)` borrows it and closes nothing of it, and #! `reader_of("text")` reads a view of text. #! #! The standard input is read through `io::input()`, which every part of the #! program shares, so what one part leaves in its buffer the next part reads. #! #! Each read waits only for what it needs: a line waits for its line break, and #! `read` gives whatever has arrived, so a reader serves a program that talks #! with another as it goes, as a language server does. #! #! A wait that a signal the program handles ends fails with #! `io_error::interrupted`, and leaves what was read of a line or of the bytes #! asked for in the reader, so the next read carries on from it. #! @tparam S The stream it reads, held by value where it owns it, or as `&mut` #! where it borrows it. pub struct reader : owning, readable where S: readable { var _source: S; var _open: bool; #! Whether it reads, which one moved from, closed, or never made does not. var _buffer: *mut u8; #! Null until the first read. var _start: u64; #! The first byte of the buffer not yet read. var _end: u64; #! The end of what the buffer holds. var _tied: bool; #! Whether the standard output is flushed before waiting. var _error: maybe; } # The standard input, as `input()` lends it. var standard_input: reader; #! Lends the reader of the standard input, which every part of the program #! shares. It flushes `output()` before it waits for anything to arrive, so a #! prompt written there shows first. #! @returns The reader, which is never closed by the program ending. pub def input(): &mut reader { standard_input._source._handle = system::fd::stdin; standard_input._open = true; standard_input._tied = true; return &mut standard_input; } #! Reads the next line of the standard input, as `input().read_line` does. #! @param alloc The optional allocator for the line to be held in. #! @returns The line, without its line break, or `nothing` once the input has #! ended or could not be read. pub def read_line(alloc: maybe<&mut allocator> = nothing{}): maybe { hold_console(&mut input_held); var line := input().read_line(alloc); let_go_console(&mut input_held); return move(&mut line); } #! Makes a reader of a stream, which owns what it is given: a stream given by #! value, as `move(f)` or a temporary, is the reader's, and closed where it #! closes, while one given by reference, as `&mut f`, is only borrowed. #! @tparam S The stream to read, as it is given. #! @param source The stream to read, from where it is. #! @returns The reader. pub def reader_of(source: S): reader where S: readable { return reader:: { _source = move(source), _open = true }; } #! Gives back the reader's buffer, and closes what it reads where it owns it. #! Closing the reader of the standard input leaves the input open, and `input()` #! lends it again. A reader that is closed, moved from, or never made reads #! nothing, failing with `io_error::invalid`. #! @param this The reader to close. pub def reader::close(&mut this): void { raw_release(this._buffer); this._buffer = null; this._start = 0; this._end = 0; if !this._open { return; } this._open = false; close(&mut this._source); } #! Why the last read gave less than it was asked for, where it was a failure #! rather than the end of the input. #! @param this The reader to ask. #! @returns The failure, or `nothing` where the last read did not fail. pub val reader::error: maybe { get => this._error; } #! Reads the next line, waiting until its line break has arrived. #! @param this The reader to read. #! @param alloc The optional allocator for the line to be held in. #! @returns The line, without the `\n` that ends it or a `\r` before that, or #! `nothing` once the input has ended, or could not be read, as `error` #! then says. A last line without a line break is still a line. pub def reader::read_line(&mut this, alloc: maybe<&mut allocator> = nothing{}): maybe { this._error = nothing{}; var line := string::new(alloc); var took: bool = false; while true { if this._start == this._end && !this.fill() { if this.interrupted() { this.put_back(line.span); return nothing{}; } if !took { return nothing{}; } return move(line); } took = true; val waiting := strview::over(this._buffer + this._start, this._end - this._start); var at := this._end; if waiting.index_of(&'\n') is some(found) { at = this._start + found; } line.append(strview::over(this._buffer + this._start, at - this._start)); if at == this._end { this._start = this._end; continue; } this._start = at + 1; if line.length > 0 && line[line.length - 1] == '\r' { line.resize(line.length - 1); } return move(line); } return nothing{}; } #! Lends the lines the reader reads, each as `read_line` gives it, so a loop #! walks them: `for line in input.lines()` closes each line where its pass ends. #! @param this The reader to read. #! @param alloc The optional allocator for the lines to be held in. #! @returns The lines, which end where the input does, or where reading fails, #! as the reader's `error` then says. pub def reader::lines(&mut this, alloc: maybe<&mut allocator> = nothing{}): lines { return lines:: { _from = this, _alloc = alloc }; } #! Reads whatever has arrived, waiting only where nothing has. #! @param this The reader to read. #! @param into Where the bytes read are written. #! @returns How many bytes were read, which is zero only at the end of the #! input. pub def reader::read(&mut this, into: slice): result { this._error = nothing{}; if into.length == 0 { return 0u; } if !this._open { return io_error::invalid; } # What is too large for the buffer to be worth passing through goes straight # where it is wanted. if this._start == this._end && into.length >= reader_bytes { if this._tied { _ = output().flush(); } return this._source.read(into); } if this._start == this._end && !this.fill() { if this._error is some(why) { return why; } return 0u; } return this.take(into.data, into.length); } #! Reads an exact number of bytes, waiting until they have all arrived. #! @param this The reader to read. #! @param count How many bytes to read. #! @param alloc The optional allocator for the bytes to be held in. #! @returns The bytes, or why they could not all be read, which is #! `io_error::unexpected_end` where the input ended first. pub def reader::read_exactly( &mut this, count: u64, alloc: maybe<&mut allocator> = nothing{} ): result { this._error = nothing{}; var made := string::new(alloc); made.reserve(count); while made.length < count { if this._start == this._end && !this.fill() { if this.interrupted() { this.put_back(made.span); } if this._error is some(why) { return why; } return io_error::unexpected_end; } val left := count - made.length; val have := this._end - this._start; val take := left < have ? left : have; made.append(span::::over(this._buffer + this._start, take)); this._start += take; } return move(made); } #! Reads the rest of the input, until it ends. #! @param this The reader to read. #! @param alloc The optional allocator for the bytes to be held in. #! @returns The bytes, or why they could not all be read. pub def reader::read_all(&mut this, alloc: maybe<&mut allocator> = nothing{}): result { this._error = nothing{}; var made := string::new(alloc); while true { if this._start == this._end && !this.fill() { if this.interrupted() { this.put_back(made.span); } if this._error is some(why) { return why; } return move(made); } made.append(span::::over(this._buffer + this._start, this._end - this._start)); this._start = this._end; } return move(made); } # Reads what has arrived into the buffer, which is empty, giving whether anything # had, and keeping the failure where reading failed. def reader::fill(&mut this): bool { if !this._open { this._error = io_error::invalid; return false; } if this._buffer == null { this._buffer = raw_allocate(reader_bytes); } if this._tied { _ = output().flush(); } val count := this._source.read(slice::::over(this._buffer, reader_bytes)) else (why) { this._error = why; return false; }; this._start = 0; this._end = count; return count > 0; } # Whether the last read failed because a signal the program handles ended its # wait. def reader::interrupted(&this): bool { if this._error is some(why) { return why == io_error::interrupted; } return false; } # Puts bytes taken from the buffer back in it, which holds nothing more, so the # next read finds them first, growing it where they are more than it holds. def reader::put_back(&mut this, bytes: span): void { if bytes.length > reader_bytes { this._buffer = raw_resize(this._buffer, bytes.length); } memcpy(this._buffer, bytes.data, bytes.length); this._start = 0; this._end = bytes.length; } # Copies as much of what the buffer holds as fits, giving how much that was. def reader::take(&mut this, into: *mut u8, length: u64): u64 { val have := this._end - this._start; val count := length < have ? length : have; memcpy(into, this._buffer + this._start, count); this._start += count; return count; } #! The lines a reader reads, as `reader::lines` lends them, each a `string` the #! loop walking them owns. #! @tparam S The stream the reader walked reads. pub struct lines : iter where S: readable { var _from: &mut reader; var _alloc: maybe<&mut allocator>; } #! Reads the next line. #! @param this The lines to advance. #! @returns The line, or `nothing` once the reader has none left. pub def lines::next(&mut this): maybe { return this._from.read_line(this._alloc); }