encode.go 16 KB

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