Coverage Report

Created: 2026-12-01 06:37

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/snappy/snappy.h
Line
Count
Source
1
// Copyright 2005 and onwards Google Inc.
2
//
3
// Redistribution and use in source and binary forms, with or without
4
// modification, are permitted provided that the following conditions are
5
// met:
6
//
7
//     * Redistributions of source code must retain the above copyright
8
// notice, this list of conditions and the following disclaimer.
9
//     * Redistributions in binary form must reproduce the above
10
// copyright notice, this list of conditions and the following disclaimer
11
// in the documentation and/or other materials provided with the
12
// distribution.
13
//     * Neither the name of Google Inc. nor the names of its
14
// contributors may be used to endorse or promote products derived from
15
// this software without specific prior written permission.
16
//
17
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
18
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
19
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
20
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
21
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
22
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
23
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
24
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
25
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
26
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
27
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28
//
29
// A light-weight compression algorithm.  It is designed for speed of
30
// compression and decompression, rather than for the utmost in space
31
// savings.
32
//
33
// For getting better compression ratios when you are compressing data
34
// with long repeated sequences or compressing data that is similar to
35
// other data, while still compressing fast, you might look at first
36
// using BMDiff and then compressing the output of BMDiff with
37
// Snappy.
38
39
#ifndef THIRD_PARTY_SNAPPY_SNAPPY_H__
40
#define THIRD_PARTY_SNAPPY_SNAPPY_H__
41
42
#include <stddef.h>
43
#include <stdint.h>
44
45
#include <string>
46
47
#include "snappy-stubs-public.h"
48
49
namespace snappy {
50
  class Source;
51
  class Sink;
52
53
namespace internal {
54
class WorkingMemory;
55
}  // end namespace internal
56
57
  struct CompressionOptions {
58
    // Compression level.
59
    // Level 1 is the fastest
60
    // Level 2 is a little slower but provides better compression. Level 2 is
61
    // **EXPERIMENTAL** for the time being. It might happen that we decide to
62
    // fall back to level 1 in the future.
63
    // Levels 3+ are currently not supported. We plan to support levels up to
64
    // 9 in the future.
65
    // If you played with other compression algorithms, level 1 is equivalent to
66
    // fast mode (level 1) of LZ4, level 2 is equivalent to LZ4's level 2 mode
67
    // and compresses somewhere around zstd:-3 and zstd:-2 but generally with
68
    // faster decompression speeds than snappy:1 and zstd:-3.
69
    int level = DefaultCompressionLevel();
70
71
0
      constexpr CompressionOptions() = default;
72
      constexpr explicit CompressionOptions(int compression_level)
73
5.32k
          : level(compression_level) {}
74
75
2.66k
    static constexpr int MinCompressionLevel() { return 1; }
76
7.98k
    static constexpr int MaxCompressionLevel() { return 2; }
77
0
    static constexpr int DefaultCompressionLevel() { return 1; }
78
  };
79
80
  // Scratch memory for compression, reusable across compressions. Callers that
81
  // compress frequently, or that need to avoid large heap allocations can
82
  // allocate a CompressionContext once and pass it to Compress()/RawCompress()
83
  // to reuse the working memory across calls.
84
  //
85
  // The context is sized for the largest block and works for inputs of any
86
  // size. A context may be used by any number of sequential compressions, but
87
  // must not be used from multiple threads concurrently. A moved-from context
88
  // may only be destroyed or assigned to.
89
  class CompressionContext {
90
   public:
91
    // Allocates the working memory on the heap.
92
    CompressionContext();
93
94
    // Constructs a context whose working memory is placed in the
95
    // caller-provided "workspace" instead of being heap-allocated; the
96
    // library performs no allocation at all.
97
    //
98
    // REQUIRES: "workspace" points to at least "workspace_size" bytes with
99
    // "workspace_size >= WorkspaceSize()", is suitably aligned for any
100
    // object type (as if returned by malloc), and outlives "*this".
101
    CompressionContext(void* workspace, size_t workspace_size);
102
103
    ~CompressionContext();
104
105
    CompressionContext(CompressionContext&& other) noexcept;
106
    CompressionContext& operator=(CompressionContext&& other) noexcept;
107
108
    CompressionContext(const CompressionContext&) = delete;
109
    CompressionContext& operator=(const CompressionContext&) = delete;
110
111
    // The workspace size required by the non-allocating constructor above.
112
    static size_t WorkspaceSize();
113
114
   private:
115
    friend size_t Compress(Source* reader, Sink* writer,
116
                           CompressionOptions options, CompressionContext* ctx);
117
118
    // Destroys the working memory as appropriate for how it was created
119
    // (delete if heap-allocated, in-place destruction if placement-constructed
120
    // in a caller-provided workspace).
121
    void Reset();
122
123
    internal::WorkingMemory* working_memory_;
124
    bool owns_working_memory_;
125
  };
126
127
  // ------------------------------------------------------------------------
128
  // Generic compression/decompression routines.
129
  // ------------------------------------------------------------------------
130
131
  // Compress the bytes read from "*reader" and append to "*writer". Return the
132
  // number of bytes written, or zero if "*reader" has 2^32 or more bytes.
133
  // First version is to preserve ABI.
134
  size_t Compress(Source* reader, Sink* writer);
135
  size_t Compress(Source* reader, Sink* writer,
136
                  CompressionOptions options);
137
138
  // Same as the above, but uses the working memory of "*ctx" instead of
139
  // allocating it internally. See CompressionContext.
140
  size_t Compress(Source* reader, Sink* writer, CompressionOptions options,
141
                  CompressionContext* ctx);
142
143
  // Find the uncompressed length of the given stream, as given by the header.
144
  // Note that the true length could deviate from this; the stream could e.g.
145
  // be truncated.
146
  //
147
  // Also note that this leaves "*source" in a state that is unsuitable for
148
  // further operations, such as RawUncompress(). You will need to rewind
149
  // or recreate the source yourself before attempting any further calls.
150
  bool GetUncompressedLength(Source* source, uint32_t* result);
151
152
  // ------------------------------------------------------------------------
153
  // Higher-level string based routines (should be sufficient for most users)
154
  // ------------------------------------------------------------------------
155
156
  // Sets "*compressed" to the compressed version of "input[0..input_length-1]".
157
  // Original contents of *compressed are lost. Returns zero and writes nothing
158
  // if "input_length" is 2^32 or more.
159
  //
160
  // REQUIRES: "input[]" is not an alias of "*compressed".
161
  // First version is to preserve ABI.
162
  size_t Compress(const char* input, size_t input_length,
163
                  std::string* compressed);
164
  size_t Compress(const char* input, size_t input_length,
165
                  std::string* compressed, CompressionOptions options);
166
167
  // Same as `Compress` above but taking an `iovec` array as input. Note that
168
  // this function preprocesses the inputs to compute the sum of
169
  // `iov[0..iov_cnt-1].iov_len` before reading. To avoid this, use
170
  // `RawCompressFromIOVec` below. Returns zero and writes nothing if that sum
171
  // is 2^32 or more.
172
  // First version is to preserve ABI.
173
  size_t CompressFromIOVec(const struct iovec* iov, size_t iov_cnt,
174
                           std::string* compressed);
175
  size_t CompressFromIOVec(const struct iovec* iov, size_t iov_cnt,
176
                           std::string* compressed,
177
                           CompressionOptions options);
178
179
  // Decompresses "compressed[0..compressed_length-1]" to "*uncompressed".
180
  // Original contents of "*uncompressed" are lost.
181
  //
182
  // REQUIRES: "compressed[]" is not an alias of "*uncompressed".
183
  //
184
  // returns false if the message is corrupted and could not be decompressed
185
  bool Uncompress(const char* compressed, size_t compressed_length,
186
                  std::string* uncompressed);
187
188
  // Decompresses "compressed" to "*uncompressed".
189
  //
190
  // returns false if the message is corrupted and could not be decompressed
191
  bool Uncompress(Source* compressed, Sink* uncompressed);
192
193
  // This routine uncompresses as much of the "compressed" as possible
194
  // into sink.  It returns the number of valid bytes added to sink
195
  // (extra invalid bytes may have been added due to errors; the caller
196
  // should ignore those). The emitted data typically has length
197
  // GetUncompressedLength(), but may be shorter if an error is
198
  // encountered.
199
  size_t UncompressAsMuchAsPossible(Source* compressed, Sink* uncompressed);
200
201
  // ------------------------------------------------------------------------
202
  // Lower-level character array based routines.  May be useful for
203
  // efficiency reasons in certain circumstances.
204
  // ------------------------------------------------------------------------
205
206
  // REQUIRES: "compressed" must point to an area of memory that is at
207
  // least "MaxCompressedLength(input_length)" bytes in length.
208
  //
209
  // Takes the data stored in "input[0..input_length]" and stores
210
  // it in the array pointed to by "compressed".
211
  //
212
  // "*compressed_length" is set to the length of the compressed output, or to
213
  // zero, with nothing written, if "input_length" is 2^32 or more.
214
  //
215
  // "*compressed_length" is set to the length of the compressed output.
216
  //
217
  // Example:
218
  //    char* output = new char[snappy::MaxCompressedLength(input_length)];
219
  //    size_t output_length;
220
  //    RawCompress(input, input_length, output, &output_length);
221
  //    ... Process(output, output_length) ...
222
  //    delete [] output;
223
  // First version is to preserve ABI.
224
  void RawCompress(const char* input, size_t input_length, char* compressed,
225
                   size_t* compressed_length);
226
  void RawCompress(const char* input, size_t input_length, char* compressed,
227
                   size_t* compressed_length, CompressionOptions options);
228
  // Same as the above, but uses the working memory of "*ctx" instead of
229
  // allocating it internally. See CompressionContext.
230
  void RawCompress(const char* input, size_t input_length, char* compressed,
231
                   size_t* compressed_length, CompressionOptions options,
232
                   CompressionContext* ctx);
233
234
  // Same as `RawCompress` above but taking an `iovec` array as input. Note that
235
  // `uncompressed_length` is the total number of bytes to be read from the
236
  // elements of `iov` (_not_ the number of elements in `iov`). Sets
237
  // "*compressed_length" to zero and writes nothing if `uncompressed_length`
238
  // is 2^32 or more.
239
  // First version is to preserve ABI.
240
  void RawCompressFromIOVec(const struct iovec* iov, size_t uncompressed_length,
241
                            char* compressed, size_t* compressed_length);
242
  void RawCompressFromIOVec(const struct iovec* iov, size_t uncompressed_length,
243
                            char* compressed, size_t* compressed_length,
244
                            CompressionOptions options);
245
246
  // Given data in "compressed[0..compressed_length-1]" generated by
247
  // calling the Snappy::Compress routine, this routine
248
  // stores the uncompressed data to
249
  //    uncompressed[0..GetUncompressedLength(compressed)-1]
250
  // returns false if the message is corrupted and could not be decrypted
251
  bool RawUncompress(const char* compressed, size_t compressed_length,
252
                     char* uncompressed);
253
254
  // Given data from the byte source 'compressed' generated by calling
255
  // the Snappy::Compress routine, this routine stores the uncompressed
256
  // data to
257
  //    uncompressed[0..GetUncompressedLength(compressed,compressed_length)-1]
258
  // returns false if the message is corrupted and could not be decrypted
259
  bool RawUncompress(Source* compressed, char* uncompressed);
260
261
  // Given data in "compressed[0..compressed_length-1]" generated by
262
  // calling the Snappy::Compress routine, this routine
263
  // stores the uncompressed data to the iovec "iov". The number of physical
264
  // buffers in "iov" is given by iov_cnt and their cumulative size
265
  // must be at least GetUncompressedLength(compressed). The individual buffers
266
  // in "iov" must not overlap with each other.
267
  //
268
  // returns false if the message is corrupted and could not be decrypted
269
  bool RawUncompressToIOVec(const char* compressed, size_t compressed_length,
270
                            const struct iovec* iov, size_t iov_cnt);
271
272
  // Given data from the byte source 'compressed' generated by calling
273
  // the Snappy::Compress routine, this routine stores the uncompressed
274
  // data to the iovec "iov". The number of physical
275
  // buffers in "iov" is given by iov_cnt and their cumulative size
276
  // must be at least GetUncompressedLength(compressed). The individual buffers
277
  // in "iov" must not overlap with each other.
278
  //
279
  // returns false if the message is corrupted and could not be decrypted
280
  bool RawUncompressToIOVec(Source* compressed, const struct iovec* iov,
281
                            size_t iov_cnt);
282
283
  // Returns the maximal size of the compressed representation of
284
  // input data that is "source_bytes" bytes in length;
285
  size_t MaxCompressedLength(size_t source_bytes);
286
287
  // REQUIRES: "compressed[]" was produced by RawCompress() or Compress()
288
  // Returns true and stores the length of the uncompressed data in
289
  // *result normally.  Returns false on parsing error.
290
  // This operation takes O(1) time.
291
  bool GetUncompressedLength(const char* compressed, size_t compressed_length,
292
                             size_t* result);
293
294
  // Returns true iff the contents of "compressed[]" can be uncompressed
295
  // successfully.  Does not return the uncompressed data.  Takes
296
  // time proportional to compressed_length, but is usually at least
297
  // a factor of four faster than actual decompression.
298
  bool IsValidCompressedBuffer(const char* compressed,
299
                               size_t compressed_length);
300
301
  // Returns true iff the contents of "compressed" can be uncompressed
302
  // successfully.  Does not return the uncompressed data.  Takes
303
  // time proportional to *compressed length, but is usually at least
304
  // a factor of four faster than actual decompression.
305
  // On success, consumes all of *compressed.  On failure, consumes an
306
  // unspecified prefix of *compressed.
307
  bool IsValidCompressed(Source* compressed);
308
309
  // The size of a compression block. Note that many parts of the compression
310
  // code assumes that kBlockSize <= 65536; in particular, the hash table
311
  // can only store 16-bit offsets, and EmitCopy() also assumes the offset
312
  // is 65535 bytes or less. Note also that if you change this, it will
313
  // affect the framing format (see framing_format.txt).
314
  //
315
  // Note that there might be older data around that is compressed with larger
316
  // block sizes, so the decompression code should not rely on the
317
  // non-existence of long backreferences.
318
  static constexpr int kBlockLog = 16;
319
  static constexpr size_t kBlockSize = 1 << kBlockLog;
320
321
  static constexpr int kMinHashTableBits = 8;
322
  static constexpr size_t kMinHashTableSize = 1 << kMinHashTableBits;
323
324
  static constexpr int kMaxHashTableBits = 15;
325
  static constexpr size_t kMaxHashTableSize = 1 << kMaxHashTableBits;
326
}  // end namespace snappy
327
328
#endif  // THIRD_PARTY_SNAPPY_SNAPPY_H__