aboutsummaryrefslogtreecommitdiff
path: root/src/libutil/serialise.hh
diff options
context:
space:
mode:
authoreldritch horrors <pennae@lix.systems>2024-06-27 21:23:50 +0200
committereldritch horrors <pennae@lix.systems>2024-07-05 22:28:16 +0000
commitb51ea465de48e4c5516ba0182cc642b4e644be10 (patch)
treeed8aa9edc953af11c29a7e6b4d4f811555568d22 /src/libutil/serialise.hh
parentb9f91ec3c5da5b59ff095011493dd6d2093bdd3d (diff)
libutil: allow construction of sources from generators
Change-Id: I78ff8d0720f06bce731e26d5e1c53b1382bbd589
Diffstat (limited to 'src/libutil/serialise.hh')
-rw-r--r--src/libutil/serialise.hh28
1 files changed, 28 insertions, 0 deletions
diff --git a/src/libutil/serialise.hh b/src/libutil/serialise.hh
index 2651ec979..874c67b75 100644
--- a/src/libutil/serialise.hh
+++ b/src/libutil/serialise.hh
@@ -334,6 +334,34 @@ struct ChainSource : Source
size_t read(char * data, size_t len) override;
};
+struct GeneratorSource : Source
+{
+ GeneratorSource(Generator<Bytes> && g) : g(std::move(g)) {}
+
+ virtual size_t read(char * data, size_t len)
+ {
+ // we explicitly do not poll the generator multiple times to fill the
+ // buffer, only to produce some output at all. this is allowed by the
+ // semantics of read(), only operator() must fill the buffer entirely
+ while (!buf.size()) {
+ if (auto next = g.next()) {
+ buf = *next;
+ } else {
+ throw EndOfFile("coroutine has finished");
+ }
+ }
+
+ len = std::min(len, buf.size());
+ memcpy(data, buf.data(), len);
+ buf = buf.subspan(len);
+ return len;
+ }
+
+private:
+ Generator<Bytes> g;
+ Bytes buf{};
+};
+
std::unique_ptr<FinishSink> sourceToSink(std::function<void(Source &)> fun);
/**