bool
Hash::hash_fd(int fd)
{
- char buf[READ_BUFFER_SIZE];
- ssize_t n;
-
- while ((n = read(fd, buf, sizeof(buf))) != 0) {
- if (n == -1 && errno != EINTR) {
- break;
- }
- if (n > 0) {
- hash_buffer(string_view(buf, n));
- add_debug_text(string_view(buf, n));
- }
- }
- return n >= 0;
+ return Util::read_fd(
+ fd, [=](const void* data, size_t size) { hash(data, size); });
}
bool
void
copy_fd(int fd_in, int fd_out)
{
- ssize_t n;
- char buf[READ_BUFFER_SIZE];
- while ((n = read(fd_in, buf, sizeof(buf))) != 0) {
- if (n == -1 && errno != EINTR) {
- break;
- }
- if (n > 0) {
- write_fd(fd_out, buf, n);
- }
- }
+ read_fd(fd_in,
+ [=](const void* data, size_t size) { write_fd(fd_out, data, size); });
}
void
return result;
}
+bool
+read_fd(int fd, DataReceiver data_receiver)
+{
+ ssize_t n;
+ char buffer[READ_BUFFER_SIZE];
+ while ((n = read(fd, buffer, sizeof(buffer))) != 0) {
+ if (n == -1 && errno != EINTR) {
+ break;
+ }
+ if (n > 0) {
+ data_receiver(buffer, n);
+ }
+ }
+ return n >= 0;
+}
+
std::string
read_file(const std::string& path, size_t size_hint)
{
namespace Util {
+using DataReceiver = std::function<void(const void* data, size_t size)>;
using ProgressReceiver = std::function<void(double progress)>;
using SubdirVisitor = std::function<void(
const std::string& dir_path, const ProgressReceiver& progress_receiver)>;
// Throws `Error` on error.
uint32_t parse_uint32(const std::string& value);
+// Read data from `fd` until end of file and call `data_receiver` with the read
+// data. Returns whether reading was successful, i.e. whether the read(2) call
+// did not return -1.
+bool read_fd(int fd, DataReceiver data_receiver);
+
// Return `path`'s content as a string. If `size_hint` is not 0 then assume that
// `path` has this size (this saves system calls).
//