1 /* This Source Code Form is subject to the terms of the Mozilla Public
2  * License, v. 2.0. If a copy of the MPL was not distributed with this
3  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
4 
5 #include "mozilla/Compression.h"
6 
7 /**
8  * LZ4 is a very fast byte-wise compression algorithm.
9  *
10  * Compared to Google's Snappy it is faster to compress and decompress and
11  * generally produces output of about the same size.
12  *
13  * Compared to zlib it compresses at about 10x the speed, decompresses at about
14  * 4x the speed and produces output of about 1.5x the size.
15  *
16  */
17 
18 using namespace mozilla::Compression;
19 
20 /**
21  * Compresses 'inputSize' bytes from 'source' into 'dest'.
22  * Destination buffer must be already allocated,
23  * and must be sized to handle worst cases situations (input data not
24  * compressible) Worst case size evaluation is provided by function
25  * LZ4_compressBound()
26  *
27  * @param inputSize is the input size. Max supported value is ~1.9GB
28  * @param return the number of bytes written in buffer dest
29  */
workerlz4_compress(const char * source,size_t inputSize,char * dest)30 extern "C" MOZ_EXPORT size_t workerlz4_compress(const char* source,
31                                                 size_t inputSize, char* dest) {
32   return LZ4::compress(source, inputSize, dest);
33 }
34 
35 /**
36  * If the source stream is malformed, the function will stop decoding
37  * and return a negative result, indicating the byte position of the
38  * faulty instruction
39  *
40  * This function never writes outside of provided buffers, and never
41  * modifies input buffer.
42  *
43  * note : destination buffer must be already allocated.
44  *        its size must be a minimum of 'outputSize' bytes.
45  * @param outputSize is the output size, therefore the original size
46  * @return true/false
47  */
workerlz4_decompress(const char * source,size_t inputSize,char * dest,size_t maxOutputSize,size_t * bytesOutput)48 extern "C" MOZ_EXPORT int workerlz4_decompress(const char* source,
49                                                size_t inputSize, char* dest,
50                                                size_t maxOutputSize,
51                                                size_t* bytesOutput) {
52   return LZ4::decompress(source, inputSize, dest, maxOutputSize, bytesOutput);
53 }
54 
55 /*
56   Provides the maximum size that LZ4 may output in a "worst case"
57   scenario (input data not compressible) primarily useful for memory
58   allocation of output buffer.
59   note : this function is limited by "int" range (2^31-1)
60 
61   @param inputSize is the input size. Max supported value is ~1.9GB
62   @return maximum output size in a "worst case" scenario
63 */
workerlz4_maxCompressedSize(size_t inputSize)64 extern "C" MOZ_EXPORT size_t workerlz4_maxCompressedSize(size_t inputSize) {
65   return LZ4::maxCompressedSize(inputSize);
66 }
67