encode.go 16 KB

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