encode.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430
  1. // Copyright 2011 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 snappy
  5. import (
  6. "encoding/binary"
  7. "errors"
  8. "io"
  9. )
  10. func load32(b []byte, i int) uint32 {
  11. b = b[i : i+4 : len(b)] // Help the compiler eliminate bounds checks on the next line.
  12. return uint32(b[0]) | uint32(b[1])<<8 | uint32(b[2])<<16 | uint32(b[3])<<24
  13. }
  14. func load64(b []byte, i int) uint64 {
  15. b = b[i : i+8 : len(b)] // Help the compiler eliminate bounds checks on the next line.
  16. return uint64(b[0]) | uint64(b[1])<<8 | uint64(b[2])<<16 | uint64(b[3])<<24 |
  17. uint64(b[4])<<32 | uint64(b[5])<<40 | uint64(b[6])<<48 | uint64(b[7])<<56
  18. }
  19. // Encode returns the encoded form of src. The returned slice may be a sub-
  20. // slice of dst if dst was large enough to hold the entire encoded block.
  21. // Otherwise, a newly allocated slice will be returned.
  22. //
  23. // The dst and src must not overlap. It is valid to pass a nil dst.
  24. func Encode(dst, src []byte) []byte {
  25. if n := MaxEncodedLen(len(src)); n < 0 {
  26. panic(ErrTooLarge)
  27. } else if len(dst) < n {
  28. dst = make([]byte, n)
  29. }
  30. // The block starts with the varint-encoded length of the decompressed bytes.
  31. d := binary.PutUvarint(dst, uint64(len(src)))
  32. for len(src) > 0 {
  33. p := src
  34. src = nil
  35. if len(p) > maxBlockSize {
  36. p, src = p[:maxBlockSize], p[maxBlockSize:]
  37. }
  38. if len(p) < minNonLiteralBlockSize {
  39. d += emitLiteral(dst[d:], p)
  40. } else {
  41. d += encodeBlock(dst[d:], p)
  42. }
  43. }
  44. return dst[:d]
  45. }
  46. // inputMargin is the minimum number of extra input bytes to keep, inside
  47. // encodeBlock's inner loop. On some architectures, this margin lets us
  48. // implement a fast path for emitLiteral, where the copy of short (<= 16 byte)
  49. // literals can be implemented as a single load to and store from a 16-byte
  50. // register. That literal's actual length can be as short as 1 byte, so this
  51. // can copy up to 15 bytes too much, but that's OK as subsequent iterations of
  52. // the encoding loop will fix up the copy overrun, and this inputMargin ensures
  53. // that we don't overrun the dst and src buffers.
  54. //
  55. // TODO: implement this fast path.
  56. const inputMargin = 16 - 1
  57. // minNonLiteralBlockSize is the minimum size of the input to encodeBlock that
  58. // could be encoded with a copy tag. This is the minimum with respect to the
  59. // algorithm used by encodeBlock, not a minimum enforced by the file format.
  60. //
  61. // The encoded output must start with at least a 1 byte literal, as there are
  62. // no previous bytes to copy. A minimal (1 byte) copy after that, generated
  63. // from an emitCopy call in encodeBlock's main loop, would require at least
  64. // another inputMargin bytes, for the reason above: we want any emitLiteral
  65. // calls inside encodeBlock's main loop to use the fast path if possible, which
  66. // requires being able to overrun by inputMargin bytes. Thus,
  67. // minNonLiteralBlockSize equals 1 + 1 + inputMargin.
  68. //
  69. // The C++ code doesn't use this exact threshold, but it could, as discussed at
  70. // https://groups.google.com/d/topic/snappy-compression/oGbhsdIJSJ8/discussion
  71. // The difference between Go (2+inputMargin) and C++ (inputMargin) is purely an
  72. // optimization. It should not affect the encoded form. This is tested by
  73. // TestSameEncodingAsCppShortCopies.
  74. const minNonLiteralBlockSize = 1 + 1 + inputMargin
  75. func hash(u, shift uint32) uint32 {
  76. return (u * 0x1e35a7bd) >> shift
  77. }
  78. // encodeBlock encodes a non-empty src to a guaranteed-large-enough dst. It
  79. // assumes that the varint-encoded length of the decompressed bytes has already
  80. // been written.
  81. //
  82. // It also assumes that:
  83. // len(dst) >= MaxEncodedLen(len(src)) &&
  84. // minNonLiteralBlockSize <= len(src) && len(src) <= maxBlockSize
  85. func encodeBlock(dst, src []byte) (d int) {
  86. // Initialize the hash table. Its size ranges from 1<<8 to 1<<14 inclusive.
  87. // The table element type is uint16, as s < sLimit and sLimit < len(src)
  88. // and len(src) <= maxBlockSize and maxBlockSize == 65536.
  89. const (
  90. maxTableSize = 1 << 14
  91. // tableMask is redundant, but helps the compiler eliminate bounds
  92. // checks.
  93. tableMask = maxTableSize - 1
  94. )
  95. shift := uint32(32 - 8)
  96. for tableSize := 1 << 8; tableSize < maxTableSize && tableSize < len(src); tableSize *= 2 {
  97. shift--
  98. }
  99. // In Go, all array elements are zero-initialized, so there is no advantage
  100. // to a smaller tableSize per se. However, it matches the C++ algorithm,
  101. // and in the asm versions of this code, we can get away with zeroing only
  102. // the first tableSize elements.
  103. var table [maxTableSize]uint16
  104. // sLimit is when to stop looking for offset/length copies. The inputMargin
  105. // lets us use a fast path for emitLiteral in the main loop, while we are
  106. // looking for copies.
  107. sLimit := len(src) - inputMargin
  108. // nextEmit is where in src the next emitLiteral should start from.
  109. nextEmit := 0
  110. // The encoded form must start with a literal, as there are no previous
  111. // bytes to copy, so we start looking for hash matches at s == 1.
  112. s := 1
  113. nextHash := hash(load32(src, s), shift)
  114. for {
  115. // Copied from the C++ snappy implementation:
  116. //
  117. // Heuristic match skipping: If 32 bytes are scanned with no matches
  118. // found, start looking only at every other byte. If 32 more bytes are
  119. // scanned (or skipped), look at every third byte, etc.. When a match
  120. // is found, immediately go back to looking at every byte. This is a
  121. // small loss (~5% performance, ~0.1% density) for compressible data
  122. // due to more bookkeeping, but for non-compressible data (such as
  123. // JPEG) it's a huge win since the compressor quickly "realizes" the
  124. // data is incompressible and doesn't bother looking for matches
  125. // everywhere.
  126. //
  127. // The "skip" variable keeps track of how many bytes there are since
  128. // the last match; dividing it by 32 (ie. right-shifting by five) gives
  129. // the number of bytes to move ahead for each iteration.
  130. skip := 32
  131. nextS := s
  132. candidate := 0
  133. for {
  134. s = nextS
  135. bytesBetweenHashLookups := skip >> 5
  136. nextS = s + bytesBetweenHashLookups
  137. skip += bytesBetweenHashLookups
  138. if nextS > sLimit {
  139. goto emitRemainder
  140. }
  141. candidate = int(table[nextHash&tableMask])
  142. table[nextHash&tableMask] = uint16(s)
  143. nextHash = hash(load32(src, nextS), shift)
  144. if load32(src, s) == load32(src, candidate) {
  145. break
  146. }
  147. }
  148. // A 4-byte match has been found. We'll later see if more than 4 bytes
  149. // match. But, prior to the match, src[nextEmit:s] are unmatched. Emit
  150. // them as literal bytes.
  151. d += emitLiteral(dst[d:], src[nextEmit:s])
  152. // Call emitCopy, and then see if another emitCopy could be our next
  153. // move. Repeat until we find no match for the input immediately after
  154. // what was consumed by the last emitCopy call.
  155. //
  156. // If we exit this loop normally then we need to call emitLiteral next,
  157. // though we don't yet know how big the literal will be. We handle that
  158. // by proceeding to the next iteration of the main loop. We also can
  159. // exit this loop via goto if we get close to exhausting the input.
  160. for {
  161. // Invariant: we have a 4-byte match at s, and no need to emit any
  162. // literal bytes prior to s.
  163. base := s
  164. // Extend the 4-byte match as long as possible.
  165. s = extendMatch(src, candidate+4, s+4)
  166. d += emitCopy(dst[d:], base-candidate, s-base)
  167. nextEmit = s
  168. if s >= sLimit {
  169. goto emitRemainder
  170. }
  171. // We could immediately start working at s now, but to improve
  172. // compression we first update the hash table at s-1 and at s. If
  173. // another emitCopy is not our next move, also calculate nextHash
  174. // at s+1. At least on GOARCH=amd64, these three hash calculations
  175. // are faster as one load64 call (with some shifts) instead of
  176. // three load32 calls.
  177. x := load64(src, s-1)
  178. prevHash := hash(uint32(x>>0), shift)
  179. table[prevHash&tableMask] = uint16(s - 1)
  180. currHash := hash(uint32(x>>8), shift)
  181. candidate = int(table[currHash&tableMask])
  182. table[currHash&tableMask] = uint16(s)
  183. if uint32(x>>8) != load32(src, candidate) {
  184. nextHash = hash(uint32(x>>16), shift)
  185. s++
  186. break
  187. }
  188. }
  189. }
  190. emitRemainder:
  191. if nextEmit < len(src) {
  192. d += emitLiteral(dst[d:], src[nextEmit:])
  193. }
  194. return d
  195. }
  196. // MaxEncodedLen returns the maximum length of a snappy block, given its
  197. // uncompressed length.
  198. //
  199. // It will return a negative value if srcLen is too large to encode.
  200. func MaxEncodedLen(srcLen int) int {
  201. n := uint64(srcLen)
  202. if n > 0xffffffff {
  203. return -1
  204. }
  205. // Compressed data can be defined as:
  206. // compressed := item* literal*
  207. // item := literal* copy
  208. //
  209. // The trailing literal sequence has a space blowup of at most 62/60
  210. // since a literal of length 60 needs one tag byte + one extra byte
  211. // for length information.
  212. //
  213. // Item blowup is trickier to measure. Suppose the "copy" op copies
  214. // 4 bytes of data. Because of a special check in the encoding code,
  215. // we produce a 4-byte copy only if the offset is < 65536. Therefore
  216. // the copy op takes 3 bytes to encode, and this type of item leads
  217. // to at most the 62/60 blowup for representing literals.
  218. //
  219. // Suppose the "copy" op copies 5 bytes of data. If the offset is big
  220. // enough, it will take 5 bytes to encode the copy op. Therefore the
  221. // worst case here is a one-byte literal followed by a five-byte copy.
  222. // That is, 6 bytes of input turn into 7 bytes of "compressed" data.
  223. //
  224. // This last factor dominates the blowup, so the final estimate is:
  225. n = 32 + n + n/6
  226. if n > 0xffffffff {
  227. return -1
  228. }
  229. return int(n)
  230. }
  231. var errClosed = errors.New("snappy: Writer is closed")
  232. // NewWriter returns a new Writer that compresses to w.
  233. //
  234. // The Writer returned does not buffer writes. There is no need to Flush or
  235. // Close such a Writer.
  236. //
  237. // Deprecated: the Writer returned is not suitable for many small writes, only
  238. // for few large writes. Use NewBufferedWriter instead, which is efficient
  239. // regardless of the frequency and shape of the writes, and remember to Close
  240. // that Writer when done.
  241. func NewWriter(w io.Writer) *Writer {
  242. return &Writer{
  243. w: w,
  244. obuf: make([]byte, obufLen),
  245. }
  246. }
  247. // NewBufferedWriter returns a new Writer that compresses to w, using the
  248. // framing format described at
  249. // https://github.com/google/snappy/blob/master/framing_format.txt
  250. //
  251. // The Writer returned buffers writes. Users must call Close to guarantee all
  252. // data has been forwarded to the underlying io.Writer. They may also call
  253. // Flush zero or more times before calling Close.
  254. func NewBufferedWriter(w io.Writer) *Writer {
  255. return &Writer{
  256. w: w,
  257. ibuf: make([]byte, 0, maxBlockSize),
  258. obuf: make([]byte, obufLen),
  259. }
  260. }
  261. // Writer is an io.Writer than can write Snappy-compressed bytes.
  262. type Writer struct {
  263. w io.Writer
  264. err error
  265. // ibuf is a buffer for the incoming (uncompressed) bytes.
  266. //
  267. // Its use is optional. For backwards compatibility, Writers created by the
  268. // NewWriter function have ibuf == nil, do not buffer incoming bytes, and
  269. // therefore do not need to be Flush'ed or Close'd.
  270. ibuf []byte
  271. // obuf is a buffer for the outgoing (compressed) bytes.
  272. obuf []byte
  273. // wroteStreamHeader is whether we have written the stream header.
  274. wroteStreamHeader bool
  275. }
  276. // Reset discards the writer's state and switches the Snappy writer to write to
  277. // w. This permits reusing a Writer rather than allocating a new one.
  278. func (w *Writer) Reset(writer io.Writer) {
  279. w.w = writer
  280. w.err = nil
  281. if w.ibuf != nil {
  282. w.ibuf = w.ibuf[:0]
  283. }
  284. w.wroteStreamHeader = false
  285. }
  286. // Write satisfies the io.Writer interface.
  287. func (w *Writer) Write(p []byte) (nRet int, errRet error) {
  288. if w.ibuf == nil {
  289. // Do not buffer incoming bytes. This does not perform or compress well
  290. // if the caller of Writer.Write writes many small slices. This
  291. // behavior is therefore deprecated, but still supported for backwards
  292. // compatibility with code that doesn't explicitly Flush or Close.
  293. return w.write(p)
  294. }
  295. // The remainder of this method is based on bufio.Writer.Write from the
  296. // standard library.
  297. for len(p) > (cap(w.ibuf)-len(w.ibuf)) && w.err == nil {
  298. var n int
  299. if len(w.ibuf) == 0 {
  300. // Large write, empty buffer.
  301. // Write directly from p to avoid copy.
  302. n, _ = w.write(p)
  303. } else {
  304. n = copy(w.ibuf[len(w.ibuf):cap(w.ibuf)], p)
  305. w.ibuf = w.ibuf[:len(w.ibuf)+n]
  306. w.Flush()
  307. }
  308. nRet += n
  309. p = p[n:]
  310. }
  311. if w.err != nil {
  312. return nRet, w.err
  313. }
  314. n := copy(w.ibuf[len(w.ibuf):cap(w.ibuf)], p)
  315. w.ibuf = w.ibuf[:len(w.ibuf)+n]
  316. nRet += n
  317. return nRet, nil
  318. }
  319. func (w *Writer) write(p []byte) (nRet int, errRet error) {
  320. if w.err != nil {
  321. return 0, w.err
  322. }
  323. for len(p) > 0 {
  324. obufStart := len(magicChunk)
  325. if !w.wroteStreamHeader {
  326. w.wroteStreamHeader = true
  327. copy(w.obuf, magicChunk)
  328. obufStart = 0
  329. }
  330. var uncompressed []byte
  331. if len(p) > maxBlockSize {
  332. uncompressed, p = p[:maxBlockSize], p[maxBlockSize:]
  333. } else {
  334. uncompressed, p = p, nil
  335. }
  336. checksum := crc(uncompressed)
  337. // Compress the buffer, discarding the result if the improvement
  338. // isn't at least 12.5%.
  339. compressed := Encode(w.obuf[obufHeaderLen:], uncompressed)
  340. chunkType := uint8(chunkTypeCompressedData)
  341. chunkLen := 4 + len(compressed)
  342. obufEnd := obufHeaderLen + len(compressed)
  343. if len(compressed) >= len(uncompressed)-len(uncompressed)/8 {
  344. chunkType = chunkTypeUncompressedData
  345. chunkLen = 4 + len(uncompressed)
  346. obufEnd = obufHeaderLen
  347. }
  348. // Fill in the per-chunk header that comes before the body.
  349. w.obuf[len(magicChunk)+0] = chunkType
  350. w.obuf[len(magicChunk)+1] = uint8(chunkLen >> 0)
  351. w.obuf[len(magicChunk)+2] = uint8(chunkLen >> 8)
  352. w.obuf[len(magicChunk)+3] = uint8(chunkLen >> 16)
  353. w.obuf[len(magicChunk)+4] = uint8(checksum >> 0)
  354. w.obuf[len(magicChunk)+5] = uint8(checksum >> 8)
  355. w.obuf[len(magicChunk)+6] = uint8(checksum >> 16)
  356. w.obuf[len(magicChunk)+7] = uint8(checksum >> 24)
  357. if _, err := w.w.Write(w.obuf[obufStart:obufEnd]); err != nil {
  358. w.err = err
  359. return nRet, err
  360. }
  361. if chunkType == chunkTypeUncompressedData {
  362. if _, err := w.w.Write(uncompressed); err != nil {
  363. w.err = err
  364. return nRet, err
  365. }
  366. }
  367. nRet += len(uncompressed)
  368. }
  369. return nRet, nil
  370. }
  371. // Flush flushes the Writer to its underlying io.Writer.
  372. func (w *Writer) Flush() error {
  373. if w.err != nil {
  374. return w.err
  375. }
  376. if len(w.ibuf) == 0 {
  377. return nil
  378. }
  379. w.write(w.ibuf)
  380. w.ibuf = w.ibuf[:0]
  381. return w.err
  382. }
  383. // Close calls Flush and then closes the Writer.
  384. func (w *Writer) Close() error {
  385. w.Flush()
  386. ret := w.err
  387. if w.err == nil {
  388. w.err = errClosed
  389. }
  390. return ret
  391. }