blocks.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. // Package lz4block provides LZ4 BlockSize types and pools of buffers.
  2. package lz4block
  3. import "sync"
  4. const (
  5. Block64Kb uint32 = 1 << (16 + iota*2)
  6. Block256Kb
  7. Block1Mb
  8. Block4Mb
  9. Block8Mb = 2 * Block4Mb
  10. )
  11. var (
  12. BlockPool64K = sync.Pool{New: func() interface{} { return make([]byte, Block64Kb) }}
  13. BlockPool256K = sync.Pool{New: func() interface{} { return make([]byte, Block256Kb) }}
  14. BlockPool1M = sync.Pool{New: func() interface{} { return make([]byte, Block1Mb) }}
  15. BlockPool4M = sync.Pool{New: func() interface{} { return make([]byte, Block4Mb) }}
  16. BlockPool8M = sync.Pool{New: func() interface{} { return make([]byte, Block8Mb) }}
  17. )
  18. func Index(b uint32) BlockSizeIndex {
  19. switch b {
  20. case Block64Kb:
  21. return 4
  22. case Block256Kb:
  23. return 5
  24. case Block1Mb:
  25. return 6
  26. case Block4Mb:
  27. return 7
  28. case Block8Mb: // only valid in legacy mode
  29. return 3
  30. }
  31. return 0
  32. }
  33. func IsValid(b uint32) bool {
  34. return Index(b) > 0
  35. }
  36. type BlockSizeIndex uint8
  37. func (b BlockSizeIndex) IsValid() bool {
  38. switch b {
  39. case 4, 5, 6, 7:
  40. return true
  41. }
  42. return false
  43. }
  44. func (b BlockSizeIndex) Get() []byte {
  45. var buf interface{}
  46. switch b {
  47. case 4:
  48. buf = BlockPool64K.Get()
  49. case 5:
  50. buf = BlockPool256K.Get()
  51. case 6:
  52. buf = BlockPool1M.Get()
  53. case 7:
  54. buf = BlockPool4M.Get()
  55. case 3:
  56. buf = BlockPool8M.Get()
  57. }
  58. return buf.([]byte)
  59. }
  60. func Put(buf []byte) {
  61. // Safeguard: do not allow invalid buffers.
  62. switch c := cap(buf); uint32(c) {
  63. case Block64Kb:
  64. BlockPool64K.Put(buf[:c])
  65. case Block256Kb:
  66. BlockPool256K.Put(buf[:c])
  67. case Block1Mb:
  68. BlockPool1M.Put(buf[:c])
  69. case Block4Mb:
  70. BlockPool4M.Put(buf[:c])
  71. case Block8Mb:
  72. BlockPool8M.Put(buf[:c])
  73. }
  74. }
  75. type CompressionLevel uint32
  76. const Fast CompressionLevel = 0