| 1 |
// SPDX-License-Identifier: MPL-2.0 |
| 2 |
// (c) Hare authors <https://harelang.org> |
| 3 |
|
| 4 |
export type unstream = struct { |
| 5 |
vtable: stream, |
| 6 |
source: handle, |
| 7 |
buf: []u8, |
| 8 |
}; |
| 9 |
|
| 10 |
const unstream_vtable = vtable { |
| 11 |
reader = &unstream_read, |
| 12 |
closer = &unstream_close, |
| 13 |
... |
| 14 |
}; |
| 15 |
|
| 16 |
// Create an overlay stream that allows bytes to be "unread", such that the |
| 17 |
// unread bytes are always returned before new bytes are fetched from the |
| 18 |
// underlying stream. For example, |
| 19 |
// |
| 20 |
// let s = io::unreader(...); |
| 21 |
// io::unread(&s, [3, 4])!; |
| 22 |
// io::unread(&s, [1, 2])!; |
| 23 |
// let buf: [4]u8 = [0...]; |
| 24 |
// io::read(&s, buf)!; |
| 25 |
// |
| 26 |
// will fill buf with [1, 2, 3, 4] and not issue any reads to the underlying |
| 27 |
// stream. |
| 28 |
// |
| 29 |
// There is no limit to the number of bytes which may be unread. The unreader |
| 30 |
// stream must be closed, and doing so will not automatically close the |
| 31 |
// underlying stream. |
| 32 |
export fn unreader(source: handle) unstream = unstream { |
| 33 |
vtable = &unstream_vtable, |
| 34 |
source = source, |
| 35 |
buf = [], |
| 36 |
}; |
| 37 |
|
| 38 |
// Unreads bytes onto an unreader stream, such that they're returned before new |
| 39 |
// bytes are fetched from the underlying stream. See [[unreader]] for details. |
| 40 |
export fn unread(s: *unstream, buf: []u8) (void | nomem) = { |
| 41 |
insert(s.buf[0], buf...)?; |
| 42 |
}; |
| 43 |
|
| 44 |
fn unstream_read(s: *stream, buf: []u8) (size | EOF | error) = { |
| 45 |
let s = s: *unstream; |
| 46 |
assert(s.vtable == &unstream_vtable); |
| 47 |
assert(len(buf) != 0); |
| 48 |
|
| 49 |
let z = if (len(s.buf) < len(buf)) len(s.buf) else len(buf); |
| 50 |
if (z != 0) { |
| 51 |
buf[..z] = s.buf[..z]; |
| 52 |
buf = buf[z..]; |
| 53 |
delete(s.buf[..z]); |
| 54 |
}; |
| 55 |
|
| 56 |
match (read(s.source, buf)?) { |
| 57 |
case EOF => |
| 58 |
if (z == 0) { |
| 59 |
return EOF; |
| 60 |
} else { |
| 61 |
return z; |
| 62 |
}; |
| 63 |
case let z2: size => |
| 64 |
return z + z2; |
| 65 |
}; |
| 66 |
}; |
| 67 |
|
| 68 |
fn unstream_close(s: *stream) (void | error) = { |
| 69 |
let s = s: *unstream; |
| 70 |
assert(s.vtable == &unstream_vtable); |
| 71 |
|
| 72 |
free(s.buf); |
| 73 |
}; |