Add format support for efficient sparse file handling.
[cumulus.git] / sha1.cc
diff --git a/sha1.cc b/sha1.cc
index 1fc4ad7..3218075 100644 (file)
--- a/sha1.cc
+++ b/sha1.cc
 #include "sha1.h"
 
 #include <stddef.h>
+#include <stdio.h>
 #include <string.h>
 #include <arpa/inet.h>
 
+#include <string.h>
+
+using std::string;
+
 /* SWAP does an endian swap on architectures that are little-endian,
    as SHA1 needs some data in a big-endian form.  */
 #define SWAP(n) htonl(n)
@@ -339,13 +344,51 @@ SHA1Checksum::~SHA1Checksum()
 {
 }
 
-void SHA1Checksum::process(void *data, size_t len)
+void SHA1Checksum::process(const void *data, size_t len)
 {
     sha1_process_bytes(data, len, &ctx);
 }
 
+bool SHA1Checksum::process_file(const char *filename)
+{
+    FILE *f = fopen(filename, "rb");
+    if (f == NULL)
+        return false;
+
+    while (!feof(f)) {
+        char buf[4096];
+        size_t bytes = fread(buf, 1, sizeof(buf), f);
+
+        if (ferror(f)) {
+            fclose(f);
+            return false;
+        }
+
+        process(buf, bytes);
+    }
+
+    fclose(f);
+    return true;
+}
+
 const uint8_t *SHA1Checksum::checksum()
 {
     sha1_finish_ctx(&ctx, resbuf);
     return (const uint8_t *)resbuf;
 }
+
+string SHA1Checksum::checksum_str()
+{
+    uint8_t resbuf[20];
+    char hexbuf[4];
+    string result = "sha1=";
+
+    sha1_finish_ctx(&ctx, resbuf);
+
+    for (int i = 0; i < 20; i++) {
+        sprintf(hexbuf, "%02x", resbuf[i]);
+        result += hexbuf;
+    }
+
+    return result;
+}