history.go 1.9 KB

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