libutil: return a source from readFile

don't consume a sink, return a source instead. the only reason to not do
this is a very slight reduction in dynamic allocations, but since we are
going to *at least* do disk io that will not be a lot of overhead anyway

Change-Id: Iae2f879ec64c3c3ac1d5310eeb6a85e696d4614a
This commit is contained in:
eldritch horrors
2024-06-19 10:50:12 +00:00
parent 67f778670c
commit 11f4a5bc7e
10 changed files with 19 additions and 13 deletions
+7 -2
View File
@@ -289,12 +289,17 @@ std::string readFile(const Path & path)
}
void readFile(const Path & path, Sink & sink)
box_ptr<Source> readFileSource(const Path & path)
{
AutoCloseFD fd{open(path.c_str(), O_RDONLY | O_CLOEXEC)};
if (!fd)
throw SysError("opening file '%s'", path);
drainFD(fd.get(), sink);
struct FileSource : FdSource {
AutoCloseFD fd;
explicit FileSource(AutoCloseFD fd) : FdSource(fd.get()), fd(std::move(fd)) {}
};
return make_box_ptr<FileSource>(std::move(fd));
}
+2 -1
View File
@@ -5,6 +5,7 @@
* Utiltities for working with the file sytem and file paths.
*/
#include "box_ptr.hh"
#include "types.hh"
#include "file-descriptor.hh"
@@ -142,7 +143,7 @@ unsigned char getFileType(const Path & path);
* Read the contents of a file into a string.
*/
std::string readFile(const Path & path);
void readFile(const Path & path, Sink & sink);
box_ptr<Source> readFileSource(const Path & path);
/**
* Write a string to a file.
+1 -1
View File
@@ -324,7 +324,7 @@ Hash hashString(HashType ht, std::string_view s)
Hash hashFile(HashType ht, const Path & path)
{
HashSink sink(ht);
readFile(path, sink);
readFileSource(path)->drainInto(sink);
return sink.finish().first;
}