add lz4 compression options to eet. remove amalgamated build too.
authorraster <raster@7cbeb6ba-43b4-40fd-8cce-4c39aea84d33>
Tue, 15 May 2012 12:27:56 +0000 (12:27 +0000)
committerraster <raster@7cbeb6ba-43b4-40fd-8cce-4c39aea84d33>
Tue, 15 May 2012 12:27:56 +0000 (12:27 +0000)
git-svn-id: svn+ssh://svn.enlightenment.org/var/svn/e/trunk/eet@71111 7cbeb6ba-43b4-40fd-8cce-4c39aea84d33

ChangeLog
configure.ac
src/lib/Eet.h
src/lib/Eet_private.h
src/lib/Makefile.am
src/lib/eet_image.c
src/lib/eet_lib.c
src/lib/lz4/lz4.c [new file with mode: 0644]
src/lib/lz4/lz4.h [new file with mode: 0644]
src/lib/lz4/lz4hc.c [new file with mode: 0644]
src/lib/lz4/lz4hc.h [new file with mode: 0644]

index 43e85b2..9df47e5 100644 (file)
--- a/ChangeLog
+++ b/ChangeLog
 
        * Force destruction of all pending file when shuting down eet.
 
+2012-05-14  Carsten Haitzler (The Rasterman)
+
+        * Add LZ4/LZ4HC compression & decompression capabilities
+
 2012-05-15  Cedric Bail
 
        * Make eet_dictionary thread safe.
index 882fda8..8e9a0c3 100644 (file)
@@ -72,23 +72,6 @@ want_signature="yes"
 
 requirement_eet=""
 
-
-### Additional options to configure
-
-# Amalgamation
-
-AC_ARG_ENABLE([amalgamation],
-   [AC_HELP_STRING([--enable-amalgamation], [enable generation of one single file with all source code in it, helps compiler optimizations.])],
-   [if test "x${enableval}" = "xyes"; then
-       do_amalgamation="yes"
-    else
-       do_amalgamation="no"
-    fi
-   ],
-   [do_amalgamation="no"]
-)
-AM_CONDITIONAL(EET_AMALGAMATION, test "x${do_amalgamation}" = "xyes")
-
 EFL_ENABLE_BIN([eet])
 
 # Old eet file format support
@@ -516,7 +499,6 @@ echo "------------------------------------------------------------------------"
 echo
 echo "Configuration Options Summary:"
 echo
-echo "  Amalgamation.........: ${do_amalgamation}"
 echo "  Secure layer.........: ${secure_layer}"
 if test "x${have_gnutls}" = "xyes" || test "x${have_openssl}" = "xyes" ; then
    echo "    Cipher support.....: ${have_cipher}"
index 6207294..c525a9b 100644 (file)
@@ -259,6 +259,39 @@ typedef enum _Eet_Error
 /**
  * @}
  */
+   
+/**
+ * @defgroup Eet_Compression Eet Compression Levels
+ * Compression modes/levels supported by Eet.
+ *
+ * @{
+ */
+
+/**
+ * @enum _Eet_Compression
+ * All the compression modes known by Eet.
+ */
+
+typedef enum _Eet_Compression
+{
+   EET_COMPRESSION_NONE      = 0,  /**< No compression at all */
+   EET_COMPRESSION_DEFAULT   = 1,  /**< Default compression (Zlib) */
+   EET_COMPRESSION_LOW       = 2,  /**< Fast but minimal compression (Zlib) */
+   EET_COMPRESSION_MED       = 6,  /**< Medium compression level (Zlib) */
+   EET_COMPRESSION_HI        = 9,  /**< Slow but high compression level (Zlib) */
+   EET_COMPRESSION_VERYFAST  = 10, /**< Very fast, but lower compression ratio (LZ4HC) */
+   EET_COMPRESSION_SUPERFAST = 11, /**< Very fast, but lower compression ratio (faster to compress than EET_COMPRESSION_VERYFAST)  (LZ4) */
+     
+   EET_COMPRESSION_LOW2      = 3,  /**< Space filler for compatibility. Don't use it */
+   EET_COMPRESSION_MED1      = 4,  /**< Space filler for compatibility. Don't use it */
+   EET_COMPRESSION_MED2      = 5,  /**< Space filler for compatibility. Don't use it */
+   EET_COMPRESSION_HI1       = 7,  /**< Space filler for compatibility. Don't use it */
+   EET_COMPRESSION_HI2       = 8   /**< Space filler for compatibility. Don't use it */
+} Eet_Compression; /**< Eet compression modes */
+   
+/**
+ * @}
+ */
 
 /**
  * Initialize the EET library.
index afd4685..20c12d7 100644 (file)
@@ -125,6 +125,8 @@ struct _Eet_File_Node
    unsigned int      size;
    unsigned int      data_size;
 
+   unsigned char     compression_type;
+   
    unsigned char     free_name : 1;
    unsigned char     compression : 1;
    unsigned char     ciphered : 1;
index ae60168..952cc9d 100644 (file)
@@ -4,6 +4,7 @@ MAINTAINERCLEANFILES = Makefile.in
 AM_CPPFLAGS = \
 -I. \
 -I$(top_srcdir)/src/lib \
+-I$(top_srcdir)/src/lib/lz4 \
 -I$(top_builddir)/src/lib \
 -DPACKAGE_BIN_DIR=\"$(bindir)\" \
 -DPACKAGE_LIB_DIR=\"$(libdir)\" \
@@ -21,7 +22,7 @@ includesdir = $(includedir)/eet-@VMAJ@
 
 lib_LTLIBRARIES = libeet.la
 
-base_sources = \
+libeet_la_SOURCES = \
 eet_alloc.c \
 eet_lib.c \
 eet_data.c \
@@ -30,128 +31,11 @@ eet_cipher.c \
 eet_dictionary.c \
 eet_node.c \
 eet_utils.c \
-eet_connection.c
-
-if EET_AMALGAMATION
-nodist_libeet_la_SOURCES = eet_amalgamation.c
-
-eet_amalgamation.c: $(base_sources) Makefile
-       -rm -f eet_amalgamation.c
-
-       @echo "#ifdef HAVE_CONFIG_H" >> eet_amalgamation.c
-       @echo "# include \"config.h\"" >> eet_amalgamation.c
-       @echo "#endif" >> eet_amalgamation.c
-
-       @echo "#ifdef HAVE_ALLOCA_H" >> eet_amalgamation.c
-       @echo "# include <alloca.h>" >> eet_amalgamation.c
-       @echo "#elif defined __GNUC__" >> eet_amalgamation.c
-       @echo "# define alloca __builtin_alloca" >> eet_amalgamation.c
-       @echo "#elif defined _AIX" >> eet_amalgamation.c
-       @echo "# define alloca __alloca" >> eet_amalgamation.c
-       @echo "#elif defined _MSC_VER" >> eet_amalgamation.c
-       @echo "# include <malloc.h>" >> eet_amalgamation.c
-       @echo "# define alloca _alloca" >> eet_amalgamation.c
-       @echo "#else" >> eet_amalgamation.c
-       @echo "# include <stddef.h>" >> eet_amalgamation.c
-       @echo "# ifdef __cplusplus" >> eet_amalgamation.c
-       @echo "#extern \"C\"" >> eet_amalgamation.c
-       @echo "# endif" >> eet_amalgamation.c
-       @echo "#void *alloca (size_t);" >> eet_amalgamation.c
-       @echo "#endif" >> eet_amalgamation.c
-
-       @echo "#include <stdio.h>" >> eet_amalgamation.c
-       @echo "#include <string.h>" >> eet_amalgamation.c
-       @echo "#include <math.h>" >> eet_amalgamation.c
-       @echo "#include <ctype.h>" >> eet_amalgamation.c
-       @echo "#include <limits.h>" >> eet_amalgamation.c
-       @echo "#include <sys/types.h>" >> eet_amalgamation.c
-       @echo "#include <sys/stat.h>" >> eet_amalgamation.c
-       @echo "#ifdef HAVE_SIGNATURE" >> eet_amalgamation.c
-       @echo "# include <sys/mman.h>" >> eet_amalgamation.c
-       @echo "#endif" >> eet_amalgamation.c
-       @echo "#include <setjmp.h>" >> eet_amalgamation.c
-       @echo "#include <errno.h>" >> eet_amalgamation.c
-       @echo "#include <time.h>" >> eet_amalgamation.c
-       @echo "#include <fnmatch.h>" >> eet_amalgamation.c
-       @echo "#include <fcntl.h>" >> eet_amalgamation.c
-
-       @echo "#ifdef _WIN32" >> eet_amalgamation.c
-       @echo "# include <winsock2.h>" >> eet_amalgamation.c
-       @echo "#endif" >> eet_amalgamation.c
-
-       @echo "#ifndef _MSC_VER" >> eet_amalgamation.c
-       @echo "# include <unistd.h>" >> eet_amalgamation.c
-       @echo "#endif" >> eet_amalgamation.c
-
-       @echo "#ifdef HAVE_NETINET_IN_H" >> eet_amalgamation.c
-       @echo "# include <netinet/in.h>" >> eet_amalgamation.c
-       @echo "#endif" >> eet_amalgamation.c
-
-       @echo "#ifdef HAVE_GNUTLS" >> eet_amalgamation.c
-       @echo "# include <gnutls/gnutls.h>" >> eet_amalgamation.c
-       @echo "# include <gcrypt.h>" >> eet_amalgamation.c
-       @echo "#endif" >> eet_amalgamation.c
-
-       @echo "#ifdef HAVE_OPENSSL" >> eet_amalgamation.c
-       @echo "# include <openssl/err.h>" >> eet_amalgamation.c
-       @echo "# include <openssl/evp.h>" >> eet_amalgamation.c
-       @echo "# include <openssl/sha.h>" >> eet_amalgamation.c
-       @echo "#endif" >> eet_amalgamation.c
-
-       @echo "#ifdef HAVE_SIGNATURE" >> eet_amalgamation.c
-       @echo "# ifdef HAVE_GNUTLS" >> eet_amalgamation.c
-       @echo "#  include <gnutls/gnutls.h>" >> eet_amalgamation.c
-       @echo "#  include <gnutls/x509.h>" >> eet_amalgamation.c
-       @echo "# else" >> eet_amalgamation.c
-       @echo "#  include <openssl/rsa.h>" >> eet_amalgamation.c
-       @echo "#  include <openssl/objects.h>" >> eet_amalgamation.c
-       @echo "#  include <openssl/err.h>" >> eet_amalgamation.c
-       @echo "#  include <openssl/ssl.h>" >> eet_amalgamation.c
-       @echo "#  include <openssl/dh.h>" >> eet_amalgamation.c
-       @echo "#  include <openssl/dsa.h>" >> eet_amalgamation.c
-       @echo "#  include <openssl/evp.h>" >> eet_amalgamation.c
-       @echo "#  include <openssl/x509.h>" >> eet_amalgamation.c
-       @echo "#  include <openssl/pem.h>" >> eet_amalgamation.c
-       @echo "# endif" >> eet_amalgamation.c
-       @echo "#endif" >> eet_amalgamation.c
-
-       @echo "#ifdef HAVE_CIPHER" >> eet_amalgamation.c
-       @echo "# ifdef HAVE_GNUTLS" >> eet_amalgamation.c
-       @echo "#  include <gnutls/x509.h>" >> eet_amalgamation.c
-       @echo "#  include <gcrypt.h>" >> eet_amalgamation.c
-       @echo "# else" >> eet_amalgamation.c
-       @echo "#  include <openssl/evp.h>" >> eet_amalgamation.c
-       @echo "#  include <openssl/hmac.h>" >> eet_amalgamation.c
-       @echo "#  include <openssl/rand.h>" >> eet_amalgamation.c
-       @echo "# endif" >> eet_amalgamation.c
-       @echo "#endif" >> eet_amalgamation.c
-
-       @echo "#include <zlib.h>" >> eet_amalgamation.c
-       @echo "#include <jpeglib.h>" >> eet_amalgamation.c
-
-       @echo "#ifdef HAVE_EVIL" >> eet_amalgamation.c
-       @echo "# include <Evil.h>" >> eet_amalgamation.c
-       @echo "#endif" >> eet_amalgamation.c
-
-       @echo "#include <Eet.h>" >> eet_amalgamation.c
-
-       @echo "#include \"Eet_private.h\"" >> eet_amalgamation.c
-       @echo "#include \"Eet.h\"" >> eet_amalgamation.c
-
-       @for f in $(base_sources); do \
-          if [ `echo $$f | sed -e 's/^...\(.\).*/\1/'` != '/' ]; then \
-                 file="$(srcdir)/$$f" ; \
-          else \
-                 file="$$f" ; \
-          fi ; \
-          echo "/* file: $$file */" >> eet_amalgamation.c; \
-          grep -v -e '^# *include \+.\(config\|\|Evil\|Eina\|stdio\|string\|math\|ctype\|limits\|sys/types\|sys/stat\|sys/mman\|setjmp\|errno\|time\|fnmatch\|fcntl\|winsock2\|unistd\|netinet/in\|gnutls/gnutls\|gcrypt\|gnutls/x509\|openssl/rsa\|openssl/objects\|openssl/err\|openssl/ssl\|openssl/dh\|openssl/dsa\|openssl/evp\|openssl/pem\|openssl/sha\|openssl/hmac\|openssl/x509\|openssl/rand\|zlib\|jpeglib\|Eet_private\|Eet\)[.]h.*' $$file >> eet_amalgamation.c; \
-       done
-       @echo "eet_amalgamation.c generated"
-
-else
-libeet_la_SOURCES = $(base_sources)
-endif
+eet_connection.c \
+lz4/lz4.c \
+lz4/lz4.h \
+lz4/lz4hc.c \
+lz4/lz4hc.h
 
 libeet_la_CFLAGS = @EET_CFLAGS@ @DEBUG_CFLAGS@
 libeet_la_LIBADD = @GNUTLS_LIBS@ @OPENSSL_LIBS@ @EFL_COVERAGE_LIBS@ @EET_LIBS@ @EINA_LIBS@ @EVIL_LIBS@ -lz -ljpeg -lm
