encode_other.go 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236
  1. // Copyright 2016 The Snappy-Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. package snapref
  5. func load32(b []byte, i int) uint32 {
  6. b = b[i : i+4 : len(b)] // Help the compiler eliminate bounds checks on the next line.
  7. return uint32(b[0]) | uint32(b[1])<<8 | uint32(b[2])<<16 | uint32(b[3])<<24
  8. }
  9. func load64(b []byte, i int) uint64 {
  10. b = b[i : i+8 : len(b)] // Help the compiler eliminate bounds checks on the next line.
  11. return uint64(b[0]) | uint64(b[1])<<8 | uint64(b[2])<<16 | uint64(b[3])<<24 |
  12. uint64(b[4])<<32 | uint64(b[5])<<40 | uint64(b[6])<<48 | uint64(b[7])<<56
  13. }
  14. // emitLiteral writes a literal chunk and returns the number of bytes written.
  15. //
  16. // It assumes that:
  17. // dst is long enough to hold the encoded bytes
  18. // 1 <= len(lit) && len(lit) <= 65536
  19. func emitLiteral(dst, lit []byte) int {
  20. i, n := 0, uint(len(lit)-1)
  21. switch {
  22. case n < 60:
  23. dst[0] = uint8(n)<<2 | tagLiteral
  24. i = 1
  25. case n < 1<<8:
  26. dst[0] = 60<<2 | tagLiteral
  27. dst[1] = uint8(n)
  28. i = 2
  29. default:
  30. dst[0] = 61<<2 | tagLiteral
  31. dst[1] = uint8(n)
  32. dst[2] = uint8(n >> 8)
  33. i = 3
  34. }
  35. return i + copy(dst[i:], lit)
  36. }
  37. // emitCopy writes a copy chunk and returns the number of bytes written.
  38. //
  39. // It assumes that:
  40. // dst is long enough to hold the encoded bytes
  41. // 1 <= offset && offset <= 65535
  42. // 4 <= length && length <= 65535
  43. func emitCopy(dst []byte, offset, length int) int {
  44. i := 0
  45. // The maximum length for a single tagCopy1 or tagCopy2 op is 64 bytes. The
  46. // threshold for this loop is a little higher (at 68 = 64 + 4), and the
  47. // length emitted down below is is a little lower (at 60 = 64 - 4), because
  48. // it's shorter to encode a length 67 copy as a length 60 tagCopy2 followed
  49. // by a length 7 tagCopy1 (which encodes as 3+2 bytes) than to encode it as
  50. // a length 64 tagCopy2 followed by a length 3 tagCopy2 (which encodes as
  51. // 3+3 bytes). The magic 4 in the 64±4 is because the minimum length for a
  52. // tagCopy1 op is 4 bytes, which is why a length 3 copy has to be an
  53. // encodes-as-3-bytes tagCopy2 instead of an encodes-as-2-bytes tagCopy1.
  54. for length >= 68 {
  55. // Emit a length 64 copy, encoded as 3 bytes.
  56. dst[i+0] = 63<<2 | tagCopy2
  57. dst[i+1] = uint8(offset)
  58. dst[i+2] = uint8(offset >> 8)
  59. i += 3
  60. length -= 64
  61. }
  62. if length > 64 {
  63. // Emit a length 60 copy, encoded as 3 bytes.
  64. dst[i+0] = 59<<2 | tagCopy2
  65. dst[i+1] = uint8(offset)
  66. dst[i+2] = uint8(offset >> 8)
  67. i += 3
  68. length -= 60
  69. }
  70. if length >= 12 || offset >= 2048 {
  71. // Emit the remaining copy, encoded as 3 bytes.
  72. dst[i+0] = uint8(length-1)<<2 | tagCopy2
  73. dst[i+1] = uint8(offset)
  74. dst[i+2] = uint8(offset >> 8)
  75. return i + 3
  76. }
  77. // Emit the remaining copy, encoded as 2 bytes.
  78. dst[i+0] = uint8(offset>>8)<<5 | uint8(length-4)<<2 | tagCopy1
  79. dst[i+1] = uint8(offset)
  80. return i + 2
  81. }
  82. // extendMatch returns the largest k such that k <= len(src) and that
  83. // src[i:i+k-j] and src[j:k] have the same contents.
  84. //
  85. // It assumes that:
  86. // 0 <= i && i < j && j <= len(src)
  87. func extendMatch(src []byte, i, j int) int {
  88. for ; j < len(src) && src[i] == src[j]; i, j = i+1, j+1 {
  89. }
  90. return j
  91. }
  92. func hash(u, shift uint32) uint32 {
  93. return (u * 0x1e35a7bd) >> shift
  94. }
  95. // encodeBlock encodes a non-empty src to a guaranteed-large-enough dst. It
  96. // assumes that the varint-encoded length of the decompressed bytes has already
  97. // been written.
  98. //
  99. // It also assumes that:
  100. // len(dst) >= MaxEncodedLen(len(src)) &&
  101. // minNonLiteralBlockSize <= len(src) && len(src) <= maxBlockSize
  102. func encodeBlock(dst, src []byte) (d int) {
  103. // Initialize the hash table. Its size ranges from 1<<8 to 1<<14 inclusive.
  104. // The table element type is uint16, as s < sLimit and sLimit < len(src)
  105. // and len(src) <= maxBlockSize and maxBlockSize == 65536.
  106. const (
  107. maxTableSize = 1 << 14
  108. // tableMask is redundant, but helps the compiler eliminate bounds
  109. // checks.
  110. tableMask = maxTableSize - 1
  111. )
  112. shift := uint32(32 - 8)
  113. for tableSize := 1 << 8; tableSize < maxTableSize && tableSize < len(src); tableSize *= 2 {
  114. shift--
  115. }
  116. // In Go, all array elements are zero-initialized, so there is no advantage
  117. // to a smaller tableSize per se. However, it matches the C++ algorithm,
  118. // and in the asm versions of this code, we can get away with zeroing only
  119. // the first tableSize elements.
  120. var table [maxTableSize]uint16
  121. // sLimit is when to stop looking for offset/length copies. The inputMargin
  122. // lets us use a fast path for emitLiteral in the main loop, while we are
  123. // looking for copies.
  124. sLimit := len(src) - inputMargin
  125. // nextEmit is where in src the next emitLiteral should start from.
  126. nextEmit := 0
  127. // The encoded form must start with a literal, as there are no previous
  128. // bytes to copy, so we start looking for hash matches at s == 1.
  129. s := 1
  130. nextHash := hash(load32(src, s), shift)
  131. for {
  132. // Copied from the C++ snappy implementation:
  133. //
  134. // Heuristic match skipping: If 32 bytes are scanned with no matches
  135. // found, start looking only at every other byte. If 32 more bytes are
  136. // scanned (or skipped), look at every third byte, etc.. When a match
  137. // is found, immediately go back to looking at every byte. This is a
  138. // small loss (~5% performance, ~0.1% density) for compressible data
  139. // due to more bookkeeping, but for non-compressible data (such as
  140. // JPEG) it's a huge win since the compressor quickly "realizes" the
  141. // data is incompressible and doesn't bother looking for matches
  142. // everywhere.
  143. //
  144. // The "skip" variable keeps track of how many bytes there are since
  145. // the last match; dividing it by 32 (ie. right-shifting by five) gives
  146. // the number of bytes to move ahead for each iteration.
  147. skip := 32
  148. nextS := s
  149. candidate := 0
  150. for {
  151. s = nextS
  152. bytesBetweenHashLookups := skip >> 5
  153. nextS = s + bytesBetweenHashLookups
  154. skip += bytesBetweenHashLookups
  155. if nextS > sLimit {
  156. goto emitRemainder
  157. }
  158. candidate = int(table[nextHash&tableMask])
  159. table[nextHash&tableMask] = uint16(s)
  160. nextHash = hash(load32(src, nextS), shift)
  161. if load32(src, s) == load32(src, candidate) {
  162. break
  163. }
  164. }
  165. // A 4-byte match has been found. We'll later see if more than 4 bytes
  166. // match. But, prior to the match, src[nextEmit:s] are unmatched. Emit
  167. // them as literal bytes.
  168. d += emitLiteral(dst[d:], src[nextEmit:s])
  169. // Call emitCopy, and then see if another emitCopy could be our next
  170. // move. Repeat until we find no match for the input immediately after
  171. // what was consumed by the last emitCopy call.
  172. //
  173. // If we exit this loop normally then we need to call emitLiteral next,
  174. // though we don't yet know how big the literal will be. We handle that
  175. // by proceeding to the next iteration of the main loop. We also can
  176. // exit this loop via goto if we get close to exhausting the input.
  177. for {
  178. // Invariant: we have a 4-byte match at s, and no need to emit any
  179. // literal bytes prior to s.
  180. base := s
  181. // Extend the 4-byte match as long as possible.
  182. //
  183. // This is an inlined version of:
  184. // s = extendMatch(src, candidate+4, s+4)
  185. s += 4
  186. for i := candidate + 4; s < len(src) && src[i] == src[s]; i, s = i+1, s+1 {
  187. }
  188. d += emitCopy(dst[d:], base-candidate, s-base)
  189. nextEmit = s
  190. if s >= sLimit {
  191. goto emitRemainder
  192. }
  193. // We could immediately start working at s now, but to improve
  194. // compression we first update the hash table at s-1 and at s. If
  195. // another emitCopy is not our next move, also calculate nextHash
  196. // at s+1. At least on GOARCH=amd64, these three hash calculations
  197. // are faster as one load64 call (with some shifts) instead of
  198. // three load32 calls.
  199. x := load64(src, s-1)
  200. prevHash := hash(uint32(x>>0), shift)
  201. table[prevHash&tableMask] = uint16(s - 1)
  202. currHash := hash(uint32(x>>8), shift)
  203. candidate = int(table[currHash&tableMask])
  204. table[currHash&tableMask] = uint16(s)
  205. if uint32(x>>8) != load32(src, candidate) {
  206. nextHash = hash(uint32(x>>16), shift)
  207. s++
  208. break
  209. }
  210. }
  211. }
  212. emitRemainder:
  213. if nextEmit < len(src) {
  214. d += emitLiteral(dst[d:], src[nextEmit:])
  215. }
  216. return d
  217. }