[Mesa-dev] [PATCH 6/7] util/disk_cache: add a write helper

Grazvydas Ignotas notasas at gmail.com
Wed Mar 15 23:09:32 UTC 2017


Simplifies the write code a bit and handles EINTR.

Signed-off-by: Grazvydas Ignotas <notasas at gmail.com>
---
 src/util/disk_cache.c | 40 ++++++++++++++++++++++++++--------------
 1 file changed, 26 insertions(+), 14 deletions(-)

diff --git a/src/util/disk_cache.c b/src/util/disk_cache.c
index 904aa66..ad591be 100644
--- a/src/util/disk_cache.c
+++ b/src/util/disk_cache.c
@@ -650,6 +650,24 @@ disk_cache_remove(struct disk_cache *cache, const cache_key key)
       p_atomic_add(cache->size, - (uint64_t)sb.st_size);
 }
 
+static ssize_t
+write_all(int fd, const void *buf, size_t count)
+{
+   const char *out = buf;
+   ssize_t written;
+   size_t done;
+
+   for (done = 0; done < count; done += written) {
+      written = write(fd, out + done, count - done);
+      if (written == -1) {
+         if (errno != EINTR)
+            return -1;
+         written = 0;
+      }
+   }
+   return done;
+}
+
 /* From the zlib docs:
  *    "If the memory is available, buffers sizes on the order of 128K or 256K
  *    bytes should be used."
@@ -699,13 +717,10 @@ deflate_and_write_to_disk(const void *in_data, size_t in_data_size, int dest,
          size_t have = BUFSIZE - strm.avail_out;
          compressed_size += have;
 
-         size_t written = 0;
-         for (size_t len = 0; len < have; len += written) {
-            written = write(dest, out + len, have - len);
-            if (written == -1) {
-               (void)deflateEnd(&strm);
-               return 0;
-            }
+         ssize_t written = write_all(dest, out, have);
+         if (written == -1) {
+            (void)deflateEnd(&strm);
+            return 0;
          }
       } while (strm.avail_out == 0);
 
@@ -760,7 +775,6 @@ cache_put(void *job, int thread_index)
 
    int fd = -1, fd_final = -1, err, ret;
    unsigned i = 0;
-   size_t len;
    char *filename = NULL, *filename_tmp = NULL;
    struct disk_cache_put_job *dc_job = (struct disk_cache_put_job *) job;
 
@@ -827,12 +841,10 @@ cache_put(void *job, int thread_index)
    cf_data.uncompressed_size = dc_job->size;
 
    size_t cf_data_size = sizeof(cf_data);
-   for (len = 0; len < cf_data_size; len += ret) {
-      ret = write(fd, ((uint8_t *) &cf_data) + len, cf_data_size - len);
-      if (ret == -1) {
-         unlink(filename_tmp);
-         goto done;
-      }
+   ret = write_all(fd, &cf_data, cf_data_size);
+   if (ret == -1) {
+      unlink(filename_tmp);
+      goto done;
    }
 
    /* Now, finally, write out the contents to the temporary file, then
-- 
2.7.4



More information about the mesa-dev mailing list