encode_other.go 8.2 KB

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