]> git.ipfire.org Git - thirdparty/ccache.git/commitdiff
Add and use Util::read_fd helper function
authorJoel Rosdahl <joel@rosdahl.net>
Thu, 6 Aug 2020 19:23:40 +0000 (21:23 +0200)
committerJoel Rosdahl <joel@rosdahl.net>
Thu, 6 Aug 2020 19:23:54 +0000 (21:23 +0200)
src/Hash.cpp
src/Util.cpp
src/Util.hpp

index da65d5830d760f500238261b586f8146144ace9f..9f493e45a481ed08d5e2bf6830bec423b2f3ced6 100644 (file)
@@ -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
index 8c17a79fde6c9daa68476a4b6b6c6d3c05f2414a..d3ac33cdf39f32e74ede5f7ca531f2a4cad31f8c 100644 (file)
@@ -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)
 {
index d0843f65de9e3e9d3ac0a319114453e04e9e2073..b9682cfd6745fceba20b4c9e3d8913db3a455c91 100644 (file)
@@ -33,6 +33,7 @@
 
 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)>;
@@ -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).
 //