Debian Codegraph @

s2/dict.go

raw
1 // Copyright (c) 2022+ Klaus Post. 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
5 package s2
6
7 import (
8 "bytes"
9 "encoding/binary"
10 "sync"
11 )
12
13 const (
14 // MinDictSize is the minimum dictionary size when repeat has been read.
15 MinDictSize = 16
16
17 // MaxDictSize is the maximum dictionary size when repeat has been read.
18 MaxDictSize = 65536
19
20 // MaxDictSrcOffset is the maximum offset where a dictionary entry can start.
21 MaxDictSrcOffset = 65535
22 )
23
24 // Dict contains a dictionary that can be used for encoding and decoding s2
25 type Dict struct {
26 dict []byte
27 repeat int // Repeat as index of dict
28
29 fast, better, best sync.Once
30 fastTable *[1 << 14]uint16
31
32 betterTableShort *[1 << 14]uint16
33 betterTableLong *[1 << 17]uint16
34
35 bestTableShort *[1 << 16]uint32
36 bestTableLong *[1 << 19]uint32
37 }
38
39 // NewDict will read a dictionary.
40 // It will return nil if the dictionary is invalid.
41 func NewDict(dict []byte) *Dict {
42 if len(dict) == 0 {
43 return nil
44 }
45 var d Dict
46 // Repeat is the first value of the dict
47 r, n := binary.Uvarint(dict)
48 if n <= 0 {
49 return nil
50 }
51 dict = dict[n:]
52 d.dict = dict
53 if cap(d.dict) < len(d.dict)+16 {
54 d.dict = append(make([]byte, 0, len(d.dict)+16), d.dict...)
55 }
56 if len(dict) < MinDictSize || len(dict) > MaxDictSize {
57 return nil
58 }
59 // Compare as uint64: int(r) would wrap negative for r > MaxInt64,
60 // slipping past the bounds check and causing an OOB read in encode.
61 if r > uint64(len(dict)) {
62 return nil
63 }
64 d.repeat = int(r)
65 return &d
66 }
67
68 // Bytes will return a serialized version of the dictionary.
69 // The output can be sent to NewDict.
70 func (d *Dict) Bytes() []byte {
71 dst := make([]byte, binary.MaxVarintLen16+len(d.dict))
72 return append(dst[:binary.PutUvarint(dst, uint64(d.repeat))], d.dict...)
73 }
74
75 // MakeDict will create a dictionary.
76 // 'data' must be at least MinDictSize.
77 // If data is longer than MaxDictSize only the last MaxDictSize bytes will be used.
78 // If searchStart is set the start repeat value will be set to the last
79 // match of this content.
80 // If no matches are found, it will attempt to find shorter matches.
81 // This content should match the typical start of a block.
82 // If at least 4 bytes cannot be matched, repeat is set to start of block.
83 func MakeDict(data []byte, searchStart []byte) *Dict {
84 if len(data) == 0 {
85 return nil
86 }
87 if len(data) > MaxDictSize {
88 data = data[len(data)-MaxDictSize:]
89 }
90 var d Dict
91 dict := data
92 d.dict = dict
93 if cap(d.dict) < len(d.dict)+16 {
94 d.dict = append(make([]byte, 0, len(d.dict)+16), d.dict...)
95 }
96 if len(dict) < MinDictSize {
97 return nil
98 }
99
100 // Find the longest match possible, last entry if multiple.
101 for s := len(searchStart); s > 4; s-- {
102 if idx := bytes.LastIndex(data, searchStart[:s]); idx >= 0 && idx <= len(data)-8 {
103 d.repeat = idx
104 break
105 }
106 }
107
108 return &d
109 }
110
111 // MakeDictManual will create a dictionary.
112 // 'data' must be at least MinDictSize and less than or equal to MaxDictSize.
113 // A manual first repeat index into data must be provided.
114 // It must be less than len(data)-8.
115 func MakeDictManual(data []byte, firstIdx uint16) *Dict {
116 if len(data) < MinDictSize || int(firstIdx) >= len(data)-8 || len(data) > MaxDictSize {
117 return nil
118 }
119 var d Dict
120 dict := data
121 d.dict = dict
122 if cap(d.dict) < len(d.dict)+16 {
123 d.dict = append(make([]byte, 0, len(d.dict)+16), d.dict...)
124 }
125
126 d.repeat = int(firstIdx)
127 return &d
128 }
129
130 // Encode returns the encoded form of src. The returned slice may be a sub-
131 // slice of dst if dst was large enough to hold the entire encoded block.
132 // Otherwise, a newly allocated slice will be returned.
133 //
134 // The dst and src must not overlap. It is valid to pass a nil dst.
135 //
136 // The blocks will require the same amount of memory to decode as encoding,
137 // and does not make for concurrent decoding.
138 // Also note that blocks do not contain CRC information, so corruption may be undetected.
139 //
140 // If you need to encode larger amounts of data, consider using
141 // the streaming interface which gives all of these features.
142 func (d *Dict) Encode(dst, src []byte) []byte {
143 if n := MaxEncodedLen(len(src)); n < 0 {
144 panic(ErrTooLarge)
145 } else if cap(dst) < n {
146 dst = make([]byte, n)
147 } else {
148 dst = dst[:n]
149 }
150
151 // The block starts with the varint-encoded length of the decompressed bytes.
152 dstP := binary.PutUvarint(dst, uint64(len(src)))
153
154 if len(src) == 0 {
155 return dst[:dstP]
156 }
157 if len(src) < minNonLiteralBlockSize {
158 dstP += emitLiteral(dst[dstP:], src)
159 return dst[:dstP]
160 }
161 n := encodeBlockDictGo(dst[dstP:], src, d)
162 if n > 0 {
163 dstP += n
164 return dst[:dstP]
165 }
166 // Not compressible
167 dstP += emitLiteral(dst[dstP:], src)
168 return dst[:dstP]
169 }
170
171 // EncodeBetter returns the encoded form of src. The returned slice may be a sub-
172 // slice of dst if dst was large enough to hold the entire encoded block.
173 // Otherwise, a newly allocated slice will be returned.
174 //
175 // EncodeBetter compresses better than Encode but typically with a
176 // 10-40% speed decrease on both compression and decompression.
177 //
178 // The dst and src must not overlap. It is valid to pass a nil dst.
179 //
180 // The blocks will require the same amount of memory to decode as encoding,
181 // and does not make for concurrent decoding.
182 // Also note that blocks do not contain CRC information, so corruption may be undetected.
183 //
184 // If you need to encode larger amounts of data, consider using
185 // the streaming interface which gives all of these features.
186 func (d *Dict) EncodeBetter(dst, src []byte) []byte {
187 if n := MaxEncodedLen(len(src)); n < 0 {
188 panic(ErrTooLarge)
189 } else if len(dst) < n {
190 dst = make([]byte, n)
191 }
192
193 // The block starts with the varint-encoded length of the decompressed bytes.
194 dstP := binary.PutUvarint(dst, uint64(len(src)))
195
196 if len(src) == 0 {
197 return dst[:dstP]
198 }
199 if len(src) < minNonLiteralBlockSize {
200 dstP += emitLiteral(dst[dstP:], src)
201 return dst[:dstP]
202 }
203 n := encodeBlockBetterDict(dst[dstP:], src, d)
204 if n > 0 {
205 dstP += n
206 return dst[:dstP]
207 }
208 // Not compressible
209 dstP += emitLiteral(dst[dstP:], src)
210 return dst[:dstP]
211 }
212
213 // EncodeBest returns the encoded form of src. The returned slice may be a sub-
214 // slice of dst if dst was large enough to hold the entire encoded block.
215 // Otherwise, a newly allocated slice will be returned.
216 //
217 // EncodeBest compresses as good as reasonably possible but with a
218 // big speed decrease.
219 //
220 // The dst and src must not overlap. It is valid to pass a nil dst.
221 //
222 // The blocks will require the same amount of memory to decode as encoding,
223 // and does not make for concurrent decoding.
224 // Also note that blocks do not contain CRC information, so corruption may be undetected.
225 //
226 // If you need to encode larger amounts of data, consider using
227 // the streaming interface which gives all of these features.
228 func (d *Dict) EncodeBest(dst, src []byte) []byte {
229 if n := MaxEncodedLen(len(src)); n < 0 {
230 panic(ErrTooLarge)
231 } else if len(dst) < n {
232 dst = make([]byte, n)
233 }
234
235 // The block starts with the varint-encoded length of the decompressed bytes.
236 dstP := binary.PutUvarint(dst, uint64(len(src)))
237
238 if len(src) == 0 {
239 return dst[:dstP]
240 }
241 if len(src) < minNonLiteralBlockSize {
242 dstP += emitLiteral(dst[dstP:], src)
243 return dst[:dstP]
244 }
245 n := encodeBlockBest(dst[dstP:], src, d)
246 if n > 0 {
247 dstP += n
248 return dst[:dstP]
249 }
250 // Not compressible
251 dstP += emitLiteral(dst[dstP:], src)
252 return dst[:dstP]
253 }
254
255 // Decode returns the decoded form of src. The returned slice may be a sub-
256 // slice of dst if dst was large enough to hold the entire decoded block.
257 // Otherwise, a newly allocated slice will be returned.
258 //
259 // The dst and src must not overlap. It is valid to pass a nil dst.
260 func (d *Dict) Decode(dst, src []byte) ([]byte, error) {
261 dLen, s, err := decodedLen(src)
262 if err != nil {
263 return nil, err
264 }
265 if dLen <= cap(dst) {
266 dst = dst[:dLen]
267 } else {
268 dst = make([]byte, dLen)
269 }
270 if s2DecodeDict(dst, src[s:], d) != 0 {
271 return nil, ErrCorrupt
272 }
273 return dst, nil
274 }
275
276 func (d *Dict) initFast() {
277 d.fast.Do(func() {
278 const (
279 tableBits = 14
280 maxTableSize = 1 << tableBits
281 )
282
283 var table [maxTableSize]uint16
284 // We stop so any entry of length 8 can always be read.
285 for i := 0; i < len(d.dict)-8-2; i += 3 {
286 x0 := load64(d.dict, i)
287 h0 := hash6(x0, tableBits)
288 h1 := hash6(x0>>8, tableBits)
289 h2 := hash6(x0>>16, tableBits)
290 table[h0] = uint16(i)
291 table[h1] = uint16(i + 1)
292 table[h2] = uint16(i + 2)
293 }
294 d.fastTable = &table
295 })
296 }
297
298 func (d *Dict) initBetter() {
299 d.better.Do(func() {
300 const (
301 // Long hash matches.
302 lTableBits = 17
303 maxLTableSize = 1 << lTableBits
304
305 // Short hash matches.
306 sTableBits = 14
307 maxSTableSize = 1 << sTableBits
308 )
309
310 var lTable [maxLTableSize]uint16
311 var sTable [maxSTableSize]uint16
312
313 // We stop so any entry of length 8 can always be read.
314 for i := 0; i < len(d.dict)-8; i++ {
315 cv := load64(d.dict, i)
316 lTable[hash7(cv, lTableBits)] = uint16(i)
317 sTable[hash4(cv, sTableBits)] = uint16(i)
318 }
319 d.betterTableShort = &sTable
320 d.betterTableLong = &lTable
321 })
322 }
323
324 func (d *Dict) initBest() {
325 d.best.Do(func() {
326 const (
327 // Long hash matches.
328 lTableBits = 19
329 maxLTableSize = 1 << lTableBits
330
331 // Short hash matches.
332 sTableBits = 16
333 maxSTableSize = 1 << sTableBits
334 )
335
336 var lTable [maxLTableSize]uint32
337 var sTable [maxSTableSize]uint32
338
339 // We stop so any entry of length 8 can always be read.
340 for i := 0; i < len(d.dict)-8; i++ {
341 cv := load64(d.dict, i)
342 hashL := hash8(cv, lTableBits)
343 hashS := hash4(cv, sTableBits)
344 candidateL := lTable[hashL]
345 candidateS := sTable[hashS]
346 lTable[hashL] = uint32(i) | candidateL<<16
347 sTable[hashS] = uint32(i) | candidateS<<16
348 }
349 d.bestTableShort = &sTable
350 d.bestTableLong = &lTable
351 })
352 }