encode_other.go 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262
  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 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. // extendMatch returns the largest k such that k <= len(src) and that
  85. // src[i:i+k-j] and src[j:k] have the same contents.
  86. //
  87. // It assumes that:
  88. //
  89. // 0 <= i && i < j && j <= len(src)
  90. func extendMatch(src []byte, i, j int) int {
  91. for ; j < len(src) && src[i] == src[j]; i, j = i+1, j+1 {
  92. }
  93. return j
  94. }
  95. func hash(u, shift uint32) uint32 {
  96. return (u * 0x1e35a7bd) >> shift
  97. }
  98. // EncodeBlockInto exposes encodeBlock but checks dst size.
  99. func EncodeBlockInto(dst, src []byte) (d int) {
  100. if MaxEncodedLen(len(src)) > len(dst) {
  101. return 0
  102. }
  103. // encodeBlock breaks on too big blocks, so split.
  104. for len(src) > 0 {
  105. p := src
  106. src = nil
  107. if len(p) > maxBlockSize {
  108. p, src = p[:maxBlockSize], p[maxBlockSize:]
  109. }
  110. if len(p) < minNonLiteralBlockSize {
  111. d += emitLiteral(dst[d:], p)
  112. } else {
  113. d += encodeBlock(dst[d:], p)
  114. }
  115. }
  116. return d
  117. }
  118. // encodeBlock encodes a non-empty src to a guaranteed-large-enough dst. It
  119. // assumes that the varint-encoded length of the decompressed bytes has already
  120. // been written.
  121. //
  122. // It also assumes that:
  123. //
  124. // len(dst) >= MaxEncodedLen(len(src)) &&
  125. // minNonLiteralBlockSize <= len(src) && len(src) <= maxBlockSize
  126. func encodeBlock(dst, src []byte) (d int) {
  127. // Initialize the hash table. Its size ranges from 1<<8 to 1<<14 inclusive.
  128. // The table element type is uint16, as s < sLimit and sLimit < len(src)
  129. // and len(src) <= maxBlockSize and maxBlockSize == 65536.
  130. const (
  131. maxTableSize = 1 << 14
  132. // tableMask is redundant, but helps the compiler eliminate bounds
  133. // checks.
  134. tableMask = maxTableSize - 1
  135. )
  136. shift := uint32(32 - 8)
  137. for tableSize := 1 << 8; tableSize < maxTableSize && tableSize < len(src); tableSize *= 2 {
  138. shift--
  139. }
  140. // In Go, all array elements are zero-initialized, so there is no advantage
  141. // to a smaller tableSize per se. However, it matches the C++ algorithm,
  142. // and in the asm versions of this code, we can get away with zeroing only
  143. // the first tableSize elements.
  144. var table [maxTableSize]uint16
  145. // sLimit is when to stop looking for offset/length copies. The inputMargin
  146. // lets us use a fast path for emitLiteral in the main loop, while we are
  147. // looking for copies.
  148. sLimit := len(src) - inputMargin
  149. // nextEmit is where in src the next emitLiteral should start from.
  150. nextEmit := 0
  151. // The encoded form must start with a literal, as there are no previous
  152. // bytes to copy, so we start looking for hash matches at s == 1.
  153. s := 1
  154. nextHash := hash(load32(src, s), shift)
  155. for {
  156. // Copied from the C++ snappy implementation:
  157. //
  158. // Heuristic match skipping: If 32 bytes are scanned with no matches
  159. // found, start looking only at every other byte. If 32 more bytes are
  160. // scanned (or skipped), look at every third byte, etc.. When a match
  161. // is found, immediately go back to looking at every byte. This is a
  162. // small loss (~5% performance, ~0.1% density) for compressible data
  163. // due to more bookkeeping, but for non-compressible data (such as
  164. // JPEG) it's a huge win since the compressor quickly "realizes" the
  165. // data is incompressible and doesn't bother looking for matches
  166. // everywhere.
  167. //
  168. // The "skip" variable keeps track of how many bytes there are since
  169. // the last match; dividing it by 32 (ie. right-shifting by five) gives
  170. // the number of bytes to move ahead for each iteration.
  171. skip := 32
  172. nextS := s
  173. candidate := 0
  174. for {
  175. s = nextS
  176. bytesBetweenHashLookups := skip >> 5
  177. nextS = s + bytesBetweenHashLookups
  178. skip += bytesBetweenHashLookups
  179. if nextS > sLimit {
  180. goto emitRemainder
  181. }
  182. candidate = int(table[nextHash&tableMask])
  183. table[nextHash&tableMask] = uint16(s)
  184. nextHash = hash(load32(src, nextS), shift)
  185. if load32(src, s) == load32(src, candidate) {
  186. break
  187. }
  188. }
  189. // A 4-byte match has been found. We'll later see if more than 4 bytes
  190. // match. But, prior to the match, src[nextEmit:s] are unmatched. Emit
  191. // them as literal bytes.
  192. d += emitLiteral(dst[d:], src[nextEmit:s])
  193. // Call emitCopy, and then see if another emitCopy could be our next
  194. // move. Repeat until we find no match for the input immediately after
  195. // what was consumed by the last emitCopy call.
  196. //
  197. // If we exit this loop normally then we need to call emitLiteral next,
  198. // though we don't yet know how big the literal will be. We handle that
  199. // by proceeding to the next iteration of the main loop. We also can
  200. // exit this loop via goto if we get close to exhausting the input.
  201. for {
  202. // Invariant: we have a 4-byte match at s, and no need to emit any
  203. // literal bytes prior to s.
  204. base := s
  205. // Extend the 4-byte match as long as possible.
  206. //
  207. // This is an inlined version of:
  208. // s = extendMatch(src, candidate+4, s+4)
  209. s += 4
  210. for i := candidate + 4; s < len(src) && src[i] == src[s]; i, s = i+1, s+1 {
  211. }
  212. d += emitCopy(dst[d:], base-candidate, s-base)
  213. nextEmit = s
  214. if s >= sLimit {
  215. goto emitRemainder
  216. }
  217. // We could immediately start working at s now, but to improve
  218. // compression we first update the hash table at s-1 and at s. If
  219. // another emitCopy is not our next move, also calculate nextHash
  220. // at s+1. At least on GOARCH=amd64, these three hash calculations
  221. // are faster as one load64 call (with some shifts) instead of
  222. // three load32 calls.
  223. x := load64(src, s-1)
  224. prevHash := hash(uint32(x>>0), shift)
  225. table[prevHash&tableMask] = uint16(s - 1)
  226. currHash := hash(uint32(x>>8), shift)
  227. candidate = int(table[currHash&tableMask])
  228. table[currHash&tableMask] = uint16(s)
  229. if uint32(x>>8) != load32(src, candidate) {
  230. nextHash = hash(uint32(x>>16), shift)
  231. s++
  232. break
  233. }
  234. }
  235. }
  236. emitRemainder:
  237. if nextEmit < len(src) {
  238. d += emitLiteral(dst[d:], src[nextEmit:])
  239. }
  240. return d
  241. }