encode.go 17 KB

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