9
tablelogAbsoluteMax = 15
12
// Decompress a block of data.
13
// You can provide a scratch buffer to avoid allocations.
14
// If nil is provided a temporary one will be allocated.
15
// It is possible, but by no way guaranteed that corrupt data will
17
// It is up to the caller to verify integrity of the returned data.
18
// Use a predefined Scrach to set maximum acceptable output size.
19
func Decompress(b []byte, s *Scratch) ([]byte, error) {
20
s, err := s.prepare(b)
41
// readNCount will read the symbol distribution so decoding tables can be constructed.
42
func (s *Scratch) readNCount() error {
50
return errors.New("input too small")
52
bitStream := b.Uint32()
53
nbBits := uint((bitStream & 0xF) + minTablelog) // extract tableLog
54
if nbBits > tablelogAbsoluteMax {
55
return errors.New("tableLog too large")
60
s.actualTableLog = uint8(nbBits)
61
remaining := int32((1 << nbBits) + 1)
62
threshold := int32(1 << nbBits)
69
for (bitStream & 0xFFFF) == 0xFFFF {
73
bitStream = b.Uint32() >> bitCount
79
for (bitStream & 3) == 3 {
84
n0 += uint16(bitStream & 3)
86
if n0 > maxSymbolValue {
87
return errors.New("maxSymbolValue too small")
90
s.norm[charnum&0xff] = 0
94
if b.off <= iend-7 || b.off+int(bitCount>>3) <= iend-4 {
95
b.advance(bitCount >> 3)
97
bitStream = b.Uint32() >> bitCount
103
max := (2*(threshold) - 1) - (remaining)
106
if (int32(bitStream) & (threshold - 1)) < max {
107
count = int32(bitStream) & (threshold - 1)
108
bitCount += nbBits - 1
110
count = int32(bitStream) & (2*threshold - 1)
111
if count >= threshold {
117
count-- // extra accuracy
126
s.norm[charnum&0xff] = int16(count)
128
previous0 = count == 0
129
for remaining < threshold {
133
if b.off <= iend-7 || b.off+int(bitCount>>3) <= iend-4 {
134
b.advance(bitCount >> 3)
137
bitCount -= (uint)(8 * (len(b.b) - 4 - b.off))
140
bitStream = b.Uint32() >> (bitCount & 31)
142
s.symbolLen = charnum
144
if s.symbolLen <= 1 {
145
return fmt.Errorf("symbolLen (%d) too small", s.symbolLen)
147
if s.symbolLen > maxSymbolValue+1 {
148
return fmt.Errorf("symbolLen (%d) too big", s.symbolLen)
151
return fmt.Errorf("corruption detected (remaining %d != 1)", remaining)
154
return fmt.Errorf("corruption detected (bitCount %d > 32)", bitCount)
156
if gotTotal != 1<<s.actualTableLog {
157
return fmt.Errorf("corruption detected (total %d != %d)", gotTotal, 1<<s.actualTableLog)
159
b.advance((bitCount + 7) >> 3)
163
// decSymbol contains information about a state entry,
164
// Including the state offset base, the output symbol and
165
// the number of bits to read for the low part of the destination state.
166
type decSymbol struct {
172
// allocDtable will allocate decoding tables if they are not big enough.
173
func (s *Scratch) allocDtable() {
174
tableSize := 1 << s.actualTableLog
175
if cap(s.decTable) < tableSize {
176
s.decTable = make([]decSymbol, tableSize)
178
s.decTable = s.decTable[:tableSize]
180
if cap(s.ct.tableSymbol) < 256 {
181
s.ct.tableSymbol = make([]byte, 256)
183
s.ct.tableSymbol = s.ct.tableSymbol[:256]
185
if cap(s.ct.stateTable) < 256 {
186
s.ct.stateTable = make([]uint16, 256)
188
s.ct.stateTable = s.ct.stateTable[:256]
191
// buildDtable will build the decoding table.
192
func (s *Scratch) buildDtable() error {
193
tableSize := uint32(1 << s.actualTableLog)
194
highThreshold := tableSize - 1
196
symbolNext := s.ct.stateTable[:256]
198
// Init, lay down lowprob symbols
201
largeLimit := int16(1 << (s.actualTableLog - 1))
202
for i, v := range s.norm[:s.symbolLen] {
204
s.decTable[highThreshold].symbol = uint8(i)
211
symbolNext[i] = uint16(v)
217
tableMask := tableSize - 1
218
step := tableStep(tableSize)
219
position := uint32(0)
220
for ss, v := range s.norm[:s.symbolLen] {
221
for i := 0; i < int(v); i++ {
222
s.decTable[position].symbol = uint8(ss)
223
position = (position + step) & tableMask
224
for position > highThreshold {
226
position = (position + step) & tableMask
231
// position must reach all cells once, otherwise normalizedCounter is incorrect
232
return errors.New("corrupted input (position != 0)")
236
// Build Decoding table
238
tableSize := uint16(1 << s.actualTableLog)
239
for u, v := range s.decTable {
241
nextState := symbolNext[symbol]
242
symbolNext[symbol] = nextState + 1
243
nBits := s.actualTableLog - byte(highBits(uint32(nextState)))
244
s.decTable[u].nbBits = nBits
245
newState := (nextState << nBits) - tableSize
246
if newState >= tableSize {
247
return fmt.Errorf("newState (%d) outside table size (%d)", newState, tableSize)
249
if newState == uint16(u) && nBits == 0 {
250
// Seems weird that this is possible with nbits > 0.
251
return fmt.Errorf("newState (%d) == oldState (%d) and no bits", newState, u)
253
s.decTable[u].newState = newState
259
// decompress will decompress the bitstream.
260
// If the buffer is over-read an error is returned.
261
func (s *Scratch) decompress() error {
263
br.init(s.br.unread())
266
// Initialize and decode first state and symbol.
267
s1.init(br, s.decTable, s.actualTableLog)
268
s2.init(br, s.decTable, s.actualTableLog)
270
// Use temp table to avoid bound checks/append penalty.
271
var tmp = s.ct.tableSymbol[:256]
278
tmp[off+0] = s1.nextFast()
279
tmp[off+1] = s2.nextFast()
281
tmp[off+2] = s1.nextFast()
282
tmp[off+3] = s2.nextFast()
284
// When off is 0, we have overflowed and should write.
286
s.Out = append(s.Out, tmp...)
287
if len(s.Out) >= s.DecompressLimit {
288
return fmt.Errorf("output size (%d) > DecompressLimit (%d)", len(s.Out), s.DecompressLimit)
295
tmp[off+0] = s1.next()
296
tmp[off+1] = s2.next()
298
tmp[off+2] = s1.next()
299
tmp[off+3] = s2.next()
302
s.Out = append(s.Out, tmp...)
303
// When off is 0, we have overflowed and should write.
304
if len(s.Out) >= s.DecompressLimit {
305
return fmt.Errorf("output size (%d) > DecompressLimit (%d)", len(s.Out), s.DecompressLimit)
310
s.Out = append(s.Out, tmp[:off]...)
312
// Final bits, a bit more expensive check
315
s.Out = append(s.Out, s1.final(), s2.final())
319
s.Out = append(s.Out, s1.next())
321
s.Out = append(s.Out, s2.final(), s1.final())
324
s.Out = append(s.Out, s2.next())
325
if len(s.Out) >= s.DecompressLimit {
326
return fmt.Errorf("output size (%d) > DecompressLimit (%d)", len(s.Out), s.DecompressLimit)
332
// decoder keeps track of the current state and updates it from the bitstream.
339
// init will initialize the decoder and read the first state from the stream.
340
func (d *decoder) init(in *bitReader, dt []decSymbol, tableLog uint8) {
343
d.state = in.getBits(tableLog)
346
// next returns the next symbol and sets the next state.
347
// At least tablelog bits must be available in the bit reader.
348
func (d *decoder) next() uint8 {
350
lowBits := d.br.getBits(n.nbBits)
351
d.state = n.newState + lowBits
355
// finished returns true if all bits have been read from the bitstream
356
// and the next state would require reading bits from the input.
357
func (d *decoder) finished() bool {
358
return d.br.finished() && d.dt[d.state].nbBits > 0
361
// final returns the current state symbol without decoding the next.
362
func (d *decoder) final() uint8 {
363
return d.dt[d.state].symbol
366
// nextFast returns the next symbol and sets the next state.
367
// This can only be used if no symbols are 0 bits.
368
// At least tablelog bits must be available in the bit reader.
369
func (d *decoder) nextFast() uint8 {
371
lowBits := d.br.getBitsFast(n.nbBits)
372
d.state = n.newState + lowBits