index b622236..00acda8 100644 (file)
@@ -40,6 +40,9 @@ void *alloca(size_t);
 #include "Eet.h"
 #include "Eet_private.h"
 
+#include "lz4.h"
+#include "lz4hc.h"
+
 /*---*/
 
 typedef struct _JPEG_error_mgr *emptr;
@@ -742,55 +745,68 @@ eet_data_image_lossless_compressed_convert(int         *size,
      }
 
    {
-      unsigned char *d;
-      unsigned char *comp;
-      int *header;
-      int ret;
-      uLongf buflen;
-
-      d = malloc((w * h * 4) + (8 * 4));
-      if (!d)
-        return NULL;
+      unsigned char *d, *comp;
+      int *header, ret, ok = 1;
+      uLongf buflen = 0;
 
       buflen = (((w * h * 101) / 100) + 3) * 4;
+      ret = LZ4_compressBound((w * h * 4));
+      if ((ret > 0) && ((uLongf)ret > buflen)) buflen = ret;
+      
       comp = malloc(buflen);
-      if (!comp)
+      if (!comp) return NULL;
+
+      switch (compression)
+        {
+         case EET_COMPRESSION_VERYFAST:
+           ret = LZ4_compressHC((const char *)data, (char *)comp,
+                                (w * h * 4));
+           if (ret <= 0) ok = 0;
+           buflen = ret;
+           break;
+         case EET_COMPRESSION_SUPERFAST:
+           ret = LZ4_compress((const char *)data, (char *)comp,
+                              (w * h * 4));
+           if (ret <= 0) ok = 0;
+           buflen = ret;
+           break;
+         default: /* zlib etc. */
+           ret = compress2((Bytef *)comp, &buflen, (Bytef *)(data),
+                           (uLong)(w * h * 4), compression);
+           if (ret != Z_OK) ok = 0;
+           break;
+        }
+      if ((!ok) || (buflen > (w * h * 4)))
         {
-           free(d);
+           free(comp);
+           *size = -1;
            return NULL;
         }
 
-      header = (int *)d;
-      memset(d, 0, 32);
+      d = malloc((8 * sizeof(int)) + buflen);
+      if (!d)
+        {
+           free(comp);
+           return NULL;
+        }
 
+      header = (int *)d;
+      memset(d, 0, 8 * sizeof(int));
       header[0] = 0xac1dfeed;
       header[1] = w;
       header[2] = h;
       header[3] = alpha;
       header[4] = compression;
-      memcpy(d + 32, data, w * h * 4);
 
       if (_eet_image_words_bigendian)
         {
            unsigned int i;
-
+           
            for (i = 0; i < ((w * h) + 8); i++) SWAP32(header[i]);
         }
 
-      ret = compress2((Bytef *)comp, &buflen,
-                      (Bytef *)(d + 32),
-                      (uLong)(w * h * 4),
-                      compression);
-      if (ret != Z_OK || buflen > (w * h * 4))
-        {
-           free(comp);
-           free(d);
-           *size = -1;
-           return NULL;
-        }
-
-      memcpy(d + 32, comp, buflen);
-      *size = (8 * 4) + buflen;
+      memcpy(d + (8 * sizeof(int)), comp, buflen);
+      *size = (8 * sizeof(int)) + buflen;
       free(comp);
       return d;
    }
@@ -1577,35 +1593,75 @@ _eet_data_image_decode_inside(const void   *data,
                                       w, h, row_stride);
         else
           {
-             if (src_h == h && src_w == w && row_stride == src_w * 4)
+             if ((src_h == h) && (src_w == w) && (row_stride == src_w * 4))
                {
-                  uLongf dlen;
-
-                  dlen = w * h * 4;
-                  uncompress((Bytef *)d, &dlen, (Bytef *)body,
-                             (uLongf)(size - 32));
+                  switch (comp)
+                    {
+                     case EET_COMPRESSION_VERYFAST:
+                     case EET_COMPRESSION_SUPERFAST:
+                       if (LZ4_uncompress((const char *)body,
+                                          (char *)d, w * h * 4)
+                           != (size - 32)) return 0;
+                       break;
+                     default:
+                         {
+                            uLongf dlen = w * h * 4;
+                            
+                            if (uncompress((Bytef *)d, &dlen, (Bytef *)body,
+                                           (uLongf)(size - 32)) != Z_OK)
+                              return 0;
+                         }
+                       break;
+                    }
                }
              else
                {
-                  Bytef *dtmp;
-                  uLongf dlen = src_w * src_h * 4;
-
-     /* FIXME: This could create a huge alloc. So compressed
-        data and tile could not always work. */
-                  dtmp = malloc(dlen);
-                  if (!dtmp)
-                    return 0;
-
-                  uncompress(dtmp, &dlen, (Bytef *)body, (uLongf)(size - 32));
-
-                  _eet_data_image_copy_buffer((unsigned int *)dtmp,
-                                              src_x, src_y, src_w, d,
-                                              w, h, row_stride);
-
-                  free(dtmp);
+                  switch (comp)
+                    {
+                     case EET_COMPRESSION_VERYFAST:
+                     case EET_COMPRESSION_SUPERFAST:
+                         {
+                            char *dtmp;
+                            
+                            dtmp = malloc(src_w * src_h * 4);
+                            if (!dtmp) return 0;
+                            if (LZ4_uncompress((const char *)body,
+                                               dtmp, w * h * 4)
+                                != (size - 32))
+                              {
+                                 free(dtmp);
+                                 return 0;
+                              }
+                            _eet_data_image_copy_buffer((unsigned int *)dtmp,
+                                                        src_x, src_y, src_w, d,
+                                                        w, h, row_stride);
+                            free(dtmp);
+                         }
+                       break;
+                     default:
+                         {
+                            Bytef *dtmp;
+                            uLongf dlen = src_w * src_h * 4;
+                  
+                            /* FIXME: This could create a huge alloc. So
+                             compressed data and tile could not always work.*/
+                            dtmp = malloc(dlen);
+                            if (!dtmp) return 0;
+                  
+                            if (uncompress(dtmp, &dlen, (Bytef *)body,
+                                           (uLongf)(size - 32)) != Z_OK)
+                              {
+                                 free(dtmp);
+                                 return 0;
+                              }
+                            _eet_data_image_copy_buffer((unsigned int *)dtmp,
+                                                        src_x, src_y, src_w, d,
+                                                        w, h, row_stride);
+                            free(dtmp);
+                         }
+                    }
                }
           }
