1
// Copyright 2011 The Snappy-Go Authors. All rights reserved.
2
// Use of this source code is governed by a BSD-style
3
// license that can be found in the LICENSE file.
13
// Encode returns the encoded form of src. The returned slice may be a sub-
14
// slice of dst if dst was large enough to hold the entire encoded block.
15
// Otherwise, a newly allocated slice will be returned.
17
// The dst and src must not overlap. It is valid to pass a nil dst.
19
// Encode handles the Snappy block format, not the Snappy stream format.
20
func Encode(dst, src []byte) []byte {
21
if n := MaxEncodedLen(len(src)); n < 0 {
23
} else if len(dst) < n {
27
// The block starts with the varint-encoded length of the decompressed bytes.
28
d := binary.PutUvarint(dst, uint64(len(src)))
33
if len(p) > maxBlockSize {
34
p, src = p[:maxBlockSize], p[maxBlockSize:]
36
if len(p) < minNonLiteralBlockSize {
37
d += emitLiteral(dst[d:], p)
39
d += encodeBlock(dst[d:], p)
45
// inputMargin is the minimum number of extra input bytes to keep, inside
46
// encodeBlock's inner loop. On some architectures, this margin lets us
47
// implement a fast path for emitLiteral, where the copy of short (<= 16 byte)
48
// literals can be implemented as a single load to and store from a 16-byte
49
// register. That literal's actual length can be as short as 1 byte, so this
50
// can copy up to 15 bytes too much, but that's OK as subsequent iterations of
51
// the encoding loop will fix up the copy overrun, and this inputMargin ensures
52
// that we don't overrun the dst and src buffers.
53
const inputMargin = 16 - 1
55
// minNonLiteralBlockSize is the minimum size of the input to encodeBlock that
56
// could be encoded with a copy tag. This is the minimum with respect to the
57
// algorithm used by encodeBlock, not a minimum enforced by the file format.
59
// The encoded output must start with at least a 1 byte literal, as there are
60
// no previous bytes to copy. A minimal (1 byte) copy after that, generated
61
// from an emitCopy call in encodeBlock's main loop, would require at least
62
// another inputMargin bytes, for the reason above: we want any emitLiteral
63
// calls inside encodeBlock's main loop to use the fast path if possible, which
64
// requires being able to overrun by inputMargin bytes. Thus,
65
// minNonLiteralBlockSize equals 1 + 1 + inputMargin.
67
// The C++ code doesn't use this exact threshold, but it could, as discussed at
68
// https://groups.google.com/d/topic/snappy-compression/oGbhsdIJSJ8/discussion
69
// The difference between Go (2+inputMargin) and C++ (inputMargin) is purely an
70
// optimization. It should not affect the encoded form. This is tested by
71
// TestSameEncodingAsCppShortCopies.
72
const minNonLiteralBlockSize = 1 + 1 + inputMargin
74
// MaxEncodedLen returns the maximum length of a snappy block, given its
75
// uncompressed length.
77
// It will return a negative value if srcLen is too large to encode.
78
func MaxEncodedLen(srcLen int) int {
83
// Compressed data can be defined as:
84
// compressed := item* literal*
85
// item := literal* copy
87
// The trailing literal sequence has a space blowup of at most 62/60
88
// since a literal of length 60 needs one tag byte + one extra byte
89
// for length information.
91
// Item blowup is trickier to measure. Suppose the "copy" op copies
92
// 4 bytes of data. Because of a special check in the encoding code,
93
// we produce a 4-byte copy only if the offset is < 65536. Therefore
94
// the copy op takes 3 bytes to encode, and this type of item leads
95
// to at most the 62/60 blowup for representing literals.
97
// Suppose the "copy" op copies 5 bytes of data. If the offset is big
98
// enough, it will take 5 bytes to encode the copy op. Therefore the
99
// worst case here is a one-byte literal followed by a five-byte copy.
100
// That is, 6 bytes of input turn into 7 bytes of "compressed" data.
102
// This last factor dominates the blowup, so the final estimate is:
110
var errClosed = errors.New("snappy: Writer is closed")
112
// NewWriter returns a new Writer that compresses to w.
114
// The Writer returned does not buffer writes. There is no need to Flush or
115
// Close such a Writer.
117
// Deprecated: the Writer returned is not suitable for many small writes, only
118
// for few large writes. Use NewBufferedWriter instead, which is efficient
119
// regardless of the frequency and shape of the writes, and remember to Close
120
// that Writer when done.
121
func NewWriter(w io.Writer) *Writer {
124
obuf: make([]byte, obufLen),
128
// NewBufferedWriter returns a new Writer that compresses to w, using the
129
// framing format described at
130
// https://github.com/google/snappy/blob/master/framing_format.txt
132
// The Writer returned buffers writes. Users must call Close to guarantee all
133
// data has been forwarded to the underlying io.Writer. They may also call
134
// Flush zero or more times before calling Close.
135
func NewBufferedWriter(w io.Writer) *Writer {
138
ibuf: make([]byte, 0, maxBlockSize),
139
obuf: make([]byte, obufLen),
143
// Writer is an io.Writer that can write Snappy-compressed bytes.
145
// Writer handles the Snappy stream format, not the Snappy block format.
150
// ibuf is a buffer for the incoming (uncompressed) bytes.
152
// Its use is optional. For backwards compatibility, Writers created by the
153
// NewWriter function have ibuf == nil, do not buffer incoming bytes, and
154
// therefore do not need to be Flush'ed or Close'd.
157
// obuf is a buffer for the outgoing (compressed) bytes.
160
// wroteStreamHeader is whether we have written the stream header.
161
wroteStreamHeader bool
164
// Reset discards the writer's state and switches the Snappy writer to write to
165
// w. This permits reusing a Writer rather than allocating a new one.
166
func (w *Writer) Reset(writer io.Writer) {
172
w.wroteStreamHeader = false
175
// Write satisfies the io.Writer interface.
176
func (w *Writer) Write(p []byte) (nRet int, errRet error) {
178
// Do not buffer incoming bytes. This does not perform or compress well
179
// if the caller of Writer.Write writes many small slices. This
180
// behavior is therefore deprecated, but still supported for backwards
181
// compatibility with code that doesn't explicitly Flush or Close.
185
// The remainder of this method is based on bufio.Writer.Write from the
188
for len(p) > (cap(w.ibuf)-len(w.ibuf)) && w.err == nil {
190
if len(w.ibuf) == 0 {
191
// Large write, empty buffer.
192
// Write directly from p to avoid copy.
195
n = copy(w.ibuf[len(w.ibuf):cap(w.ibuf)], p)
196
w.ibuf = w.ibuf[:len(w.ibuf)+n]
205
n := copy(w.ibuf[len(w.ibuf):cap(w.ibuf)], p)
206
w.ibuf = w.ibuf[:len(w.ibuf)+n]
211
func (w *Writer) write(p []byte) (nRet int, errRet error) {
216
obufStart := len(magicChunk)
217
if !w.wroteStreamHeader {
218
w.wroteStreamHeader = true
219
copy(w.obuf, magicChunk)
223
var uncompressed []byte
224
if len(p) > maxBlockSize {
225
uncompressed, p = p[:maxBlockSize], p[maxBlockSize:]
227
uncompressed, p = p, nil
229
checksum := crc(uncompressed)
231
// Compress the buffer, discarding the result if the improvement
232
// isn't at least 12.5%.
233
compressed := Encode(w.obuf[obufHeaderLen:], uncompressed)
234
chunkType := uint8(chunkTypeCompressedData)
235
chunkLen := 4 + len(compressed)
236
obufEnd := obufHeaderLen + len(compressed)
237
if len(compressed) >= len(uncompressed)-len(uncompressed)/8 {
238
chunkType = chunkTypeUncompressedData
239
chunkLen = 4 + len(uncompressed)
240
obufEnd = obufHeaderLen
243
// Fill in the per-chunk header that comes before the body.
244
w.obuf[len(magicChunk)+0] = chunkType
245
w.obuf[len(magicChunk)+1] = uint8(chunkLen >> 0)
246
w.obuf[len(magicChunk)+2] = uint8(chunkLen >> 8)
247
w.obuf[len(magicChunk)+3] = uint8(chunkLen >> 16)
248
w.obuf[len(magicChunk)+4] = uint8(checksum >> 0)
249
w.obuf[len(magicChunk)+5] = uint8(checksum >> 8)
250
w.obuf[len(magicChunk)+6] = uint8(checksum >> 16)
251
w.obuf[len(magicChunk)+7] = uint8(checksum >> 24)
253
if _, err := w.w.Write(w.obuf[obufStart:obufEnd]); err != nil {
257
if chunkType == chunkTypeUncompressedData {
258
if _, err := w.w.Write(uncompressed); err != nil {
263
nRet += len(uncompressed)
268
// Flush flushes the Writer to its underlying io.Writer.
269
func (w *Writer) Flush() error {
273
if len(w.ibuf) == 0 {
281
// Close calls Flush and then closes the Writer.
282
func (w *Writer) Close() error {