encode.go 16 KB

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