blob: 511bba65db8f6f1161d692d233e9f7f9cbc33794 [file] [log] [blame]
kesavandc71914f2022-03-25 11:19:03 +05301// Copyright 2016 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.
4
5package snapref
6
7func load32(b []byte, i int) uint32 {
8 b = b[i : i+4 : len(b)] // Help the compiler eliminate bounds checks on the next line.
9 return uint32(b[0]) | uint32(b[1])<<8 | uint32(b[2])<<16 | uint32(b[3])<<24
10}
11
12func load64(b []byte, i int) uint64 {
13 b = b[i : i+8 : len(b)] // Help the compiler eliminate bounds checks on the next line.
14 return uint64(b[0]) | uint64(b[1])<<8 | uint64(b[2])<<16 | uint64(b[3])<<24 |
15 uint64(b[4])<<32 | uint64(b[5])<<40 | uint64(b[6])<<48 | uint64(b[7])<<56
16}
17
18// emitLiteral writes a literal chunk and returns the number of bytes written.
19//
20// It assumes that:
21// dst is long enough to hold the encoded bytes
22// 1 <= len(lit) && len(lit) <= 65536
23func emitLiteral(dst, lit []byte) int {
24 i, n := 0, uint(len(lit)-1)
25 switch {
26 case n < 60:
27 dst[0] = uint8(n)<<2 | tagLiteral
28 i = 1
29 case n < 1<<8:
30 dst[0] = 60<<2 | tagLiteral
31 dst[1] = uint8(n)
32 i = 2
33 default:
34 dst[0] = 61<<2 | tagLiteral
35 dst[1] = uint8(n)
36 dst[2] = uint8(n >> 8)
37 i = 3
38 }
39 return i + copy(dst[i:], lit)
40}
41
42// emitCopy writes a copy chunk and returns the number of bytes written.
43//
44// It assumes that:
45// dst is long enough to hold the encoded bytes
46// 1 <= offset && offset <= 65535
47// 4 <= length && length <= 65535
48func emitCopy(dst []byte, offset, length int) int {
49 i := 0
50 // The maximum length for a single tagCopy1 or tagCopy2 op is 64 bytes. The
51 // threshold for this loop is a little higher (at 68 = 64 + 4), and the
52 // length emitted down below is is a little lower (at 60 = 64 - 4), because
53 // it's shorter to encode a length 67 copy as a length 60 tagCopy2 followed
54 // by a length 7 tagCopy1 (which encodes as 3+2 bytes) than to encode it as
55 // a length 64 tagCopy2 followed by a length 3 tagCopy2 (which encodes as
56 // 3+3 bytes). The magic 4 in the 64±4 is because the minimum length for a
57 // tagCopy1 op is 4 bytes, which is why a length 3 copy has to be an
58 // encodes-as-3-bytes tagCopy2 instead of an encodes-as-2-bytes tagCopy1.
59 for length >= 68 {
60 // Emit a length 64 copy, encoded as 3 bytes.
61 dst[i+0] = 63<<2 | tagCopy2
62 dst[i+1] = uint8(offset)
63 dst[i+2] = uint8(offset >> 8)
64 i += 3
65 length -= 64
66 }
67 if length > 64 {
68 // Emit a length 60 copy, encoded as 3 bytes.
69 dst[i+0] = 59<<2 | tagCopy2
70 dst[i+1] = uint8(offset)
71 dst[i+2] = uint8(offset >> 8)
72 i += 3
73 length -= 60
74 }
75 if length >= 12 || offset >= 2048 {
76 // Emit the remaining copy, encoded as 3 bytes.
77 dst[i+0] = uint8(length-1)<<2 | tagCopy2
78 dst[i+1] = uint8(offset)
79 dst[i+2] = uint8(offset >> 8)
80 return i + 3
81 }
82 // Emit the remaining copy, encoded as 2 bytes.
83 dst[i+0] = uint8(offset>>8)<<5 | uint8(length-4)<<2 | tagCopy1
84 dst[i+1] = uint8(offset)
85 return i + 2
86}
87
88// extendMatch returns the largest k such that k <= len(src) and that
89// src[i:i+k-j] and src[j:k] have the same contents.
90//
91// It assumes that:
92// 0 <= i && i < j && j <= len(src)
93func extendMatch(src []byte, i, j int) int {
94 for ; j < len(src) && src[i] == src[j]; i, j = i+1, j+1 {
95 }
96 return j
97}
98
99func hash(u, shift uint32) uint32 {
100 return (u * 0x1e35a7bd) >> shift
101}
102
103// encodeBlock encodes a non-empty src to a guaranteed-large-enough dst. It
104// assumes that the varint-encoded length of the decompressed bytes has already
105// been written.
106//
107// It also assumes that:
108// len(dst) >= MaxEncodedLen(len(src)) &&
109// minNonLiteralBlockSize <= len(src) && len(src) <= maxBlockSize
110func encodeBlock(dst, src []byte) (d int) {
111 // Initialize the hash table. Its size ranges from 1<<8 to 1<<14 inclusive.
112 // The table element type is uint16, as s < sLimit and sLimit < len(src)
113 // and len(src) <= maxBlockSize and maxBlockSize == 65536.
114 const (
115 maxTableSize = 1 << 14
116 // tableMask is redundant, but helps the compiler eliminate bounds
117 // checks.
118 tableMask = maxTableSize - 1
119 )
120 shift := uint32(32 - 8)
121 for tableSize := 1 << 8; tableSize < maxTableSize && tableSize < len(src); tableSize *= 2 {
122 shift--
123 }
124 // In Go, all array elements are zero-initialized, so there is no advantage
125 // to a smaller tableSize per se. However, it matches the C++ algorithm,
126 // and in the asm versions of this code, we can get away with zeroing only
127 // the first tableSize elements.
128 var table [maxTableSize]uint16
129
130 // sLimit is when to stop looking for offset/length copies. The inputMargin
131 // lets us use a fast path for emitLiteral in the main loop, while we are
132 // looking for copies.
133 sLimit := len(src) - inputMargin
134
135 // nextEmit is where in src the next emitLiteral should start from.
136 nextEmit := 0
137
138 // The encoded form must start with a literal, as there are no previous
139 // bytes to copy, so we start looking for hash matches at s == 1.
140 s := 1
141 nextHash := hash(load32(src, s), shift)
142
143 for {
144 // Copied from the C++ snappy implementation:
145 //
146 // Heuristic match skipping: If 32 bytes are scanned with no matches
147 // found, start looking only at every other byte. If 32 more bytes are
148 // scanned (or skipped), look at every third byte, etc.. When a match
149 // is found, immediately go back to looking at every byte. This is a
150 // small loss (~5% performance, ~0.1% density) for compressible data
151 // due to more bookkeeping, but for non-compressible data (such as
152 // JPEG) it's a huge win since the compressor quickly "realizes" the
153 // data is incompressible and doesn't bother looking for matches
154 // everywhere.
155 //
156 // The "skip" variable keeps track of how many bytes there are since
157 // the last match; dividing it by 32 (ie. right-shifting by five) gives
158 // the number of bytes to move ahead for each iteration.
159 skip := 32
160
161 nextS := s
162 candidate := 0
163 for {
164 s = nextS
165 bytesBetweenHashLookups := skip >> 5
166 nextS = s + bytesBetweenHashLookups
167 skip += bytesBetweenHashLookups
168 if nextS > sLimit {
169 goto emitRemainder
170 }
171 candidate = int(table[nextHash&tableMask])
172 table[nextHash&tableMask] = uint16(s)
173 nextHash = hash(load32(src, nextS), shift)
174 if load32(src, s) == load32(src, candidate) {
175 break
176 }
177 }
178
179 // A 4-byte match has been found. We'll later see if more than 4 bytes
180 // match. But, prior to the match, src[nextEmit:s] are unmatched. Emit
181 // them as literal bytes.
182 d += emitLiteral(dst[d:], src[nextEmit:s])
183
184 // Call emitCopy, and then see if another emitCopy could be our next
185 // move. Repeat until we find no match for the input immediately after
186 // what was consumed by the last emitCopy call.
187 //
188 // If we exit this loop normally then we need to call emitLiteral next,
189 // though we don't yet know how big the literal will be. We handle that
190 // by proceeding to the next iteration of the main loop. We also can
191 // exit this loop via goto if we get close to exhausting the input.
192 for {
193 // Invariant: we have a 4-byte match at s, and no need to emit any
194 // literal bytes prior to s.
195 base := s
196
197 // Extend the 4-byte match as long as possible.
198 //
199 // This is an inlined version of:
200 // s = extendMatch(src, candidate+4, s+4)
201 s += 4
202 for i := candidate + 4; s < len(src) && src[i] == src[s]; i, s = i+1, s+1 {
203 }
204
205 d += emitCopy(dst[d:], base-candidate, s-base)
206 nextEmit = s
207 if s >= sLimit {
208 goto emitRemainder
209 }
210
211 // We could immediately start working at s now, but to improve
212 // compression we first update the hash table at s-1 and at s. If
213 // another emitCopy is not our next move, also calculate nextHash
214 // at s+1. At least on GOARCH=amd64, these three hash calculations
215 // are faster as one load64 call (with some shifts) instead of
216 // three load32 calls.
217 x := load64(src, s-1)
218 prevHash := hash(uint32(x>>0), shift)
219 table[prevHash&tableMask] = uint16(s - 1)
220 currHash := hash(uint32(x>>8), shift)
221 candidate = int(table[currHash&tableMask])
222 table[currHash&tableMask] = uint16(s)
223 if uint32(x>>8) != load32(src, candidate) {
224 nextHash = hash(uint32(x>>16), shift)
225 s++
226 break
227 }
228 }
229 }
230
231emitRemainder:
232 if nextEmit < len(src) {
233 d += emitLiteral(dst[d:], src[nextEmit:])
234 }
235 return d
236}