libutil: allow construction of sources from generators

Change-Id: I78ff8d0720f06bce731e26d5e1c53b1382bbd589
This commit is contained in:
eldritch horrors
2024-06-30 19:29:07 +02:00
parent 379a892afb
commit 1540bdbcfc
+25
View File
@@ -334,6 +334,31 @@ 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)
{
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);
/**