# module Flate

The `Flate` module implements an efficient lossless compression/decompression algorithm suitable for text and data. It is a Ruby-wrapper around code from the 'zlib' compression library, written by Jean-loup Gailly and Mark Adler, who kindly grant permission for free use of their work (visit the zlib site). The algorithm for flate is based on huffman encoding and LZ77 compression. For an introduction to the details, see the description by Gailly and Adler. Compression to 1/3 original size is not unusual for text files, which explains the popularity of this algorithm and its use in applications such as 'Zip' and 'gzip', and in PDF files where it is used for lossless compression of text along with JPEG for lossy compression of images. Note that short strings, fewer than 100 bytes or so, may actually 'compress' to a larger string due to the overhead of compression tables.

### Public Class Methods

compress(str) → string click to toggle source

Returns a compressed verion of str in a new string.

    VALUE do_compress(VALUE klass, VALUE str) {
       str = rb_String(str);
       unsigned char *ptr = (unsigned char *)RSTRING_PTR(str);
       long len = RSTRING_LEN(str);
       unsigned long new_len = (len * 11) / 10 + 100;
       unsigned char *new_ptr = ALLOC_N(unsigned char, new_len);
       if (flate_compress(new_ptr, &new_len, ptr, len) != Z_OK) {
          free(new_ptr);
          rb_raise(rb_eArgError, "Error in Flate.compress");
       }
       VALUE new_str = rb_str_new((char *)new_ptr, new_len);
       free(new_ptr);
       return new_str;
    }

expand(str) → string click to toggle source

Returns a decompressed verion of str in a new string. Assumes that str was compressed using `Flate.compress`.

    VALUE do_expand(VALUE klass, VALUE str) {
       str = rb_String(str);
       unsigned char *ptr = (unsigned char *)RSTRING_PTR(str);
       long len = RSTRING_LEN(str);
       unsigned long new_len = len * 4 + 100;
       unsigned char *new_ptr = ALLOC_N(unsigned char, new_len);
       if (flate_expand(&new_ptr, &new_len, ptr, len) != Z_OK) {
          free(new_ptr);
          rb_raise(rb_eArgError, "Error in Flate.expand");
       }
       VALUE new_str = rb_str_new((char *)new_ptr, new_len);
       free(new_ptr);
       return new_str;
    }