73 lines
2.1 KiB
Plaintext
73 lines
2.1 KiB
Plaintext
#! @file streams.sakura
|
|
#! @author John Christman (sorakatadzuma@gmail.com)
|
|
#! @copyright Malunal Studios, LLC.
|
|
#! @license MIT
|
|
#!
|
|
#! Contains `copy_all` and `read_all`, which use any stream while they run: one
|
|
#! copies a stream to its end into another, the other reads one to its end into
|
|
#! a `string`.
|
|
|
|
|
|
import system;
|
|
module std::io;
|
|
|
|
# These only use a stream while they run, so they borrow it as a trait reference:
|
|
# what keeps a stream, as a reader or writer does, is generic over it instead.
|
|
|
|
# Bytes copied at a time.
|
|
const copy_bytes: u64 = 16384;
|
|
|
|
#! Copies everything a stream has left into another, until it ends.
|
|
#! @param from The stream to read, to its end.
|
|
#! @param to The stream to write, which is not flushed: whoever made it does
|
|
#! that.
|
|
#! @returns How many bytes were copied, or why reading or writing failed.
|
|
pub def copy_all(from: &mut readable, to: &mut writable): result<u64, io_error> {
|
|
val chunk := raw_allocate(copy_bytes);
|
|
var total := 0u;
|
|
while true {
|
|
val count := from.read(slice::<u8>::over(chunk, copy_bytes)) else (why) {
|
|
raw_release(chunk);
|
|
return why;
|
|
};
|
|
if count == 0 {
|
|
break;
|
|
}
|
|
|
|
to.write(span::<u8>::over(chunk as *u8, count)) else (why) {
|
|
raw_release(chunk);
|
|
return why;
|
|
};
|
|
total += count;
|
|
}
|
|
|
|
raw_release(chunk);
|
|
return total;
|
|
}
|
|
|
|
#! Reads everything a stream has left, until it ends.
|
|
#! @param from The stream 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 read_all(from: &mut readable, alloc: maybe<&mut allocator> = nothing{}): result<string, io_error> {
|
|
var made := string::new(alloc);
|
|
made.reserve(copy_bytes);
|
|
while true {
|
|
if made.length == made.capacity {
|
|
made.reserve(made.capacity * 2);
|
|
}
|
|
|
|
# The read fills the room made, which is then cut back to what it read.
|
|
val had := made.length;
|
|
made.resize(made.capacity);
|
|
val count := from.read(made.slice()[had:]) else (why) {
|
|
return why;
|
|
};
|
|
made.resize(had + count);
|
|
if count == 0 {
|
|
break;
|
|
}
|
|
}
|
|
return move(made);
|
|
}
|