encode.go 14 KB

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