compress.go 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170
  1. // Copyright 2017 The go-ethereum Authors
  2. // This file is part of the go-ethereum library.
  3. //
  4. // The go-ethereum library is free software: you can redistribute it and/or modify
  5. // it under the terms of the GNU Lesser General Public License as published by
  6. // the Free Software Foundation, either version 3 of the License, or
  7. // (at your option) any later version.
  8. //
  9. // The go-ethereum library is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. // GNU Lesser General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU Lesser General Public License
  15. // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
  16. package bitutil
  17. import "errors"
  18. var (
  19. // errMissingData is returned from decompression if the byte referenced by
  20. // the bitset header overflows the input data.
  21. errMissingData = errors.New("missing bytes on input")
  22. // errUnreferencedData is returned from decompression if not all bytes were used
  23. // up from the input data after decompressing it.
  24. errUnreferencedData = errors.New("extra bytes on input")
  25. // errExceededTarget is returned from decompression if the bitset header has
  26. // more bits defined than the number of target buffer space available.
  27. errExceededTarget = errors.New("target data size exceeded")
  28. // errZeroContent is returned from decompression if a data byte referenced in
  29. // the bitset header is actually a zero byte.
  30. errZeroContent = errors.New("zero byte in input content")
  31. )
  32. // The compression algorithm implemented by CompressBytes and DecompressBytes is
  33. // optimized for sparse input data which contains a lot of zero bytes. Decompression
  34. // requires knowledge of the decompressed data length.
  35. //
  36. // Compression works as follows:
  37. //
  38. // if data only contains zeroes,
  39. // CompressBytes(data) == nil
  40. // otherwise if len(data) <= 1,
  41. // CompressBytes(data) == data
  42. // otherwise:
  43. // CompressBytes(data) == append(CompressBytes(nonZeroBitset(data)), nonZeroBytes(data)...)
  44. // where
  45. // nonZeroBitset(data) is a bit vector with len(data) bits (MSB first):
  46. // nonZeroBitset(data)[i/8] && (1 << (7-i%8)) != 0 if data[i] != 0
  47. // len(nonZeroBitset(data)) == (len(data)+7)/8
  48. // nonZeroBytes(data) contains the non-zero bytes of data in the same order
  49. // CompressBytes compresses the input byte slice according to the sparse bitset
  50. // representation algorithm. If the result is bigger than the original input, no
  51. // compression is done.
  52. func CompressBytes(data []byte) []byte {
  53. if out := bitsetEncodeBytes(data); len(out) < len(data) {
  54. return out
  55. }
  56. cpy := make([]byte, len(data))
  57. copy(cpy, data)
  58. return cpy
  59. }
  60. // bitsetEncodeBytes compresses the input byte slice according to the sparse
  61. // bitset representation algorithm.
  62. func bitsetEncodeBytes(data []byte) []byte {
  63. // Empty slices get compressed to nil
  64. if len(data) == 0 {
  65. return nil
  66. }
  67. // One byte slices compress to nil or retain the single byte
  68. if len(data) == 1 {
  69. if data[0] == 0 {
  70. return nil
  71. }
  72. return data
  73. }
  74. // Calculate the bitset of set bytes, and gather the non-zero bytes
  75. nonZeroBitset := make([]byte, (len(data)+7)/8)
  76. nonZeroBytes := make([]byte, 0, len(data))
  77. for i, b := range data {
  78. if b != 0 {
  79. nonZeroBytes = append(nonZeroBytes, b)
  80. nonZeroBitset[i/8] |= 1 << byte(7-i%8)
  81. }
  82. }
  83. if len(nonZeroBytes) == 0 {
  84. return nil
  85. }
  86. return append(bitsetEncodeBytes(nonZeroBitset), nonZeroBytes...)
  87. }
  88. // DecompressBytes decompresses data with a known target size. If the input data
  89. // matches the size of the target, it means no compression was done in the first
  90. // place.
  91. func DecompressBytes(data []byte, target int) ([]byte, error) {
  92. if len(data) > target {
  93. return nil, errExceededTarget
  94. }
  95. if len(data) == target {
  96. cpy := make([]byte, len(data))
  97. copy(cpy, data)
  98. return cpy, nil
  99. }
  100. return bitsetDecodeBytes(data, target)
  101. }
  102. // bitsetDecodeBytes decompresses data with a known target size.
  103. func bitsetDecodeBytes(data []byte, target int) ([]byte, error) {
  104. out, size, err := bitsetDecodePartialBytes(data, target)
  105. if err != nil {
  106. return nil, err
  107. }
  108. if size != len(data) {
  109. return nil, errUnreferencedData
  110. }
  111. return out, nil
  112. }
  113. // bitsetDecodePartialBytes decompresses data with a known target size, but does
  114. // not enforce consuming all the input bytes. In addition to the decompressed
  115. // output, the function returns the length of compressed input data corresponding
  116. // to the output as the input slice may be longer.
  117. func bitsetDecodePartialBytes(data []byte, target int) ([]byte, int, error) {
  118. // Sanity check 0 targets to avoid infinite recursion
  119. if target == 0 {
  120. return nil, 0, nil
  121. }
  122. // Handle the zero and single byte corner cases
  123. decomp := make([]byte, target)
  124. if len(data) == 0 {
  125. return decomp, 0, nil
  126. }
  127. if target == 1 {
  128. decomp[0] = data[0] // copy to avoid referencing the input slice
  129. if data[0] != 0 {
  130. return decomp, 1, nil
  131. }
  132. return decomp, 0, nil
  133. }
  134. // Decompress the bitset of set bytes and distribute the non zero bytes
  135. nonZeroBitset, ptr, err := bitsetDecodePartialBytes(data, (target+7)/8)
  136. if err != nil {
  137. return nil, ptr, err
  138. }
  139. for i := 0; i < 8*len(nonZeroBitset); i++ {
  140. if nonZeroBitset[i/8]&(1<<byte(7-i%8)) != 0 {
  141. // Make sure we have enough data to push into the correct slot
  142. if ptr >= len(data) {
  143. return nil, 0, errMissingData
  144. }
  145. if i >= len(decomp) {
  146. return nil, 0, errExceededTarget
  147. }
  148. // Make sure the data is valid and push into the slot
  149. if data[ptr] == 0 {
  150. return nil, 0, errZeroContent
  151. }
  152. decomp[i] = data[ptr]
  153. ptr++
  154. }
  155. }
  156. return decomp, ptr, nil
  157. }