-
         /* Fix swapiness. */
         if (_eet_image_words_bigendian)
           {
index a3295f4..a350d11 100644 (file)
@@ -66,6 +66,9 @@ GCRY_THREAD_OPTION_PTHREAD_IMPL;
 #include "Eet.h"
 #include "Eet_private.h"
 
+#include "lz4.h"
+#include "lz4hc.h"
+
 #ifndef O_BINARY
 # define O_BINARY 0
 #endif
@@ -442,6 +445,7 @@ eet_flush2(Eet_File *ef)
              int ibuf[EET_FILE2_DIRECTORY_ENTRY_COUNT];
 
              flag = (efn->alias << 2) | (efn->ciphered << 1) | efn->compression;
+             flag |= efn->compression_type << 3;
 
              ibuf[0] = (int)htonl((unsigned int)efn->offset);
              ibuf[1] = (int)htonl((unsigned int)efn->size);
@@ -864,6 +868,7 @@ eet_internal_read2(Eet_File *ef)
         efn->compression = flag & 0x1 ? 1 : 0;
         efn->ciphered = flag & 0x2 ? 1 : 0;
         efn->alias = flag & 0x4 ? 1 : 0;
+        efn->compression_type = (flag >> 3) & 0xff;
 
 #define EFN_TEST(Test, Ef, Efn) \
   if (eet_test_close(Test, Ef)) \
@@ -1719,7 +1724,7 @@ eet_read_cipher(Eet_File   *ef,
         void *tmp_data = NULL;
         void *data_deciphered = NULL;
         unsigned int data_deciphered_sz = 0;
-        int free_tmp = 0;
+        int free_tmp = 0, ret;
         int compr_size = efn->size;
         uLongf dlen;
 
@@ -1765,12 +1770,27 @@ eet_read_cipher(Eet_File   *ef,
 
         /* decompress it */
         dlen = size;
-        if (uncompress((Bytef *)data, &dlen,
-                       tmp_data, (uLongf)compr_size))
+        switch (efn->compression_type)
           {
-             if (free_tmp)
-               free(tmp_data);
-             goto on_error;
+           case EET_COMPRESSION_VERYFAST:
+           case EET_COMPRESSION_SUPERFAST:
+             ret = LZ4_uncompress(tmp_data, data, dlen);
+             if (ret != compr_size)
+               {
+                  if (free_tmp)
+                    free(tmp_data);
+                  goto on_error;
+               }
+             break;
+           default:
+             if (uncompress((Bytef *)data, &dlen,
+                            tmp_data, (uLongf)compr_size) != Z_OK)
+               {
+                  if (free_tmp)
+                    free(tmp_data);
+                  goto on_error;
+               }
+             break;
           }
 
         if (free_tmp)
@@ -1821,7 +1841,7 @@ eet_read_direct(Eet_File   *ef,
 {
    Eet_File_Node *efn;
    const char *data = NULL;
-   int size = 0;
+   int size = 0, ret;
 
    if (size_ret)
      *size_ret = 0;
@@ -1862,23 +1882,46 @@ eet_read_direct(Eet_File   *ef,
         /* handle alias case */
         if (efn->compression)
           {
+             const void *retptr;
              char *tmp;
              int compr_size = efn->size;
              uLongf dlen;
-
-             tmp = alloca(sizeof (compr_size));
-             dlen = size;
-
-             if (uncompress((Bytef *)tmp, &dlen, (Bytef *)data,
-                            (uLongf)compr_size))
-               goto on_error;
-
+             
+             tmp = malloc(compr_size);
+             if (!tmp) goto on_error;
+             switch (efn->compression_type)
+               {
+                case EET_COMPRESSION_VERYFAST:
+                case EET_COMPRESSION_SUPERFAST:
+                  ret = LZ4_uncompress(data, tmp, size);
+                  if (ret != compr_size)
+                    {
+                       free(tmp);
+                       goto on_error;
+                    }
+                  break;
+                default:
+                  dlen = size;
+                  
+                  if (uncompress((Bytef *)tmp, &dlen, (Bytef *)data,
+                                 (uLongf)compr_size))
+                    {
+                       free(tmp);
+                       goto on_error;
+                    }
+               }
+             
              if (tmp[compr_size - 1] != '\0')
-               goto on_error;
-
+               {
+                  free(tmp);
+                  goto on_error;
+               }
+             
              UNLOCK_FILE(ef);
-
-             return eet_read_direct(ef, tmp, size_ret);
+             
+             retptr = eet_read_direct(ef, tmp, size_ret);
+             free(tmp);
+             return retptr;
           }
 
         if (!data)
@@ -1893,8 +1936,7 @@ eet_read_direct(Eet_File   *ef,
      }
    else
    /* uncompressed data */
-   if (efn->compression == 0
-       && efn->ciphered == 0)
+   if ((efn->compression == 0) && (efn->ciphered == 0))
      data = efn->data ? efn->data : ef->data + efn->offset;  /* compressed data */
    else
      data = NULL;
@@ -1918,7 +1960,7 @@ eet_alias_get(Eet_File   *ef,
 {
    Eet_File_Node *efn;
    const char *data = NULL;
-   int size = 0;
+   int size = 0, ret;
 
    /* check to see its' an eet file pointer */
    if (eet_check_pointer(ef))
@@ -1955,23 +1997,43 @@ eet_alias_get(Eet_File   *ef,
    /* handle alias case */
    if (efn->compression)
      {
+        const char *retptr;
         char *tmp;
         int compr_size = efn->size;
         uLongf dlen;
-
-        tmp = alloca(sizeof (compr_size));
-        dlen = size;
-
-        if (uncompress((Bytef *)tmp, &dlen, (Bytef *)data,
-                       (uLongf)compr_size))
-          goto on_error;
-
+                  
+        tmp = malloc(compr_size);
+        if (!tmp) goto on_error;
+        switch (efn->compression_type)
+          {
+           case EET_COMPRESSION_VERYFAST:
+           case EET_COMPRESSION_SUPERFAST:
+             ret = LZ4_uncompress(data, tmp, size);
+             if (ret != compr_size)
+               {
+                  free(tmp);
+                  goto on_error;
+               }
+             break;
+           default:
+             dlen = size;
+             
+             if (uncompress((Bytef *)tmp, &dlen, (Bytef *)data,
+                            (uLongf)compr_size))
+               {
+                  free(tmp);
+                  goto on_error;
+               }
+          }
+        
         if (tmp[compr_size - 1] != '\0')
           goto on_error;
 
         UNLOCK_FILE(ef);
 
-        return eina_stringshare_add(tmp);
+        retptr = eina_stringshare_add(tmp);
+        free(tmp);
+        return retptr;
      }
 
    if (!data)
@@ -1998,8 +2060,7 @@ eet_alias(Eet_File   *ef,
    Eet_File_Node *efn;
    void *data2;
    Eina_Bool exists_already = EINA_FALSE;
-   int data_size;
-   int hash;
+   int data_size, ret, hash, slen;
 
    /* check to see its' an eet file pointer */
    if (eet_check_pointer(ef))
@@ -2048,32 +2109,64 @@ eet_alias(Eet_File   *ef,
    /* figure hash bucket */
    hash = _eet_hash_gen(name, ef->header->directory->size);
 
+   slen = strlen(destination) + 1;
    data_size = comp ?
-     12 + (((strlen(destination) + 1) * 101) / 100)
-     : strlen(destination) + 1;
-
+     12 + ((slen * 101) / 100)
+     : slen;
+   if (comp)
+     {
+        ret = LZ4_compressBound(slen);
+        if ((ret > 0) && (ret > data_size)) data_size = ret;
+     }
+   
    data2 = malloc(data_size);
-   if (!data2)
-     goto on_error;
+   if (!data2) goto on_error;
 
    /* if we want to compress */
    if (comp)
      {
-        uLongf buflen;
-
-        /* compress the data with max compression */
-        buflen = (uLongf)data_size;
-        if (compress2((Bytef *)data2, &buflen, (Bytef *)destination,
-                      (uLong)strlen(destination) + 1,
-                      Z_BEST_COMPRESSION) != Z_OK)
+        switch (comp)
           {
-             free(data2);
-             goto on_error;
+           case EET_COMPRESSION_VERYFAST:
+             ret = LZ4_compressHC((const char *)destination, (char *)data2,
+                                  slen);
+             if (ret <= 0)
+               {
+                  free(data2);
+                  goto on_error;
+               }
+             data_size = ret;
+             break;
+           case EET_COMPRESSION_SUPERFAST:
+             ret = LZ4_compress((const char *)destination, (char *)data2,
+                                slen);
+             if (ret <= 0)
+               {
+                  free(data2);
+                  goto on_error;
+               }
+             data_size = ret;
+             break;
+           default:
+               {
+                  uLongf buflen;
+                  
+                  /* compress the data with max compression */
+                  buflen = (uLongf)data_size;
+                  if (compress2((Bytef *)data2, &buflen, 
+                                (const Bytef *)destination,
+                                (uLong)slen, Z_BEST_COMPRESSION) != Z_OK)
+                    {
+                       free(data2);
+                       goto on_error;
+                    }
+                  /* record compressed chunk size */
+                  data_size = (int)buflen;
+               }
+             break;
           }
-
-        /* record compressed chunk size */
-        data_size = (int)buflen;
-        if (data_size < 0 || data_size >= (int)(strlen(destination) + 1))
+        if ((data_size < 0) || 
+            (data_size >= (int)(strlen(destination) + 1)))
           {
              comp = 0;
              data_size = strlen(destination) + 1;
@@ -2083,13 +2176,11 @@ eet_alias(Eet_File   *ef,
              void *data3;
 
              data3 = realloc(data2, data_size);
-             if (data3)
-               data2 = data3;
+             if (data3) data2 = data3;
           }
      }
-
-   if (!comp)
-     memcpy(data2, destination, data_size);
+   
+   if (!comp) memcpy(data2, destination, data_size);
 
    /* Does this node already exist? */
    for (efn = ef->header->directory->nodes[hash]; efn; efn = efn->next)
@@ -2101,13 +2192,13 @@ eet_alias(Eet_File   *ef,
               efn->alias = 1;
               efn->ciphered = 0;
               efn->compression = !!comp;
+              efn->compression_type = comp;
               efn->size = data_size;
               efn->data_size = strlen(destination) + 1;
               efn->data = data2;
-     /* Put the offset above the limit to avoid direct access */
+              /* Put the offset above the limit to avoid direct access */
               efn->offset = ef->data_size + 1;
               exists_already = EINA_TRUE;
-
               break;
            }
      }
@@ -2131,6 +2222,7 @@ eet_alias(Eet_File   *ef,
         efn->alias = 1;
         efn->ciphered = 0;
         efn->compression = !!comp;
+        efn->compression_type = comp;
         efn->size = data_size;
         efn->data_size = strlen(destination) + 1;
         efn->data = data2;
@@ -2157,9 +2249,7 @@ eet_write_cipher(Eet_File   *ef,
 {
    Eet_File_Node *efn;
    void *data2 = NULL;
-   int exists_already = 0;
-   int data_size;
-   int hash;
+   int exists_already = 0, data_size, hash, ret;
 
    /* check to see its' an eet file pointer */
    if (eet_check_pointer(ef))
@@ -2208,8 +2298,15 @@ eet_write_cipher(Eet_File   *ef,
    /* figure hash bucket */
    hash = _eet_hash_gen(name, ef->header->directory->size);
 
+   UNLOCK_FILE(ef);
+   
    data_size = comp ? 12 + ((size * 101) / 100) : size;
-
+   if (comp)
+     {
+        ret = LZ4_compressBound(size);
+        if ((ret > 0) && (ret > data_size)) data_size = ret;
+     }
+   
    if (comp || !cipher_key)
      {
         data2 = malloc(data_size);
@@ -2220,20 +2317,46 @@ eet_write_cipher(Eet_File   *ef,
    /* if we want to compress */
    if (comp)
      {
-        uLongf buflen;
-
-        /* compress the data with max compression */
-        buflen = (uLongf)data_size;
-        if (compress2((Bytef *)data2, &buflen, (Bytef *)data,
-                      (uLong)size, Z_BEST_COMPRESSION) != Z_OK)
+        switch (comp)
           {
-             free(data2);
-             goto on_error;
-          }
+           case EET_COMPRESSION_VERYFAST:
+             ret = LZ4_compressHC((const char *)data, (char *)data2, size);
+             if (ret <= 0)
+               {
+                  free(data2);
+                  LOCK_FILE(ef);
+                  goto on_error;
+               }
+             data_size = ret;
+             break;
+           case EET_COMPRESSION_SUPERFAST:
+             ret = LZ4_compress((const char *)data, (char *)data2, size);
+             if (ret <= 0)
+               {
+                  free(data2);
+                  LOCK_FILE(ef);
+                  goto on_error;
+               }
+             data_size = ret;
+             break;
+           default:
+               {
+                  uLongf buflen;
 
-        /* record compressed chunk size */
-        data_size = (int)buflen;
-        if (data_size < 0 || data_size >= size)
+                  /* compress the data with max compression */
+                  buflen = (uLongf)data_size;
+                  if (compress2((Bytef *)data2, &buflen, (Bytef *)data,
+                                (uLong)size, Z_BEST_COMPRESSION) != Z_OK)
+                    {
+                       free(data2);
+                       LOCK_FILE(ef);
+                       goto on_error;
+                    }
+                  /* record compressed chunk size */
+                  data_size = (int)buflen;
+               }
+          }
+        if ((data_size < 0) || (data_size >= size))
           {
              comp = 0;
              data_size = size;
@@ -2276,6 +2399,7 @@ eet_write_cipher(Eet_File   *ef,
    if (!comp)
      memcpy(data2, data, size);
 
+   LOCK_FILE(ef);
    /* Does this node already exist? */
    for (efn = ef->header->directory->nodes[hash]; efn; efn = efn->next)
      {
@@ -2286,10 +2410,11 @@ eet_write_cipher(Eet_File   *ef,
               efn->alias = 0;
               efn->ciphered = cipher_key ? 1 : 0;
               efn->compression = !!comp;
+              efn->compression_type = comp;
               efn->size = data_size;
               efn->data_size = size;
               efn->data = data2;
-     /* Put the offset above the limit to avoid direct access */
+              /* Put the offset above the limit to avoid direct access */
               efn->offset = ef->data_size + 1;
               exists_already = 1;
               break;
@@ -2315,6 +2440,7 @@ eet_write_cipher(Eet_File   *ef,
         efn->alias = 0;
         efn->ciphered = cipher_key ? 1 : 0;
         efn->compression = !!comp;
+        efn->compression_type = comp;
         efn->size = data_size;
         efn->data_size = size;
         efn->data = data2;
diff --git a/src/lib/lz4/lz4.c b/src/lib/lz4/lz4.c
new file mode 100644 (file)
index 0000000..06e2829
--- /dev/null
@@ -0,0 +1,819 @@
+/*\r
+   LZ4 - Fast LZ compression algorithm\r
+   Copyright (C) 2011-2012, Yann Collet.\r
+   BSD 2-Clause License (http://www.opensource.org/licenses/bsd-license.php)\r
+\r
+   Redistribution and use in source and binary forms, with or without\r
+   modification, are permitted provided that the following conditions are\r
+   met:\r
+\r
+       * Redistributions of source code must retain the above copyright\r
+   notice, this list of conditions and the following disclaimer.\r
+       * Redistributions in binary form must reproduce the above\r
+   copyright notice, this list of conditions and the following disclaimer\r
+   in the documentation and/or other materials provided with the\r
+   distribution.\r
+\r
+   THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\r
+   "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\r
+   LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\r
+   A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\r
+   OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\r
+   SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\r
+   LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\r
+   DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\r
+   THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\r
+   (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\r
+   OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\r
+\r
+   You can contact the author at :\r
+   - LZ4 homepage : http://fastcompression.blogspot.com/p/lz4.html\r
+   - LZ4 source repository : http://code.google.com/p/lz4/\r
+*/\r
+\r
+//**************************************\r
+// Tuning parameters\r
+//**************************************\r
+// COMPRESSIONLEVEL :\r
+// Increasing this value improves compression ratio\r
+// Lowering this value reduces memory usage\r
+// Reduced memory usage typically improves speed, due to cache effect (ex : L1 32KB for Intel, L1 64KB for AMD)\r
+// Memory usage formula : N->2^(N+2) Bytes (examples : 12 -> 16KB ; 17 -> 512KB)\r
+#define COMPRESSIONLEVEL 12\r
+\r
+// NOTCOMPRESSIBLE_CONFIRMATION :\r
+// Decreasing this value will make the algorithm skip faster data segments considered "incompressible"\r
+// This may decrease compression ratio dramatically, but will be faster on incompressible data\r
+// Increasing this value will make the algorithm search more before declaring a segment "incompressible"\r
+// This could improve compression a bit, but will be slower on incompressible data\r
+// The default value (6) is recommended\r
+#define NOTCOMPRESSIBLE_CONFIRMATION 6\r
+\r
+// LZ4_COMPRESSMIN :\r
+// Compression function will *fail* if it is not successful at compressing input by at least LZ4_COMPRESSMIN bytes\r
+// Since the compression function stops working prematurely, it results in a speed gain\r
+// The output however is unusable. Compression function result will be zero.\r
+// Default : 0 = disabled\r
+#define LZ4_COMPRESSMIN 0\r
+\r
+// BIG_ENDIAN_NATIVE_BUT_INCOMPATIBLE :\r
+// This will provide a boost to performance for big endian cpu, but the resulting compressed stream will be incompatible with little-endian CPU.\r
+// You can set this option to 1 in situations where data will stay within closed environment\r
+// This option is useless on Little_Endian CPU (such as x86)\r
+//#define BIG_ENDIAN_NATIVE_BUT_INCOMPATIBLE 1\r
+\r
+\r
+\r
+//**************************************\r
+// CPU Feature Detection\r
+//**************************************\r
+// 32 or 64 bits ?\r
+#if (defined(__x86_64__) || defined(__x86_64) || defined(__amd64__) || defined(__amd64) || defined(__ppc64__) || defined(_WIN64) || defined(__LP64__) || defined(_LP64) )   // Detects 64 bits mode\r
+#  define LZ4_ARCH64 1\r
+#else\r
+#  define LZ4_ARCH64 0\r
+#endif\r
+\r
+// Little Endian or Big Endian ?\r
+// Note : overwrite the below #define if you know your architecture endianess\r
+#if (defined(__BIG_ENDIAN__) || defined(__BIG_ENDIAN) || defined(_BIG_ENDIAN) || defined(_ARCH_PPC) || defined(__PPC__) || defined(__PPC) || defined(PPC) || defined(__powerpc__) || defined(__powerpc) || defined(powerpc) || ((defined(__BYTE_ORDER__)&&(__BYTE_ORDER__ == __ORDER_BIG_ENDIAN__))) )\r
+#  define LZ4_BIG_ENDIAN 1\r
+#else\r
+// Little Endian assumed. PDP Endian and other very rare endian format are unsupported.\r
+#endif\r
+\r
+// Unaligned memory access is automatically enabled for "common" CPU, such as x86.\r
+// For others CPU, the compiler will be more cautious, and insert extra code to ensure aligned access is respected\r
+// If you know your target CPU supports unaligned memory access, you may want to force this option manually to improve performance\r
+#if defined(__ARM_FEATURE_UNALIGNED)\r
+#  define LZ4_FORCE_UNALIGNED_ACCESS 1\r
+#endif\r
+\r
+// Define this parameter if your target system or compiler does not support hardware bit count\r
+#if defined(_MSC_VER) && defined(_WIN32_WCE)            // Visual Studio for Windows CE does not support Hardware bit count\r
+#  define LZ4_FORCE_SW_BITCOUNT\r
+#endif\r
+\r
+\r
+//**************************************\r
+// Compiler Options\r
+//**************************************\r
+#if __STDC_VERSION__ >= 199901L // C99\r
+/* "restrict" is a known keyword */\r
+#else\r
+#  define restrict // Disable restrict\r
+#endif\r
+\r
+#define GCC_VERSION (__GNUC__ * 100 + __GNUC_MINOR__)\r
+\r
+#ifdef _MSC_VER  // Visual Studio\r
+#  define inline __forceinline           // Visual is not C99, but supports some kind of inline\r
+#  if LZ4_ARCH64       // 64-bit\r
+#    pragma intrinsic(_BitScanForward64) // For Visual 2005\r
+#    pragma intrinsic(_BitScanReverse64) // For Visual 2005\r
+#  else\r
+#    pragma intrinsic(_BitScanForward)   // For Visual 2005\r
+#    pragma intrinsic(_BitScanReverse)   // For Visual 2005\r
+#  endif\r
+#endif\r
+\r
+#ifdef _MSC_VER\r
+#  define lz4_bswap16(x) _byteswap_ushort(x)\r
+#else\r
+#  define lz4_bswap16(x) ((unsigned short int) ((((x) >> 8) & 0xffu) | (((x) & 0xffu) << 8)))\r
+#endif\r
+\r
+#if (GCC_VERSION >= 302) || (__INTEL_COMPILER >= 800) || defined(__clang__)\r
+#  define expect(expr,value)    (__builtin_expect ((expr),(value)) )\r
+#else\r
+#  define expect(expr,value)    (expr)\r
+#endif\r
+\r
+#define likely(expr)     expect((expr) != 0, 1)\r
+#define unlikely(expr)   expect((expr) != 0, 0)\r
+\r
+\r
+//**************************************\r
+// Includes\r
+//**************************************\r
+#include <stdlib.h>   // for malloc\r
+#include <string.h>   // for memset\r
+#include "lz4.h"\r
+\r
+\r
+//**************************************\r
+// Basic Types\r
+//**************************************\r
+#if defined(_MSC_VER)    // Visual Studio does not support 'stdint' natively\r
+#  define BYTE unsigned __int8\r
+#  define U16          unsigned __int16\r
+#  define U32          unsigned __int32\r
+#  define S32          __int32\r
+#  define U64          unsigned __int64\r
+#else\r
+#  include <stdint.h>\r
+#  define BYTE uint8_t\r
+#  define U16          uint16_t\r
+#  define U32          uint32_t\r
+#  define S32          int32_t\r
+#  define U64          uint64_t\r
+#endif\r
+\r
+#ifndef LZ4_FORCE_UNALIGNED_ACCESS\r
+#  pragma pack(push, 1)\r
+#endif\r
+\r
+typedef struct _U16_S { U16 v; } U16_S;\r
+typedef struct _U32_S { U32 v; } U32_S;\r
+typedef struct _U64_S { U64 v; } U64_S;\r
+\r
+#ifndef LZ4_FORCE_UNALIGNED_ACCESS\r
+#  pragma pack(pop)\r
+#endif\r
+\r
+#define A64(x) (((U64_S *)(x))->v)\r
+#define A32(x) (((U32_S *)(x))->v)\r
+#define A16(x) (((U16_S *)(x))->v)\r
+\r
+\r
+//**************************************\r
+// Constants\r
+//**************************************\r
+#define MINMATCH 4\r
+\r
+#define HASH_LOG COMPRESSIONLEVEL\r
+#define HASHTABLESIZE (1 << HASH_LOG)\r
+#define HASH_MASK (HASHTABLESIZE - 1)\r
+\r
+#define SKIPSTRENGTH (NOTCOMPRESSIBLE_CONFIRMATION>2?NOTCOMPRESSIBLE_CONFIRMATION:2)\r
+#define STACKLIMIT 13\r
+#define HEAPMODE (HASH_LOG>STACKLIMIT)  // Defines if memory is allocated into the stack (local variable), or into the heap (malloc()).\r
+#define COPYLENGTH 8\r
+#define LASTLITERALS 5\r
+#define MFLIMIT (COPYLENGTH+MINMATCH)\r
+#define MINLENGTH (MFLIMIT+1)\r
+\r
+#define MAXD_LOG 16\r
+#define MAX_DISTANCE ((1 << MAXD_LOG) - 1)\r
+\r
+#define ML_BITS 4\r
+#define ML_MASK ((1U<<ML_BITS)-1)\r
+#define RUN_BITS (8-ML_BITS)\r
+#define RUN_MASK ((1U<<RUN_BITS)-1)\r
+\r
+\r
+//**************************************\r
+// Architecture-specific macros\r
+//**************************************\r
+#if LZ4_ARCH64 // 64-bit\r
+#  define STEPSIZE 8\r
+#  define UARCH U64\r
+#  define AARCH A64\r
+#  define LZ4_COPYSTEP(s,d)            A64(d) = A64(s); d+=8; s+=8;\r
+#  define LZ4_COPYPACKET(s,d)          LZ4_COPYSTEP(s,d)\r
+#  define LZ4_SECURECOPY(s,d,e)        if (d<e) LZ4_WILDCOPY(s,d,e)\r
+#  define HTYPE U32\r
+#  define INITBASE(base)                       const BYTE* const base = ip\r
+#else          // 32-bit\r
+#  define STEPSIZE 4\r
+#  define UARCH U32\r
+#  define AARCH A32\r
+#  define LZ4_COPYSTEP(s,d)            A32(d) = A32(s); d+=4; s+=4;\r
+#  define LZ4_COPYPACKET(s,d)          LZ4_COPYSTEP(s,d); LZ4_COPYSTEP(s,d);\r
+#  define LZ4_SECURECOPY                       LZ4_WILDCOPY\r
+#  define HTYPE const BYTE*\r
+#  define INITBASE(base)                       const int base = 0\r
+#endif\r
+\r
+#if (defined(LZ4_BIG_ENDIAN) && !defined(BIG_ENDIAN_NATIVE_BUT_INCOMPATIBLE))\r
+#  define LZ4_READ_LITTLEENDIAN_16(d,s,p) { U16 v = A16(p); v = lz4_bswap16(v); d = (s) - v; }\r
+#  define LZ4_WRITE_LITTLEENDIAN_16(p,i)  { U16 v = (U16)(i); v = lz4_bswap16(v); A16(p) = v; p+=2; }\r
+#else          // Little Endian\r
+#  define LZ4_READ_LITTLEENDIAN_16(d,s,p) { d = (s) - A16(p); }\r
+#  define LZ4_WRITE_LITTLEENDIAN_16(p,v)  { A16(p) = v; p+=2; }\r
+#endif\r
+\r
+\r
+//**************************************\r
+// Local structures\r
+//**************************************\r
+struct refTables\r
+{\r
+       HTYPE hashTable[HASHTABLESIZE];\r
+};\r
+\r
+\r
+//**************************************\r
+// Macros\r
+//**************************************\r
+#define LZ4_HASH_FUNCTION(i)   (((i) * 2654435761U) >> ((MINMATCH*8)-HASH_LOG))\r
+#define LZ4_HASH_VALUE(p)              LZ4_HASH_FUNCTION(A32(p))\r
+#define LZ4_WILDCOPY(s,d,e)            do { LZ4_COPYPACKET(s,d) } while (d<e);\r
+#define LZ4_BLINDCOPY(s,d,l)   { BYTE* e=(d)+l; LZ4_WILDCOPY(s,d,e); d=e; }\r
+\r
+\r
+//****************************\r
+// Private functions\r
+//****************************\r
+#if LZ4_ARCH64\r
+\r
+inline static int LZ4_NbCommonBytes (register U64 val)\r
+{\r
+#if defined(LZ4_BIG_ENDIAN)\r
+    #if defined(_MSC_VER) && !defined(LZ4_FORCE_SW_BITCOUNT)\r
+    unsigned long r = 0;\r
+    _BitScanReverse64( &r, val );\r
+    return (int)(r>>3);\r
+    #elif defined(__GNUC__) && (GCC_VERSION >= 304) && !defined(LZ4_FORCE_SW_BITCOUNT)\r
+    return (__builtin_clzll(val) >> 3);\r
+    #else\r
+       int r;\r
+       if (!(val>>32)) { r=4; } else { r=0; val>>=32; }\r
+       if (!(val>>16)) { r+=2; val>>=8; } else { val>>=24; }\r
+       r += (!val);\r
+       return r;\r
+    #endif\r
+#else\r
+    #if defined(_MSC_VER) && !defined(LZ4_FORCE_SW_BITCOUNT)\r
+    unsigned long r = 0;\r
+    _BitScanForward64( &r, val );\r
+    return (int)(r>>3);\r
+    #elif defined(__GNUC__) && (GCC_VERSION >= 304) && !defined(LZ4_FORCE_SW_BITCOUNT)\r
+    return (__builtin_ctzll(val) >> 3);\r
+    #else\r
+       static const int DeBruijnBytePos[64] = { 0, 0, 0, 0, 0, 1, 1, 2, 0, 3, 1, 3, 1, 4, 2, 7, 0, 2, 3, 6, 1, 5, 3, 5, 1, 3, 4, 4, 2, 5, 6, 7, 7, 0, 1, 2, 3, 3, 4, 6, 2, 6, 5, 5, 3, 4, 5, 6, 7, 1, 2, 4, 6, 4, 4, 5, 7, 2, 6, 5, 7, 6, 7, 7 };\r
+       return DeBruijnBytePos[((U64)((val & -val) * 0x0218A392CDABBD3F)) >> 58];\r
+    #endif\r
+#endif\r
+}\r
+\r
+#else\r
+\r
+inline static int LZ4_NbCommonBytes (register U32 val)\r
+{\r
+#if defined(LZ4_BIG_ENDIAN)\r
+    #if defined(_MSC_VER) && !defined(LZ4_FORCE_SW_BITCOUNT)\r
+    unsigned long r = 0;\r
+    _BitScanReverse( &r, val );\r
+    return (int)(r>>3);\r
+    #elif defined(__GNUC__) && (GCC_VERSION >= 304) && !defined(LZ4_FORCE_SW_BITCOUNT)\r
+    return (__builtin_clz(val) >> 3);\r
+    #else\r
+       int r;\r
+       if (!(val>>16)) { r=2; val>>=8; } else { r=0; val>>=24; }\r
+       r += (!val);\r
+       return r;\r
+    #endif\r
+#else\r
+    #if defined(_MSC_VER) && !defined(LZ4_FORCE_SW_BITCOUNT)\r
+    unsigned long r = 0;\r
+    _BitScanForward( &r, val );\r
+    return (int)(r>>3);\r
+    #elif defined(__GNUC__) && (GCC_VERSION >= 304) && !defined(LZ4_FORCE_SW_BITCOUNT)\r
+    return (__builtin_ctz(val) >> 3);\r
+    #else\r
+       static const int DeBruijnBytePos[32] = { 0, 0, 3, 0, 3, 1, 3, 0, 3, 2, 2, 1, 3, 2, 0, 1, 3, 3, 1, 2, 2, 2, 2, 0, 3, 1, 2, 0, 1, 0, 1, 1 };\r
+       return DeBruijnBytePos[((U32)((val & -(S32)val) * 0x077CB531U)) >> 27];\r
+    #endif\r
+#endif\r
+}\r
+\r
+#endif\r
+\r
+\r
+//****************************\r
+// Public functions\r
+//****************************\r
+\r
+int LZ4_compressBound(int isize)\r
+{\r
+       return (isize + (isize/255) + 16);\r
+}\r
+\r
+\r
+\r
+//******************************\r
+// Compression functions\r
+//******************************\r
+\r
+int LZ4_compressCtx(void** ctx,\r
+                                const char* source,\r
+                                char* dest,\r
+                                int isize)\r
+{\r
+#if HEAPMODE\r
+       struct refTables *srt = (struct refTables *) (*ctx);\r
+       HTYPE* HashTable;\r
+#else\r
+       HTYPE HashTable[HASHTABLESIZE] = {0};\r
+#endif\r
+\r
+       const BYTE* ip = (BYTE*) source;\r
+       INITBASE(base);\r
+       const BYTE* anchor = ip;\r
+       const BYTE* const iend = ip + isize;\r
+       const BYTE* const mflimit = iend - MFLIMIT;\r
+#define matchlimit (iend - LASTLITERALS)\r
+\r
+       BYTE* op = (BYTE*) dest;\r
+\r
+       int len, length;\r
+       const int skipStrength = SKIPSTRENGTH;\r
+       U32 forwardH;\r
+\r
+\r
+       // Init\r
+       if (isize<MINLENGTH) goto _last_literals;\r
+#if HEAPMODE\r
+       if (*ctx == NULL)\r
+       {\r
+               srt = (struct refTables *) malloc ( sizeof(struct refTables) );\r
+               *ctx = (void*) srt;\r
+       }\r
+       HashTable = (HTYPE*)(srt->hashTable);\r
+       memset((void*)HashTable, 0, sizeof(srt->hashTable));\r
+#else\r
+       (void) ctx;\r
+#endif\r
+\r
+\r
+       // First Byte\r
+       HashTable[LZ4_HASH_VALUE(ip)] = ip - base;\r
+       ip++; forwardH = LZ4_HASH_VALUE(ip);\r
+\r
+       // Main Loop\r
+    for ( ; ; )\r
+       {\r
+               int findMatchAttempts = (1U << skipStrength) + 3;\r
+               const BYTE* forwardIp = ip;\r
+               const BYTE* ref;\r
+               BYTE* token;\r
+\r
+               // Find a match\r
+               do {\r
+                       U32 h = forwardH;\r
+                       int step = findMatchAttempts++ >> skipStrength;\r
+                       ip = forwardIp;\r
+                       forwardIp = ip + step;\r
+\r
+                       if unlikely(forwardIp > mflimit) { goto _last_literals; }\r
+\r
+                       forwardH = LZ4_HASH_VALUE(forwardIp);\r
+                       ref = base + HashTable[h];\r
+                       HashTable[h] = ip - base;\r
+\r
+               } while ((ref < ip - MAX_DISTANCE) || (A32(ref) != A32(ip)));\r
+\r
+               // Catch up\r
+               while ((ip>anchor) && (ref>(BYTE*)source) && unlikely(ip[-1]==ref[-1])) { ip--; ref--; }\r
+\r
+               // Encode Literal length\r
+               length = ip - anchor;\r
+               token = op++;\r
+               if (length>=(int)RUN_MASK) { *token=(RUN_MASK<<ML_BITS); len = length-RUN_MASK; for(; len > 254 ; len-=255) *op++ = 255; *op++ = (BYTE)len; }\r
+               else *token = (length<<ML_BITS);\r
+\r
+               // Copy Literals\r
+               LZ4_BLINDCOPY(anchor, op, length);\r
+\r
+_next_match:\r
+               // Encode Offset\r
+               LZ4_WRITE_LITTLEENDIAN_16(op,ip-ref);\r
+\r
+               // Start Counting\r
+               ip+=MINMATCH; ref+=MINMATCH;   // MinMatch verified\r
+               anchor = ip;\r
+               while likely(ip<matchlimit-(STEPSIZE-1))\r
+               {\r
+                       UARCH diff = AARCH(ref) ^ AARCH(ip);\r
+                       if (!diff) { ip+=STEPSIZE; ref+=STEPSIZE; continue; }\r
+                       ip += LZ4_NbCommonBytes(diff);\r
+                       goto _endCount;\r
+               }\r
+               if (LZ4_ARCH64) if ((ip<(matchlimit-3)) && (A32(ref) == A32(ip))) { ip+=4; ref+=4; }\r
+               if ((ip<(matchlimit-1)) && (A16(ref) == A16(ip))) { ip+=2; ref+=2; }\r
+               if ((ip<matchlimit) && (*ref == *ip)) ip++;\r
+_endCount:\r
+\r
+               // Encode MatchLength\r
+               len = (ip - anchor);\r
+               if (len>=(int)ML_MASK) { *token+=ML_MASK; len-=ML_MASK; for(; len > 509 ; len-=510) { *op++ = 255; *op++ = 255; } if (len > 254) { len-=255; *op++ = 255; } *op++ = (BYTE)len; }\r
+               else *token += len;\r
+\r
+               // Test end of chunk\r
+               if (ip > mflimit) { anchor = ip;  break; }\r
+\r
+               // Fill table\r
+               HashTable[LZ4_HASH_VALUE(ip-2)] = ip - 2 - base;\r
+\r
+               // Test next position\r
+               ref = base + HashTable[LZ4_HASH_VALUE(ip)];\r
+               HashTable[LZ4_HASH_VALUE(ip)] = ip - base;\r
+               if ((ref > ip - (MAX_DISTANCE + 1)) && (A32(ref) == A32(ip))) { token = op++; *token=0; goto _next_match; }\r
+\r
+               // Prepare next loop\r
+               anchor = ip++;\r
+               forwardH = LZ4_HASH_VALUE(ip);\r
+       }\r
+\r
+_last_literals:\r
+       // Encode Last Literals\r
+       {\r
+               int lastRun = iend - anchor;\r
+               if ((LZ4_COMPRESSMIN>0) && (((op - (BYTE*)dest) + lastRun + 1 + ((lastRun-15)/255)) > isize - LZ4_COMPRESSMIN)) return 0;\r
+               if (lastRun>=(int)RUN_MASK) { *op++=(RUN_MASK<<ML_BITS); lastRun-=RUN_MASK; for(; lastRun > 254 ; lastRun-=255) *op++ = 255; *op++ = (BYTE) lastRun; }\r
+               else *op++ = (lastRun<<ML_BITS);\r
+               memcpy(op, anchor, iend - anchor);\r
+               op += iend-anchor;\r
+       }\r
+\r
+       // End\r
+       return (int) (((char*)op)-dest);\r
+}\r
+\r
+\r
+\r
+// Note : this function is valid only if isize < LZ4_64KLIMIT\r
+#define LZ4_64KLIMIT ((1<<16) + (MFLIMIT-1))\r
+#define HASHLOG64K (HASH_LOG+1)\r
+#define HASH64KTABLESIZE (1U<<HASHLOG64K)\r
+#define LZ4_HASH64K_FUNCTION(i)        (((i) * 2654435761U) >> ((MINMATCH*8)-HASHLOG64K))\r
+#define LZ4_HASH64K_VALUE(p)   LZ4_HASH64K_FUNCTION(A32(p))\r
+int LZ4_compress64kCtx(void** ctx,\r
+                                const char* source,\r
+                                char* dest,\r
+                                int isize)\r
+{\r
+#if HEAPMODE\r
+       struct refTables *srt = (struct refTables *) (*ctx);\r
+       U16* HashTable;\r
+#else\r
+       U16 HashTable[HASH64KTABLESIZE] = {0};\r
+#endif\r
+\r
+       const BYTE* ip = (BYTE*) source;\r
+       const BYTE* anchor = ip;\r
+       const BYTE* const base = ip;\r
+       const BYTE* const iend = ip + isize;\r
+       const BYTE* const mflimit = iend - MFLIMIT;\r
+#define matchlimit (iend - LASTLITERALS)\r
+\r
+       BYTE* op = (BYTE*) dest;\r
+\r
+       int len, length;\r
+       const int skipStrength = SKIPSTRENGTH;\r
+       U32 forwardH;\r
+\r
+\r
+       // Init\r
+       if (isize<MINLENGTH) goto _last_literals;\r
+#if HEAPMODE\r
+       if (*ctx == NULL)\r
+       {\r
+               srt = (struct refTables *) malloc ( sizeof(struct refTables) );\r
+               *ctx = (void*) srt;\r
+       }\r
+       HashTable = (U16*)(srt->hashTable);\r
+       memset((void*)HashTable, 0, sizeof(srt->hashTable));\r
+#else\r
+       (void) ctx;\r
+#endif\r
+\r
+\r
+       // First Byte\r
+       ip++; forwardH = LZ4_HASH64K_VALUE(ip);\r
+\r
+       // Main Loop\r
+    for ( ; ; )\r
+       {\r
+               int findMatchAttempts = (1U << skipStrength) + 3;\r
+               const BYTE* forwardIp = ip;\r
+               const BYTE* ref;\r
+               BYTE* token;\r
+\r
+               // Find a match\r
+               do {\r
+                       U32 h = forwardH;\r
+                       int step = findMatchAttempts++ >> skipStrength;\r
+                       ip = forwardIp;\r
+                       forwardIp = ip + step;\r
+\r
+                       if (forwardIp > mflimit) { goto _last_literals; }\r
+\r
+                       forwardH = LZ4_HASH64K_VALUE(forwardIp);\r
+                       ref = base + HashTable[h];\r
+                       HashTable[h] = ip - base;\r
+\r
+               } while (A32(ref) != A32(ip));\r
+\r
+               // Catch up\r
+               while ((ip>anchor) && (ref>(BYTE*)source) && (ip[-1]==ref[-1])) { ip--; ref--; }\r
+\r
+               // Encode Literal length\r
+               length = ip - anchor;\r
+               token = op++;\r
+               if (length>=(int)RUN_MASK) { *token=(RUN_MASK<<ML_BITS); len = length-RUN_MASK; for(; len > 254 ; len-=255) *op++ = 255; *op++ = (BYTE)len; }\r
+               else *token = (length<<ML_BITS);\r
+\r
+               // Copy Literals\r
+               LZ4_BLINDCOPY(anchor, op, length);\r
+\r
+_next_match:\r
+               // Encode Offset\r
+               LZ4_WRITE_LITTLEENDIAN_16(op,ip-ref);\r
+\r
+               // Start Counting\r
+               ip+=MINMATCH; ref+=MINMATCH;   // MinMatch verified\r
+               anchor = ip;\r
+               while (ip<matchlimit-(STEPSIZE-1))\r
+               {\r
+                       UARCH diff = AARCH(ref) ^ AARCH(ip);\r
+                       if (!diff) { ip+=STEPSIZE; ref+=STEPSIZE; continue; }\r
+                       ip += LZ4_NbCommonBytes(diff);\r
+                       goto _endCount;\r
+               }\r
+               if (LZ4_ARCH64) if ((ip<(matchlimit-3)) && (A32(ref) == A32(ip))) { ip+=4; ref+=4; }\r
+               if ((ip<(matchlimit-1)) && (A16(ref) == A16(ip))) { ip+=2; ref+=2; }\r
+               if ((ip<matchlimit) && (*ref == *ip)) ip++;\r
+_endCount:\r
+\r
+               // Encode MatchLength\r
+               len = (ip - anchor);\r
+               if (len>=(int)ML_MASK) { *token+=ML_MASK; len-=ML_MASK; for(; len > 509 ; len-=510) { *op++ = 255; *op++ = 255; } if (len > 254) { len-=255; *op++ = 255; } *op++ = (BYTE)len; }\r
+               else *token += len;\r
+\r
+               // Test end of chunk\r
+               if (ip > mflimit) { anchor = ip;  break; }\r
+\r
+               // Fill table\r
+               HashTable[LZ4_HASH64K_VALUE(ip-2)] = ip - 2 - base;\r
+\r
+               // Test next position\r
+               ref = base + HashTable[LZ4_HASH64K_VALUE(ip)];\r
+               HashTable[LZ4_HASH64K_VALUE(ip)] = ip - base;\r
+               if (A32(ref) == A32(ip)) { token = op++; *token=0; goto _next_match; }\r
+\r
+               // Prepare next loop\r
+               anchor = ip++;\r
+               forwardH = LZ4_HASH64K_VALUE(ip);\r
+       }\r
+\r
+_last_literals:\r
+       // Encode Last Literals\r
+       {\r
+               int lastRun = iend - anchor;\r
+               if ((LZ4_COMPRESSMIN>0) && (((op - (BYTE*)dest) + lastRun + 1 + ((lastRun-15)/255)) > isize - LZ4_COMPRESSMIN)) return 0;\r
+               if (lastRun>=(int)RUN_MASK) { *op++=(RUN_MASK<<ML_BITS); lastRun-=RUN_MASK; for(; lastRun > 254 ; lastRun-=255) *op++ = 255; *op++ = (BYTE) lastRun; }\r
+               else *op++ = (lastRun<<ML_BITS);\r
+               memcpy(op, anchor, iend - anchor);\r
+               op += iend-anchor;\r
+       }\r
+\r
+       // End\r
+       return (int) (((char*)op)-dest);\r
+}\r
+\r
+\r
+\r
+int LZ4_compress(const char* source,\r
+                                char* dest,\r
+                                int isize)\r
+{\r
+#if HEAPMODE\r
+       void* ctx = malloc(sizeof(struct refTables));\r
+       int result;\r
+       if (isize < LZ4_64KLIMIT)\r
+               result = LZ4_compress64kCtx(&ctx, source, dest, isize);\r
+       else result = LZ4_compressCtx(&ctx, source, dest, isize);\r
+       free(ctx);\r
+       return result;\r
+#else\r
+       if (isize < (int)LZ4_64KLIMIT) return LZ4_compress64kCtx(NULL, source, dest, isize);\r
+       return LZ4_compressCtx(NULL, source, dest, isize);\r
+#endif\r
+}\r
+\r
+\r
+\r
+\r
+//****************************\r
+// Decompression functions\r
+//****************************\r
+\r
+// Note : The decoding functions LZ4_uncompress() and LZ4_uncompress_unknownOutputSize()\r
+//             are safe against "buffer overflow" attack type.\r
+//             They will never write nor read outside of the provided output buffers.\r
+//      LZ4_uncompress_unknownOutputSize() also insures that it will never read outside of the input buffer.\r
+//             A corrupted input will produce an error result, a negative int, indicating the position of the error within input stream.\r
+\r
+int LZ4_uncompress(const char* source,\r
+                                char* dest,\r
+                                int osize)\r
+{\r
+       // Local Variables\r
+       const BYTE* restrict ip = (const BYTE*) source;\r
+       const BYTE* restrict ref;\r
+\r
+       BYTE* restrict op = (BYTE*) dest;\r
+       BYTE* const oend = op + osize;\r
+       BYTE* cpy;\r
+\r
+       BYTE token;\r
+\r
+       int     len, length;\r
+       size_t dec[] ={0, 3, 2, 3, 0, 0, 0, 0};\r
+\r
+\r
+       // Main Loop\r
+       while (1)\r
+       {\r
+               // get runlength\r
+               token = *ip++;\r
+               if ((length=(token>>ML_BITS)) == RUN_MASK)  { for (;(len=*ip++)==255;length+=255){} length += len; }\r
+\r
+               // copy literals\r
+               cpy = op+length;\r
+               if unlikely(cpy>oend-COPYLENGTH)\r
+               {\r
+                       if (cpy > oend) goto _output_error;          // Error : request to write beyond destination buffer\r
+                       memcpy(op, ip, length);\r
+                       ip += length;\r
+                       break;    // Necessarily EOF\r
+               }\r
+               LZ4_WILDCOPY(ip, op, cpy); ip -= (op-cpy); op = cpy;\r
+\r
+               // get offset\r
+               LZ4_READ_LITTLEENDIAN_16(ref,cpy,ip); ip+=2;\r
+               if (ref < (BYTE* const)dest) goto _output_error;   // Error : offset create reference outside destination buffer\r
+\r
+               // get matchlength\r
+               if ((length=(token&ML_MASK)) == ML_MASK) { for (;*ip==255;length+=255) {ip++;} length += *ip++; }\r
+\r
+               // copy repeated sequence\r
+               if unlikely(op-ref<STEPSIZE)\r
+               {\r
+#if LZ4_ARCH64\r
+                       size_t dec2table[]={0, 0, 0, -1, 0, 1, 2, 3};\r
+                       size_t dec2 = dec2table[op-ref];\r
+#else\r
+                       const int dec2 = 0;\r
+#endif\r
+                       *op++ = *ref++;\r
+                       *op++ = *ref++;\r
+                       *op++ = *ref++;\r
+                       *op++ = *ref++;\r
+                       ref -= dec[op-ref];\r
+                       A32(op)=A32(ref); op += STEPSIZE-4;\r
+                       ref -= dec2;\r
+               } else { LZ4_COPYSTEP(ref,op); }\r
+               cpy = op + length - (STEPSIZE-4);\r
+               if (cpy>oend-COPYLENGTH)\r
+               {\r
+                       if (cpy > oend) goto _output_error;             // Error : request to write beyond destination buffer\r
+                       LZ4_SECURECOPY(ref, op, (oend-COPYLENGTH));\r
+                       while(op<cpy) *op++=*ref++;\r
+                       op=cpy;\r
+                       if (op == oend) break;    // Check EOF (should never happen, since last 5 bytes are supposed to be literals)\r
+                       continue;\r
+               }\r
+               LZ4_SECURECOPY(ref, op, cpy);\r
+               op=cpy;         // correction\r
+       }\r
+\r
+       // end of decoding\r
+       return (int) (((char*)ip)-source);\r
+\r
+       // write overflow error detected\r
+_output_error:\r
+       return (int) (-(((char*)ip)-source));\r
+}\r
+\r
+\r
+int LZ4_uncompress_unknownOutputSize(\r
+                               const char* source,\r
+                               char* dest,\r
+                               int isize,\r
+                               int maxOutputSize)\r
+{\r
+       // Local Variables\r
+       const BYTE* restrict ip = (const BYTE*) source;\r
+       const BYTE* const iend = ip + isize;\r
+       const BYTE* restrict ref;\r
+\r
+       BYTE* restrict op = (BYTE*) dest;\r
+       BYTE* const oend = op + maxOutputSize;\r
+       BYTE* cpy;\r
+\r
+       size_t dec[] ={0, 3, 2, 3, 0, 0, 0, 0};\r
+\r
+\r
+       // Main Loop\r
+       while (ip<iend)\r
+       {\r
+               BYTE token;\r
+               int length;\r
+\r
+               // get runlength\r
+               token = *ip++;\r
+               if ((length=(token>>ML_BITS)) == RUN_MASK) { int s=255; while ((ip<iend) && (s==255)) { s=*ip++; length += s; } }\r
+\r
+               // copy literals\r
+               cpy = op+length;\r
+               if ((cpy>oend-COPYLENGTH) || (ip+length>iend-COPYLENGTH))\r
+               {\r
+                       if (cpy > oend) goto _output_error;          // Error : request to write beyond destination buffer\r
+                       if (ip+length > iend) goto _output_error;    // Error : request to read beyond source buffer\r
+                       memcpy(op, ip, length);\r
+                       op += length;\r
+                       ip += length;\r
+                       if (ip<iend) goto _output_error;             // Error : LZ4 format violation\r
+                       break;    // Necessarily EOF, due to parsing restrictions\r
+               }\r
+               LZ4_WILDCOPY(ip, op, cpy); ip -= (op-cpy); op = cpy;\r
+\r
+               // get offset\r
+               LZ4_READ_LITTLEENDIAN_16(ref,cpy,ip); ip+=2;\r
+               if (ref < (BYTE* const)dest) goto _output_error;   // Error : offset creates reference outside of destination buffer\r
+\r
+               // get matchlength\r
+               if ((length=(token&ML_MASK)) == ML_MASK) { while (ip<iend) { int s = *ip++; length +=s; if (s==255) continue; break; } }\r
+\r
+               // copy repeated sequence\r
+               if unlikely(op-ref<STEPSIZE)\r
+               {\r
+#if LZ4_ARCH64\r
+                       size_t dec2table[]={0, 0, 0, -1, 0, 1, 2, 3};\r
+                       size_t dec2 = dec2table[op-ref];\r
+#else\r
+                       const int dec2 = 0;\r
+#endif\r
+                       *op++ = *ref++;\r
+                       *op++ = *ref++;\r
+                       *op++ = *ref++;\r
+                       *op++ = *ref++;\r
+                       ref -= dec[op-ref];\r
+                       A32(op)=A32(ref); op += STEPSIZE-4;\r
+                       ref -= dec2;\r
+               } else { LZ4_COPYSTEP(ref,op); }\r
+               cpy = op + length - (STEPSIZE-4);\r
+               if (cpy>oend-COPYLENGTH)\r
+               {\r
+                       if (cpy > oend) goto _output_error;           // Error : request to write outside of destination buffer\r
+                       LZ4_SECURECOPY(ref, op, (oend-COPYLENGTH));\r
+                       while(op<cpy) *op++=*ref++;\r
+                       op=cpy;\r
+                       if (op == oend) break;    // Check EOF (should never happen, since last 5 bytes are supposed to be literals)\r
+                       continue;\r
+               }\r
+               LZ4_SECURECOPY(ref, op, cpy);\r
+               op=cpy;         // correction\r
+       }\r
+\r
+       // end of decoding\r
+       return (int) (((char*)op)-dest);\r
+\r
+       // write overflow error detected\r
+_output_error:\r
+       return (int) (-(((char*)ip)-source));\r
+}\r
+\r
diff --git a/src/lib/lz4/lz4.h b/src/lib/lz4/lz4.h
new file mode 100644 (file)
index 0000000..ebd62b6
--- /dev/null
@@ -0,0 +1,120 @@
+/*\r
+   LZ4 - Fast LZ compression algorithm\r
+   Header File\r
+   Copyright (C) 2011-2012, Yann Collet.\r
+   BSD 2-Clause License (http://www.opensource.org/licenses/bsd-license.php)\r
+\r
+   Redistribution and use in source and binary forms, with or without\r
+   modification, are permitted provided that the following conditions are\r
+   met:\r
+\r
+       * Redistributions of source code must retain the above copyright\r
+   notice, this list of conditions and the following disclaimer.\r
+       * Redistributions in binary form must reproduce the above\r
+   copyright notice, this list of conditions and the following disclaimer\r
+   in the documentation and/or other materials provided with the\r
+   distribution.\r
+\r
+   THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\r
+   "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\r
+   LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\r
+   A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\r
+   OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\r
+   SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\r
+   LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\r
+   DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\r
+   THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\r
+   (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\r
+   OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\r
+\r
+   You can contact the author at :\r
+   - LZ4 homepage : http://fastcompression.blogspot.com/p/lz4.html\r
+   - LZ4 source repository : http://code.google.com/p/lz4/\r
+*/\r
+#pragma once\r
+\r
+#if defined (__cplusplus)\r
+extern "C" {\r
+#endif\r
+\r
+\r
+//****************************\r
+// Simple Functions\r
+//****************************\r
+\r
+int LZ4_compress   (const char* source, char* dest, int isize);\r
+int LZ4_uncompress (const char* source, char* dest, int osize);\r
+\r
+/*\r
+LZ4_compress() :\r
+       isize  : is the input size. Max supported value is ~1.9GB\r
+       return : the number of bytes written in buffer dest\r
+                        or 0 if the compression fails (if LZ4_COMPRESSMIN is set)\r
+       note : destination buffer must be already allocated.\r
+               destination buffer must be sized to handle worst cases situations (input data not compressible)\r
+               worst case size evaluation is provided by function LZ4_compressBound()\r
+\r
+LZ4_uncompress() :\r
+       osize  : is the output size, therefore the original size\r
+       return : the number of bytes read in the source buffer\r
+                        If the source stream is malformed, the function will stop decoding and return a negative result, indicating the byte position of the faulty instruction\r
+                        This function never writes beyond dest + osize, and is therefore protected against malicious data packets\r
+       note : destination buffer must be already allocated\r
+*/\r
+\r
+\r
+//****************************\r
+// Advanced Functions\r
+//****************************\r
+\r
+int LZ4_compressBound(int isize);\r
+\r
+/*\r
+LZ4_compressBound() :\r
+       Provides the maximum size that LZ4 may output in a "worst case" scenario (input data not compressible)\r
+       primarily useful for memory allocation of output buffer.\r
+\r
+       isize  : is the input size. Max supported value is ~1.9GB\r
+       return : maximum output size in a "worst case" scenario\r
+       note : this function is limited by "int" range (2^31-1)\r
+*/\r
+\r
+\r
+int LZ4_uncompress_unknownOutputSize (const char* source, char* dest, int isize, int maxOutputSize);\r
+\r
+/*\r
+LZ4_uncompress_unknownOutputSize() :\r
+       isize  : is the input size, therefore the compressed size\r
+       maxOutputSize : is the size of the destination buffer (which must be already allocated)\r
+       return : the number of bytes decoded in the destination buffer (necessarily <= maxOutputSize)\r
+                        If the source stream is malformed, the function will stop decoding and return a negative result, indicating the byte position of the faulty instruction\r
+                        This function never writes beyond dest + maxOutputSize, and is therefore protected against malicious data packets\r
+       note   : Destination buffer must be already allocated.\r
+                This version is slightly slower than LZ4_uncompress()\r
+*/\r
+\r
+\r
+int LZ4_compressCtx(void** ctx, const char* source,  char* dest, int isize);\r
+int LZ4_compress64kCtx(void** ctx, const char* source,  char* dest, int isize);\r
+\r
+/*\r
+LZ4_compressCtx() :\r
+       This function explicitly handles the CTX memory structure.\r
+       It avoids allocating/deallocating memory between each call, improving performance when malloc is heavily invoked.\r
+       This function is only useful when memory is allocated into the heap (HASH_LOG value beyond STACK_LIMIT)\r
+       Performance difference will be noticeable only when repetitively calling the compression function over many small segments.\r
+       Note : by default, memory is allocated into the stack, therefore "malloc" is not invoked.\r
+LZ4_compress64kCtx() :\r
+       Same as LZ4_compressCtx(), but specific to small inputs (<64KB).\r
+       isize *Must* be <64KB, otherwise the output will be corrupted.\r
+\r
+       On first call : provide a *ctx=NULL; It will be automatically allocated.\r
+       On next calls : reuse the same ctx pointer.\r
+       Use different pointers for different threads when doing multi-threading.\r
+\r
+*/\r
+\r
+\r
+#if defined (__cplusplus)\r
+}\r
+#endif\r
diff --git a/src/lib/lz4/lz4hc.c b/src/lib/lz4/lz4hc.c
new file mode 100644 (file)
index 0000000..cca755c
--- /dev/null
@@ -0,0 +1,663 @@
+/*\r
+   LZ4 HC - High Compression Mode of LZ4\r
+   Copyright (C) 2011-2012, Yann Collet.\r
+   BSD 2-Clause License (http://www.opensource.org/licenses/bsd-license.php)\r
+\r
+   Redistribution and use in source and binary forms, with or without\r
+   modification, are permitted provided that the following conditions are\r
+   met:\r
+\r
+       * Redistributions of source code must retain the above copyright\r
+   notice, this list of conditions and the following disclaimer.\r
+       * Redistributions in binary form must reproduce the above\r
+   copyright notice, this list of conditions and the following disclaimer\r
+   in the documentation and/or other materials provided with the\r
+   distribution.\r
+\r
+   THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\r
+   "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\r
+   LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\r
+   A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\r
+   OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\r
+   SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\r
+   LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\r
+   DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\r
+   THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\r
+   (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\r
+   OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\r
+\r
+   You can contact the author at :\r
+   - LZ4 homepage : http://fastcompression.blogspot.com/p/lz4.html\r
+   - LZ4 source repository : http://code.google.com/p/lz4/\r
+*/\r
+\r
+\r
+//**************************************\r
+// CPU Feature Detection\r
+//**************************************\r
+// 32 or 64 bits ?\r
+#if (defined(__x86_64__) || defined(__x86_64) || defined(__amd64__) || defined(__amd64) || defined(__ppc64__) || defined(_WIN64) || defined(__LP64__) || defined(_LP64) )   // Detects 64 bits mode\r
+#define LZ4_ARCH64 1\r
+#else\r
+#define LZ4_ARCH64 0\r
+#endif\r
+\r
+// Little Endian or Big Endian ? \r
+#if (defined(__BIG_ENDIAN__) || defined(__BIG_ENDIAN) || defined(_BIG_ENDIAN) || defined(_ARCH_PPC) || defined(__PPC__) || defined(__PPC) || defined(PPC) || defined(__powerpc__) || defined(__powerpc) || defined(powerpc) || ((defined(__BYTE_ORDER__)&&(__BYTE_ORDER__ == __ORDER_BIG_ENDIAN__))) )\r
+#define LZ4_BIG_ENDIAN 1\r
+#else\r
+// Little Endian assumed. PDP Endian and other very rare endian format are unsupported.\r
+#endif\r
+\r
+// Unaligned memory access is automatically enabled for "common" CPU, such as x86.\r
+// For others CPU, the compiler will be more cautious, and insert extra code to ensure aligned access is respected\r
+// If you know your target CPU supports unaligned memory access, you may want to force this option manually to improve performance\r
+#if defined(__ARM_FEATURE_UNALIGNED)\r
+#define LZ4_FORCE_UNALIGNED_ACCESS 1\r
+#endif\r
+\r
+\r
+//**************************************\r
+// Compiler Options\r
+//**************************************\r
+#if __STDC_VERSION__ >= 199901L    // C99\r
+  /* "restrict" is a known keyword */\r
+#else\r
+#define restrict  // Disable restrict\r
+#endif\r
+\r
+#ifdef _MSC_VER\r
+#define inline __forceinline    // Visual is not C99, but supports some kind of inline\r
+#endif\r
+\r
+#ifdef _MSC_VER  // Visual Studio\r
+#define bswap16(x) _byteswap_ushort(x)\r
+#else\r
+#define bswap16(x)  ((unsigned short int) ((((x) >> 8) & 0xffu) | (((x) & 0xffu) << 8)))\r
+#endif\r
+\r
+\r
+//**************************************\r
+// Includes\r
+//**************************************\r
+#include <stdlib.h>   // calloc, free\r
+#include <string.h>   // memset, memcpy\r
+#include "lz4hc.h"\r
+\r
+#define ALLOCATOR(s) calloc(1,s)\r
+#define FREEMEM free\r
+#define MEM_INIT memset\r
+\r
+\r
+//**************************************\r
+// Basic Types\r
+//**************************************\r
+#if defined(_MSC_VER)    // Visual Studio does not support 'stdint' natively\r
+#define BYTE   unsigned __int8\r
+#define U16            unsigned __int16\r
+#define U32            unsigned __int32\r
+#define S32            __int32\r
+#define U64            unsigned __int64\r
+#else\r
+#include <stdint.h>\r
+#define BYTE   uint8_t\r
+#define U16            uint16_t\r
+#define U32            uint32_t\r
+#define S32            int32_t\r
+#define U64            uint64_t\r
+#endif\r
+\r
+#ifndef LZ4_FORCE_UNALIGNED_ACCESS\r
+#pragma pack(push, 1) \r
+#endif\r
+\r
+typedef struct _U16_S { U16 v; } U16_S;\r
+typedef struct _U32_S { U32 v; } U32_S;\r
+typedef struct _U64_S { U64 v; } U64_S;\r
+\r
+#ifndef LZ4_FORCE_UNALIGNED_ACCESS\r
+#pragma pack(pop) \r
+#endif\r
+\r
+#define A64(x) (((U64_S *)(x))->v)\r
+#define A32(x) (((U32_S *)(x))->v)\r
+#define A16(x) (((U16_S *)(x))->v)\r
+\r
+\r
+//**************************************\r
+// Constants\r
+//**************************************\r
+#define MINMATCH 4\r
+\r
+#define DICTIONARY_LOGSIZE 16\r
+#define MAXD (1<<DICTIONARY_LOGSIZE)\r
+#define MAXD_MASK ((U32)(MAXD - 1))\r
+#define MAX_DISTANCE (MAXD - 1)\r
+\r
+#define HASH_LOG (DICTIONARY_LOGSIZE-1)\r
+#define HASHTABLESIZE (1 << HASH_LOG)\r
+#define HASH_MASK (HASHTABLESIZE - 1)\r
+\r
+#define MAX_NB_ATTEMPTS 256\r
+\r
+#define ML_BITS  4\r
+#define ML_MASK  (size_t)((1U<<ML_BITS)-1)\r
+#define RUN_BITS (8-ML_BITS)\r
+#define RUN_MASK ((1U<<RUN_BITS)-1)\r
+\r
+#define COPYLENGTH 8\r
+#define LASTLITERALS 5\r
+#define MFLIMIT (COPYLENGTH+MINMATCH)\r
+#define MINLENGTH (MFLIMIT+1)\r
+#define OPTIMAL_ML (int)((ML_MASK-1)+MINMATCH)\r
+\r
+\r
+//**************************************\r
+// Architecture-specific macros\r
+//**************************************\r
+#if LZ4_ARCH64 // 64-bit\r
+#define STEPSIZE 8\r
+#define LZ4_COPYSTEP(s,d)              A64(d) = A64(s); d+=8; s+=8;\r
+#define LZ4_COPYPACKET(s,d)            LZ4_COPYSTEP(s,d)\r
+#define UARCH U64\r
+#define AARCH A64\r
+#define HTYPE                                  U32\r
+#define INITBASE(b,s)                  const BYTE* const b = s\r
+#else          // 32-bit\r
+#define STEPSIZE 4\r
+#define LZ4_COPYSTEP(s,d)              A32(d) = A32(s); d+=4; s+=4;\r
+#define LZ4_COPYPACKET(s,d)            LZ4_COPYSTEP(s,d); LZ4_COPYSTEP(s,d);\r
+#define UARCH U32\r
+#define AARCH A32\r
+#define HTYPE                                  const BYTE*\r
+#define INITBASE(b,s)              const int b = 0\r
+#endif\r
+\r
+#if defined(LZ4_BIG_ENDIAN)\r
+#define LZ4_READ_LITTLEENDIAN_16(d,s,p) { U16 v = A16(p); v = bswap16(v); d = (s) - v; }\r
+#define LZ4_WRITE_LITTLEENDIAN_16(p,i)  { U16 v = (U16)(i); v = bswap16(v); A16(p) = v; p+=2; }\r
+#else          // Little Endian\r
+#define LZ4_READ_LITTLEENDIAN_16(d,s,p) { d = (s) - A16(p); }\r
+#define LZ4_WRITE_LITTLEENDIAN_16(p,v)  { A16(p) = v; p+=2; }\r
+#endif\r
+\r
+\r
+//************************************************************\r
+// Local Types\r
+//************************************************************\r
+typedef struct \r
+{\r
+       const BYTE* base;\r
+       HTYPE hashTable[HASHTABLESIZE];\r
+       U16 chainTable[MAXD];\r
+       const BYTE* nextToUpdate;\r
+} LZ4HC_Data_Structure;\r
+\r
+\r
+//**************************************\r
+// Macros\r
+//**************************************\r
+#define LZ4_WILDCOPY(s,d,e)            do { LZ4_COPYPACKET(s,d) } while (d<e);\r
+#define LZ4_BLINDCOPY(s,d,l)   { BYTE* e=d+l; LZ4_WILDCOPY(s,d,e); d=e; }\r
+#define HASH_FUNCTION(i)       (((i) * 2654435761U) >> ((MINMATCH*8)-HASH_LOG))\r
+#define HASH_VALUE(p)          HASH_FUNCTION(*(U32*)(p))\r
+#define HASH_POINTER(p)                (HashTable[HASH_VALUE(p)] + base)\r
+#define DELTANEXT(p)           chainTable[(size_t)(p) & MAXD_MASK] \r
+#define GETNEXT(p)                     ((p) - (size_t)DELTANEXT(p))\r
+#define ADD_HASH(p)                    { size_t delta = (p) - HASH_POINTER(p); if (delta>MAX_DISTANCE) delta = MAX_DISTANCE; DELTANEXT(p) = (U16)delta; HashTable[HASH_VALUE(p)] = (p) - base; }\r
+\r
+\r
+//**************************************\r
+// Private functions\r
+//**************************************\r
+#if LZ4_ARCH64\r
+\r
+inline static int LZ4_NbCommonBytes (register U64 val)\r
+{\r
+#if defined(LZ4_BIG_ENDIAN)\r
+    #if defined(_MSC_VER) && !defined(LZ4_FORCE_SW_BITCOUNT)\r
+    unsigned long r = 0;\r
+    _BitScanReverse64( &r, val );\r
+    return (int)(r>>3);\r
+    #elif defined(__GNUC__) && ((__GNUC__ * 100 + __GNUC_MINOR__) >= 304) && !defined(LZ4_FORCE_SW_BITCOUNT)\r
+    return (__builtin_clzll(val) >> 3); \r
+    #else\r
+       int r;\r
+       if (!(val>>32)) { r=4; } else { r=0; val>>=32; }\r
+       if (!(val>>16)) { r+=2; val>>=8; } else { val>>=24; }\r
+       r += (!val);\r
+       return r;\r
+    #endif\r
+#else\r
+    #if defined(_MSC_VER) && !defined(LZ4_FORCE_SW_BITCOUNT)\r
+    unsigned long r = 0;\r
+    _BitScanForward64( &r, val );\r
+    return (int)(r>>3);\r
+    #elif defined(__GNUC__) && ((__GNUC__ * 100 + __GNUC_MINOR__) >= 304) && !defined(LZ4_FORCE_SW_BITCOUNT)\r
+    return (__builtin_ctzll(val) >> 3); \r
+    #else\r
+       static const int DeBruijnBytePos[64] = { 0, 0, 0, 0, 0, 1, 1, 2, 0, 3, 1, 3, 1, 4, 2, 7, 0, 2, 3, 6, 1, 5, 3, 5, 1, 3, 4, 4, 2, 5, 6, 7, 7, 0, 1, 2, 3, 3, 4, 6, 2, 6, 5, 5, 3, 4, 5, 6, 7, 1, 2, 4, 6, 4, 4, 5, 7, 2, 6, 5, 7, 6, 7, 7 };\r
+       return DeBruijnBytePos[((U64)((val & -val) * 0x0218A392CDABBD3F)) >> 58];\r
+    #endif\r
+#endif\r
+}\r
+\r
+#else\r
+\r
+inline static int LZ4_NbCommonBytes (register U32 val)\r
+{\r
+#if defined(LZ4_BIG_ENDIAN)\r
+    #if defined(_MSC_VER) && !defined(LZ4_FORCE_SW_BITCOUNT)\r
+    unsigned long r = 0;\r
+    _BitScanReverse( &r, val );\r
+    return (int)(r>>3);\r
+    #elif defined(__GNUC__) && ((__GNUC__ * 100 + __GNUC_MINOR__) >= 304) && !defined(LZ4_FORCE_SW_BITCOUNT)\r
+    return (__builtin_clz(val) >> 3); \r
+    #else\r
+       int r;\r
+       if (!(val>>16)) { r=2; val>>=8; } else { r=0; val>>=24; }\r
+       r += (!val);\r
+       return r;\r
+    #endif\r
+#else\r
+    #if defined(_MSC_VER) && !defined(LZ4_FORCE_SW_BITCOUNT)\r
+    unsigned long r = 0;\r
+    _BitScanForward( &r, val );\r
+    return (int)(r>>3);\r
+    #elif defined(__GNUC__) && ((__GNUC__ * 100 + __GNUC_MINOR__) >= 304) && !defined(LZ4_FORCE_SW_BITCOUNT)\r
+    return (__builtin_ctz(val) >> 3); \r
+    #else\r
+       static const int DeBruijnBytePos[32] = { 0, 0, 3, 0, 3, 1, 3, 0, 3, 2, 2, 1, 3, 2, 0, 1, 3, 3, 1, 2, 2, 2, 2, 0, 3, 1, 2, 0, 1, 0, 1, 1 };\r
+       return DeBruijnBytePos[((U32)((val & -(S32)val) * 0x077CB531U)) >> 27];\r
+    #endif\r
+#endif\r
+}\r
+\r
+#endif\r
+\r
+\r
+inline static int LZ4HC_Init (LZ4HC_Data_Structure* hc4, const BYTE* base)\r
+{\r
+       MEM_INIT((void*)hc4->hashTable, 0, sizeof(hc4->hashTable));\r
+       MEM_INIT(hc4->chainTable, 0xFF, sizeof(hc4->chainTable));\r
+       hc4->nextToUpdate = base + LZ4_ARCH64;\r
+       hc4->base = base;\r
+       return 1;\r
+}\r
+\r
+\r
+inline static void* LZ4HC_Create (const BYTE* base)\r
+{\r
+       void* hc4 = ALLOCATOR(sizeof(LZ4HC_Data_Structure));\r
+\r
+       LZ4HC_Init (hc4, base);\r
+       return hc4;\r
+}\r
+\r
+\r
+inline static int LZ4HC_Free (void** LZ4HC_Data)\r
+{\r
+       FREEMEM(*LZ4HC_Data);\r
+       *LZ4HC_Data = NULL;\r
+       return (1);\r
+}\r
+\r
+\r
+inline static void LZ4HC_Insert (LZ4HC_Data_Structure* hc4, const BYTE* ip)\r
+{\r
+       U16*   chainTable = hc4->chainTable;\r
+       HTYPE* HashTable  = hc4->hashTable;\r
+       INITBASE(base,hc4->base);\r
+\r
+       while(hc4->nextToUpdate < ip)\r
+       {\r
+               ADD_HASH(hc4->nextToUpdate);\r
+               hc4->nextToUpdate++;\r
+       }\r
+}\r
+\r
+\r
+inline static int LZ4HC_InsertAndFindBestMatch (LZ4HC_Data_Structure* hc4, const BYTE* ip, const BYTE* const matchlimit, const BYTE** matchpos)\r
+{\r
+       U16* const chainTable = hc4->chainTable;\r
+       HTYPE* const HashTable = hc4->hashTable;\r
+       const BYTE* ref;\r
+       INITBASE(base,hc4->base);\r
+       int nbAttempts=MAX_NB_ATTEMPTS;\r
+       int ml=0;\r
+\r
+       // HC4 match finder\r
+       LZ4HC_Insert(hc4, ip);\r
+       ref = HASH_POINTER(ip);\r
+       while ((ref > (ip-MAX_DISTANCE)) && (nbAttempts))\r
+       {\r
+               nbAttempts--;\r
+               if (*(ref+ml) == *(ip+ml))\r
+               if (*(U32*)ref == *(U32*)ip)\r
+               {\r
+                       const BYTE* reft = ref+MINMATCH;\r
+                       const BYTE* ipt = ip+MINMATCH;\r
+\r
+                       while (ipt<matchlimit-(STEPSIZE-1))\r
+                       {\r
+                               UARCH diff = AARCH(reft) ^ AARCH(ipt);\r
+                               if (!diff) { ipt+=STEPSIZE; reft+=STEPSIZE; continue; }\r
+                               ipt += LZ4_NbCommonBytes(diff);\r
+                               goto _endCount;\r
+                       }\r
+                       if (LZ4_ARCH64) if ((ipt<(matchlimit-3)) && (A32(reft) == A32(ipt))) { ipt+=4; reft+=4; }\r
+                       if ((ipt<(matchlimit-1)) && (A16(reft) == A16(ipt))) { ipt+=2; reft+=2; }\r
+                       if ((ipt<matchlimit) && (*reft == *ipt)) ipt++;\r
+_endCount:\r
+\r
+                       if (ipt-ip > ml) { ml = ipt-ip; *matchpos = ref; }\r
+               }\r
+               ref = GETNEXT(ref);\r
+       }\r
+\r
+       return ml;\r
+}\r
+\r
+\r
+inline static int LZ4HC_InsertAndGetWiderMatch (LZ4HC_Data_Structure* hc4, const BYTE* ip, const BYTE* startLimit, const BYTE* matchlimit, int longest, const BYTE** matchpos, const BYTE** startpos)\r
+{\r
+       U16* const  chainTable = hc4->chainTable;\r
+       HTYPE* const HashTable = hc4->hashTable;\r
+       INITBASE(base,hc4->base);\r
+       const BYTE*  ref;\r
+       int nbAttempts = MAX_NB_ATTEMPTS;\r
+       int delta = ip-startLimit;\r
+\r
+       // First Match\r
+       LZ4HC_Insert(hc4, ip);\r
+       ref = HASH_POINTER(ip);\r
+\r
+       while ((ref > ip-MAX_DISTANCE) && (ref >= hc4->base) && (nbAttempts))\r
+       {\r
+               nbAttempts--;\r
+               if (*(startLimit + longest) == *(ref - delta + longest))\r
+               if (*(U32*)ref == *(U32*)ip)\r
+               {\r
+                       const BYTE* reft = ref+MINMATCH;\r
+                       const BYTE* ipt = ip+MINMATCH;\r
+                       const BYTE* startt = ip;\r
+\r
+                       while (ipt<matchlimit-(STEPSIZE-1))\r
+                       {\r
+                               UARCH diff = AARCH(reft) ^ AARCH(ipt);\r
+                               if (!diff) { ipt+=STEPSIZE; reft+=STEPSIZE; continue; }\r
+                               ipt += LZ4_NbCommonBytes(diff);\r
+                               goto _endCount;\r
+                       }\r
+                       if (LZ4_ARCH64) if ((ipt<(matchlimit-3)) && (A32(reft) == A32(ipt))) { ipt+=4; reft+=4; }\r
+                       if ((ipt<(matchlimit-1)) && (A16(reft) == A16(ipt))) { ipt+=2; reft+=2; }\r
+                       if ((ipt<matchlimit) && (*reft == *ipt)) ipt++;\r
+_endCount:\r
+\r
+                       reft = ref;\r
+                       while ((startt>startLimit) && (reft > hc4->base) && (startt[-1] == reft[-1])) {startt--; reft--;}\r
+\r
+                       if ((ipt-startt) > longest)\r
+                       {\r
+                               longest = ipt-startt;\r
+                               *matchpos = reft;\r
+                               *startpos = startt;\r
+                       }\r
+               }\r
+               ref = GETNEXT(ref);\r
+       }\r
+\r
+       return longest;\r
+}\r
+\r
+\r
+inline static int LZ4_encodeSequence(const BYTE** ip, BYTE** op, const BYTE** anchor, int ml, const BYTE* ref)\r
+{\r
+       int length, len; \r
+       BYTE* token;\r
+\r
+       // Encode Literal length\r
+       length = *ip - *anchor;\r
+       token = (*op)++;\r
+       if (length>=(int)RUN_MASK) { *token=(RUN_MASK<<ML_BITS); len = length-RUN_MASK; for(; len > 254 ; len-=255) *(*op)++ = 255;  *(*op)++ = (BYTE)len; } \r
+       else *token = (length<<ML_BITS);\r
+\r
+       // Copy Literals\r
+       LZ4_BLINDCOPY(*anchor, *op, length);\r
+\r
+       // Encode Offset\r
+       LZ4_WRITE_LITTLEENDIAN_16(*op,*ip-ref);\r
+\r
+       // Encode MatchLength\r
+       len = (int)(ml-MINMATCH);\r
+       if (len>=(int)ML_MASK) { *token+=ML_MASK; len-=ML_MASK; for(; len > 509 ; len-=510) { *(*op)++ = 255; *(*op)++ = 255; } if (len > 254) { len-=255; *(*op)++ = 255; } *(*op)++ = (BYTE)len; } \r
+       else *token += len;     \r
+\r
+       // Prepare next loop\r
+       *ip += ml;\r
+       *anchor = *ip; \r
+\r
+       return 0;\r
+}\r
+\r
+\r
+//****************************\r
+// Compression CODE\r
+//****************************\r
+\r
+int LZ4_compressHCCtx(LZ4HC_Data_Structure* ctx,\r
+                                const char* source, \r
+                                char* dest,\r
+                                int isize)\r
+{      \r
+       const BYTE* ip = (const BYTE*) source;\r
+       const BYTE* anchor = ip;\r
+       const BYTE* const iend = ip + isize;\r
+       const BYTE* const mflimit = iend - MFLIMIT;\r
+       const BYTE* const matchlimit = (iend - LASTLITERALS);\r
+\r
+       BYTE* op = (BYTE*) dest;\r
+\r
+       int     ml, ml2, ml3, ml0;\r
+       const BYTE* ref=NULL;\r
+       const BYTE* start2=NULL;\r
+       const BYTE* ref2=NULL;\r
+       const BYTE* start3=NULL;\r
+       const BYTE* ref3=NULL;\r
+       const BYTE* start0;\r
+       const BYTE* ref0;\r
+\r
+       ip++;\r
+\r
+       // Main Loop\r
+       while (ip < mflimit)\r
+       {\r
+               ml = LZ4HC_InsertAndFindBestMatch (ctx, ip, matchlimit, (&ref));\r
+               if (!ml) { ip++; continue; }\r
+\r
+               // saved, in case we would skip too much\r
+               start0 = ip;\r
+               ref0 = ref;\r
+               ml0 = ml;\r
+\r
+_Search2:\r
+               if (ip+ml < mflimit)\r
+                       ml2 = LZ4HC_InsertAndGetWiderMatch(ctx, ip + ml - 2, ip + 1, matchlimit, ml, &ref2, &start2);\r
+               else ml2=ml;\r
+\r
+               if (ml2 == ml)  // No better match\r
+               {\r
+                       LZ4_encodeSequence(&ip, &op, &anchor, ml, ref);\r
+                       continue;\r
+               }\r
+\r
+               if (start0 < ip)\r
+               {\r
+                       if (start2 < ip + ml0)   // empirical\r
+                       {\r
+                               ip = start0;\r
+                               ref = ref0;\r
+                               ml = ml0;\r
+                       }\r
+               }\r
+\r
+               // Here, start0==ip\r
+               if ((start2 - ip) < 3)   // First Match too small : removed\r
+               {\r
+                       ml = ml2;\r
+                       ip = start2;\r
+                       ref =ref2;\r
+                       goto _Search2;\r
+               }\r
+\r
+_Search3:\r
+               // Currently we have :\r
+               // ml2 > ml1, and\r
+               // ip1+3 <= ip2 (usually < ip1+ml1)\r
+               if ((start2 - ip) < OPTIMAL_ML)\r
+               {\r
+                       int correction;\r
+                       int new_ml = ml;\r
+                       if (new_ml > OPTIMAL_ML) new_ml = OPTIMAL_ML;\r
+                       if (ip+new_ml > start2 + ml2 - MINMATCH) new_ml = start2 - ip + ml2 - MINMATCH;\r
+                       correction = new_ml - (start2 - ip);\r
+                       if (correction > 0)\r
+                       {\r
+                               start2 += correction;\r
+                               ref2 += correction;\r
+                               ml2 -= correction;\r
+                       }\r
+               }\r
+               // Now, we have start2 = ip+new_ml, with new_ml=min(ml, OPTIMAL_ML=18)\r
+\r
+               if (start2 + ml2 < mflimit)\r
+                       ml3 = LZ4HC_InsertAndGetWiderMatch(ctx, start2 + ml2 - 3, start2, matchlimit, ml2, &ref3, &start3);\r
+               else ml3=ml2;\r
+\r
+               if (ml3 == ml2) // No better match : 2 sequences to encode\r
+               {\r
+                       // ip & ref are known; Now for ml\r
+                       if (start2 < ip+ml)\r
+                       {\r
+                               if ((start2 - ip) < OPTIMAL_ML)\r
+                               {\r
+                                       int correction;\r
+                                       if (ml > OPTIMAL_ML) ml = OPTIMAL_ML;\r
+                                       if (ip+ml > start2 + ml2 - MINMATCH) ml = start2 - ip + ml2 - MINMATCH;\r
+                                       correction = ml - (start2 - ip);\r
+                                       if (correction > 0)\r
+                                       {\r
+                                               start2 += correction;\r
+                                               ref2 += correction;\r
+                                               ml2 -= correction;\r
+                                       }\r
+                               }\r
+                               else\r
+                               {\r
+                                       ml = start2 - ip;\r
+                               }\r
+                       }\r
+                       // Now, encode 2 sequences\r
+                       LZ4_encodeSequence(&ip, &op, &anchor, ml, ref);\r
+                       ip = start2;\r
+                       LZ4_encodeSequence(&ip, &op, &anchor, ml2, ref2);\r
+                       continue;\r
+               }\r
+\r
+               if (start3 < ip+ml+3) // Not enough space for match 2 : remove it\r
+               {\r
+                       if (start3 >= (ip+ml)) // can write Seq1 immediately ==> Seq2 is removed, so Seq3 becomes Seq1\r
+                       {\r
+                               if (start2 < ip+ml)\r
+                               {\r
+                                       int correction = (ip+ml) - start2;\r
+                                       start2 += correction;\r
+                                       ref2 += correction;\r
+                                       ml2 -= correction;\r
+                                       if (ml2 < MINMATCH)\r
+                                       {\r
+                                               start2 = start3;\r
+                                               ref2 = ref3;\r
+                                               ml2 = ml3;\r
+                                       }\r
+                               }\r
+\r
+                               LZ4_encodeSequence(&ip, &op, &anchor, ml, ref);\r
+                               ip  = start3;\r
+                               ref = ref3;\r
+                               ml  = ml3;\r
+\r
+                               start0 = start2;\r
+                               ref0 = ref2;\r
+                               ml0 = ml2;\r
+                               goto _Search2;\r
+                       }\r
+\r
+                       start2 = start3;\r
+                       ref2 = ref3;\r
+                       ml2 = ml3;\r
+                       goto _Search3;\r
+               }\r
+\r
+               // OK, now we have 3 ascending matches; let's write at least the first one\r
+               // ip & ref are known; Now for ml\r
+               if (start2 < ip+ml)\r
+               {\r
+                       if ((start2 - ip) < (int)ML_MASK)\r
+                       {\r
+                               int correction;\r
+                               if (ml > OPTIMAL_ML) ml = OPTIMAL_ML;\r
+                               if (ip + ml > start2 + ml2 - MINMATCH) ml = start2 - ip + ml2 - MINMATCH;\r
+                               correction = ml - (start2 - ip);\r
+                               if (correction > 0)\r
+                               {\r
+                                       start2 += correction;\r
+                                       ref2 += correction;\r
+                                       ml2 -= correction;\r
+                               }\r
+                       }\r
+                       else\r
+                       {\r
+                               ml = start2 - ip;\r
+                       }\r
+               }\r
+               LZ4_encodeSequence(&ip, &op, &anchor, ml, ref);\r
+\r
+               ip = start2;\r
+               ref = ref2;\r
+               ml = ml2;\r
+\r
+               start2 = start3;\r
+               ref2 = ref3;\r
+               ml2 = ml3;\r
+\r
+               goto _Search3;\r
+\r
+       }\r
+\r
+       // Encode Last Literals\r
+       {\r
+               int lastRun = iend - anchor;\r
+               if (lastRun>=(int)RUN_MASK) { *op++=(RUN_MASK<<ML_BITS); lastRun-=RUN_MASK; for(; lastRun > 254 ; lastRun-=255) *op++ = 255; *op++ = (BYTE) lastRun; } \r
+               else *op++ = (lastRun<<ML_BITS);\r
+               memcpy(op, anchor, iend - anchor);\r
+               op += iend-anchor;\r
+       } \r
+\r
+       // End\r
+       return (int) (((char*)op)-dest);\r
+}\r
+\r
+\r
+int LZ4_compressHC(const char* source, \r
+                                char* dest,\r
+                                int isize)\r
+{\r
+       void* ctx = LZ4HC_Create((const BYTE*)source);\r
+       int result = LZ4_compressHCCtx(ctx, source, dest, isize);\r
+       LZ4HC_Free (&ctx);\r
+\r
+       return result;\r
+}\r
+\r
+\r
diff --git a/src/lib/lz4/lz4hc.h b/src/lib/lz4/lz4hc.h
new file mode 100644 (file)
index 0000000..cb74689
--- /dev/null
@@ -0,0 +1,60 @@
+/*\r
+   LZ4 HC - High Compression Mode of LZ4\r
+   Header File\r
+   Copyright (C) 2011-2012, Yann Collet.\r
+   BSD 2-Clause License (http://www.opensource.org/licenses/bsd-license.php)\r
+\r
+   Redistribution and use in source and binary forms, with or without\r
+   modification, are permitted provided that the following conditions are\r
+   met:\r
+\r
+       * Redistributions of source code must retain the above copyright\r
+   notice, this list of conditions and the following disclaimer.\r
+       * Redistributions in binary form must reproduce the above\r
+   copyright notice, this list of conditions and the following disclaimer\r
+   in the documentation and/or other materials provided with the\r
+   distribution.\r
+\r
+   THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\r
+   "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\r
+   LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\r
+   A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\r
+   OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\r
+   SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\r
+   LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\r
+   DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\r
+   THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\r
+   (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\r
+   OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\r
+\r
+   You can contact the author at :\r
+   - LZ4 homepage : http://fastcompression.blogspot.com/p/lz4.html\r
+   - LZ4 source repository : http://code.google.com/p/lz4/\r
+*/\r
+#pragma once\r
+\r
+\r
+#if defined (__cplusplus)\r
+extern "C" {\r
+#endif\r
+\r
+\r
+int LZ4_compressHC (const char* source, char* dest, int isize);\r
+\r
+/*\r
+LZ4_compressHC :\r
+       return : the number of bytes in compressed buffer dest\r
+       note : destination buffer must be already allocated. \r
+               To avoid any problem, size it to handle worst cases situations (input data not compressible)\r
+               Worst case size evaluation is provided by function LZ4_compressBound() (see "lz4.h")\r
+*/\r
+\r
+\r
+/* Note :\r
+Decompression functions are provided within regular LZ4 source code (see "lz4.h") (BSD license)\r
+*/\r
+\r
+\r
+#if defined (__cplusplus)\r
+}\r
+#endif\r