encode.go 14 KB

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