From 2092e2167e45fc2651f87129629ad5d93beb9087 Mon Sep 17 00:00:00 2001 From: Christoffer Lerno Date: Tue, 10 Sep 2024 13:20:08 +0200 Subject: [PATCH] Add `io::read_new_fully` for reading to the end of a stream. Add `io::wrap_bytes` for reading bytes with `io` functions. --- lib/std/io/io.c3 | 8 ++++++++ lib/std/io/stream.c3 | 16 ++++++++++++++++ releasenotes.md | 2 ++ 3 files changed, 26 insertions(+) diff --git a/lib/std/io/io.c3 b/lib/std/io/io.c3 index 17a920d8c..60a02beb5 100644 --- a/lib/std/io/io.c3 +++ b/lib/std/io/io.c3 @@ -401,3 +401,11 @@ fn File* stdin() { return &stdin_file; } + +/** + * Wrap bytes for reading using io functions. + **/ +fn ByteReader wrap_bytes(char[] bytes) +{ + return { bytes, 0 }; +} \ No newline at end of file diff --git a/lib/std/io/stream.c3 b/lib/std/io/stream.c3 index 9191a1092..4f8423554 100644 --- a/lib/std/io/stream.c3 +++ b/lib/std/io/stream.c3 @@ -77,6 +77,22 @@ macro usz! read_all(stream, char[] buffer) return n; } +/** + * @require @is_instream(stream) + */ +macro char[]! read_new_fully(stream, Allocator allocator = allocator::heap()) +{ + usz len = available(stream)!; + char* data = allocator::malloc_try(allocator, len)!; + defer catch allocator::free(allocator, data); + usz read = 0; + while (read < len) + { + read += stream.read(data[read:len - read])!; + } + return data[:len]; +} + /** * @require @is_outstream(stream) */ diff --git a/releasenotes.md b/releasenotes.md index 61262f81f..b4b9f7ca6 100644 --- a/releasenotes.md +++ b/releasenotes.md @@ -24,6 +24,8 @@ - Additional init functions for hashmap. - `format` functions are now functions and work better with splat. - Add support for the QOI format. +- Add `io::read_new_fully` for reading to the end of a stream. +- Add `io::wrap_bytes` for reading bytes with `io` functions. ## 0.6.2 Change list