Scott Baker | ed4efab | 2020-01-13 19:12:25 -0800 | [diff] [blame] | 1 | // Copyright 2019+ Klaus Post. All rights reserved. |
| 2 | // License information can be found in the LICENSE file. |
| 3 | // Based on work by Yann Collet, released under BSD License. |
| 4 | |
| 5 | package zstd |
| 6 | |
| 7 | import ( |
| 8 | "github.com/klauspost/compress/huff0" |
| 9 | ) |
| 10 | |
| 11 | // history contains the information transferred between blocks. |
| 12 | type history struct { |
| 13 | b []byte |
| 14 | huffTree *huff0.Scratch |
| 15 | recentOffsets [3]int |
| 16 | decoders sequenceDecs |
| 17 | windowSize int |
| 18 | maxSize int |
| 19 | error bool |
| 20 | } |
| 21 | |
| 22 | // reset will reset the history to initial state of a frame. |
| 23 | // The history must already have been initialized to the desired size. |
| 24 | func (h *history) reset() { |
| 25 | h.b = h.b[:0] |
| 26 | h.error = false |
| 27 | h.recentOffsets = [3]int{1, 4, 8} |
| 28 | if f := h.decoders.litLengths.fse; f != nil && !f.preDefined { |
| 29 | fseDecoderPool.Put(f) |
| 30 | } |
| 31 | if f := h.decoders.offsets.fse; f != nil && !f.preDefined { |
| 32 | fseDecoderPool.Put(f) |
| 33 | } |
| 34 | if f := h.decoders.matchLengths.fse; f != nil && !f.preDefined { |
| 35 | fseDecoderPool.Put(f) |
| 36 | } |
| 37 | h.decoders = sequenceDecs{} |
| 38 | if h.huffTree != nil { |
| 39 | huffDecoderPool.Put(h.huffTree) |
| 40 | } |
| 41 | h.huffTree = nil |
| 42 | //printf("history created: %+v (l: %d, c: %d)", *h, len(h.b), cap(h.b)) |
| 43 | } |
| 44 | |
| 45 | // append bytes to history. |
| 46 | // This function will make sure there is space for it, |
| 47 | // if the buffer has been allocated with enough extra space. |
| 48 | func (h *history) append(b []byte) { |
| 49 | if len(b) >= h.windowSize { |
| 50 | // Discard all history by simply overwriting |
| 51 | h.b = h.b[:h.windowSize] |
| 52 | copy(h.b, b[len(b)-h.windowSize:]) |
| 53 | return |
| 54 | } |
| 55 | |
| 56 | // If there is space, append it. |
| 57 | if len(b) < cap(h.b)-len(h.b) { |
| 58 | h.b = append(h.b, b...) |
| 59 | return |
| 60 | } |
| 61 | |
| 62 | // Move data down so we only have window size left. |
| 63 | // We know we have less than window size in b at this point. |
| 64 | discard := len(b) + len(h.b) - h.windowSize |
| 65 | copy(h.b, h.b[discard:]) |
| 66 | h.b = h.b[:h.windowSize] |
| 67 | copy(h.b[h.windowSize-len(b):], b) |
| 68 | } |
| 69 | |
| 70 | // append bytes to history without ever discarding anything. |
| 71 | func (h *history) appendKeep(b []byte) { |
| 72 | h.b = append(h.b, b...) |
| 73 | } |