From 924780d92c148c8a76936d17599e64ab9d204860 Mon Sep 17 00:00:00 2001 From: kayomn Date: Mon, 20 Feb 2023 00:34:46 +0000 Subject: [PATCH] Update coral library to use new reader / writer system --- source/coral.cpp | 40 +++++++++++++++++++++------------------- 1 file changed, 21 insertions(+), 19 deletions(-) diff --git a/source/coral.cpp b/source/coral.cpp index 4d265c4..6e2826f 100644 --- a/source/coral.cpp +++ b/source/coral.cpp @@ -450,9 +450,13 @@ export namespace coral { unavailable, }; - using readable = callable(slice const &)>; + struct reader { + virtual expected read(slice const & buffer) = 0; + }; - using writable = callable(slice const &)>; + struct writer { + virtual expected write(slice const & buffer) = 0; + }; } // Input/output operations. @@ -533,30 +537,28 @@ export namespace coral { * *Note*: if `buffer` has a length of `0`, no data will be streamed as there is nowhere to * temporarily place data during streaming. */ - expected stream(writable const & output, - readable const & input, slice const & buffer) { + expected stream(writer & output, reader & input, slice const & buffer) { + usize total_bytes_written = 0; + expected bytes_read = input.read(buffer); - usize written = 0; - expected maybe_read = input(buffer); + if (!bytes_read.is_ok()) return bytes_read.error(); - if (!maybe_read.is_ok()) return maybe_read.error(); - - usize read = maybe_read.value(); + usize read = bytes_read.value(); while (read != 0) { - expected const maybe_written = output(buffer.sliced(0, read)); + expected const bytes_written = output.write(buffer.sliced(0, read)); - if (!maybe_written.is_ok()) return maybe_read.error(); + if (!bytes_written.is_ok()) return bytes_read.error(); - written += maybe_written.value(); - maybe_read = input(buffer); + total_bytes_written += bytes_written.value(); + bytes_read = input.read(buffer); - if (!maybe_read.is_ok()) return maybe_read.error(); + if (!bytes_read.is_ok()) return bytes_read.error(); - read = maybe_read.value(); + read = bytes_read.value(); } - return written; + return total_bytes_written; } /** @@ -565,8 +567,8 @@ export namespace coral { * The returned [expected] can be used to introspect if `output` encountered any issues during * printing, otherwise it will contain the number of characters used to print `value` as text. */ - expected print_unsigned(writable const & output, u64 value) { - if (value == 0) return output(slice{"0"}.as_bytes()); + expected print_unsigned(writer & output, u64 value) { + if (value == 0) return output.write(slice{"0"}.as_bytes()); u8 buffer[20]{0}; usize buffer_count{0}; @@ -584,7 +586,7 @@ export namespace coral { for (usize i = 0; i < half_buffer_count; i += 1) swap(buffer[i], buffer[buffer_count - i - 1]); - return output(slice{buffer, buffer_count}); + return output.write(slice{buffer, buffer_count}); } /**