util: add git__compress()
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81
diff --git a/src/compress.c b/src/compress.c
new file mode 100644
index 0000000..9388df1
--- /dev/null
+++ b/src/compress.c
@@ -0,0 +1,53 @@
+/*
+ * Copyright (C) 2009-2012 the libgit2 contributors
+ *
+ * This file is part of libgit2, distributed under the GNU GPL v2 with
+ * a Linking Exception. For full terms see the included COPYING file.
+ */
+
+#include "compress.h"
+
+#include <zlib.h>
+
+#define BUFFER_SIZE (1024 * 1024)
+
+int git__compress(git_buf *buf, const void *buff, size_t len)
+{
+ z_stream zs;
+ char *zb;
+ size_t have;
+
+ memset(&zs, 0, sizeof(zs));
+ if (deflateInit(&zs, Z_DEFAULT_COMPRESSION) != Z_OK)
+ return -1;
+
+ zb = git__malloc(BUFFER_SIZE);
+ GITERR_CHECK_ALLOC(zb);
+
+ zs.next_in = (void *)buff;
+ zs.avail_in = (uInt)len;
+
+ do {
+ zs.next_out = (unsigned char *)zb;
+ zs.avail_out = BUFFER_SIZE;
+
+ if (deflate(&zs, Z_FINISH) == Z_STREAM_ERROR) {
+ git__free(zb);
+ return -1;
+ }
+
+ have = BUFFER_SIZE - (size_t)zs.avail_out;
+
+ if (git_buf_put(buf, zb, have) < 0) {
+ git__free(zb);
+ return -1;
+ }
+
+ } while (zs.avail_out == 0);
+
+ assert(zs.avail_in == 0);
+
+ deflateEnd(&zs);
+ git__free(zb);
+ return 0;
+}
diff --git a/src/compress.h b/src/compress.h
new file mode 100644
index 0000000..4b73885
--- /dev/null
+++ b/src/compress.h
@@ -0,0 +1,16 @@
+/*
+ * Copyright (C) 2009-2012 the libgit2 contributors
+ *
+ * This file is part of libgit2, distributed under the GNU GPL v2 with
+ * a Linking Exception. For full terms see the included COPYING file.
+ */
+#ifndef INCLUDE_compress_h__
+#define INCLUDE_compress_h__
+
+#include "common.h"
+
+#include "buffer.h"
+
+int git__compress(git_buf *buf, const void *buff, size_t len);
+
+#endif /* INCLUDE_compress_h__ */