diff src/dmzlib.c @ 1054:d98fcb10df6a

Work on dmzlib.
author Matti Hamalainen <ccr@tnsp.org>
date Sun, 01 Mar 2015 22:37:39 +0200
parents a726c1b9a41e
children e51ec592bfb6
line wrap: on
line diff
--- a/src/dmzlib.c	Sun Mar 01 22:27:08 2015 +0200
+++ b/src/dmzlib.c	Sun Mar 01 22:37:39 2015 +0200
@@ -17,14 +17,21 @@
 
 
 // @TODO: should statically initialize these for optimal thread safety
-static Uint8 dm_zdefault_length[288], dm_zdefault_distance[32];
+static Uint8 *dm_zdefault_length = NULL,
+             *dm_zdefault_distance = NULL;
 
 
-void dmZLibInit()
+int dmZLibInit()
 {
     int i;
 
     // Use <= to match clearly with DEFLATE spec
+    if ((dm_zdefault_length   = dmMalloc(288)) == NULL ||
+        (dm_zdefault_distance = dmMalloc(32)) == NULL)
+    {
+        return dmErrorDBG(DMERR_MALLOC,
+            "Failed to allocate zlib decompression tables.\n");
+    }
 
     // Literals 0  ..143:  8 bits, codes 00110000 .. 10111111
     for (i = 0; i <= 143; i++)
@@ -45,6 +52,17 @@
     // Default distances
     for (i = 0; i <= 31; i++)
         dm_zdefault_distance[i] = 5;
+
+    return DMERR_OK;
+}
+
+
+void dmZLibClose()
+{
+    dmFree(dm_zdefault_length);
+    dm_zdefault_length = NULL;
+    dmFree(dm_zdefault_distance);
+    dm_zdefault_distance = NULL;
 }
 
 
@@ -352,7 +370,9 @@
 }
 
 
-static const Uint8 dm_zlib_length_dezigzag[19] =
+#define DM_ZLIB_NCODELENGTH_SIZES 19
+
+static const Uint8 dm_zlib_length_dezigzag[DM_ZLIB_NCODELENGTH_SIZES] =
 {
     16, 17, 18,  0,  8,  7,  9,
     6 , 10, 5 , 11,  4, 12,  3,
@@ -363,8 +383,8 @@
 static int dmZLibComputeHuffmanCodes(DMZLibContext * ctx)
 {
     DMZHuffmanContext z_codelength;
-    Uint8 codeLengths[286 + 32 + 137];     // padding for maximum single op
-    Uint8 codeLengthSizes[19];
+    Uint8 codeLengths[288 + 32 + 137];     // padding for maximum single op
+    Uint8 codeLengthSizes[DM_ZLIB_NCODELENGTH_SIZES];
     int i, n, ret;
 
     int hlit  = dmZReceive(ctx, 5) + 257;
@@ -389,7 +409,7 @@
         if ((ret = dmZLibHuffmanDecode(ctx, &z_codelength, &c)) != DMERR_OK)
             return ret;
 
-        DMSTBI_ASSERT(c >= 0 && c < 19);
+        DMSTBI_ASSERT(c >= 0 && c < DM_ZLIB_NCODELENGTH_SIZES);
 
         if (c < 16)
             codeLengths[n++] = (Uint8) c;