From: Joel Rosdahl Date: Thu, 6 Aug 2020 19:23:40 +0000 (+0200) Subject: Add and use Util::read_fd helper function X-Git-Tag: v4.0~203 X-Git-Url: http://git.ipfire.org/gitweb.cgi?a=commitdiff_plain;h=089067bdf4701cd73a54f912f1abe7d9242eb35b;p=thirdparty%2Fccache.git Add and use Util::read_fd helper function --- diff --git a/src/Hash.cpp b/src/Hash.cpp index da65d5830..9f493e45a 100644 --- a/src/Hash.cpp +++ b/src/Hash.cpp @@ -104,19 +104,8 @@ Hash::hash(int64_t x) 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 diff --git a/src/Util.cpp b/src/Util.cpp index 8c17a79fd..d3ac33cdf 100644 --- a/src/Util.cpp +++ b/src/Util.cpp @@ -289,16 +289,8 @@ common_dir_prefix_length(string_view dir, string_view path) 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 @@ -997,6 +989,22 @@ parse_uint32(const std::string& value) 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) { diff --git a/src/Util.hpp b/src/Util.hpp index d0843f65d..b9682cfd6 100644 --- a/src/Util.hpp +++ b/src/Util.hpp @@ -33,6 +33,7 @@ namespace Util { +using DataReceiver = std::function; using ProgressReceiver = std::function; using SubdirVisitor = std::function; @@ -330,6 +331,11 @@ uint64_t parse_size(const std::string& value); // 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). //