encode.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423
  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 int32) 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. // emitLiteral writes a literal chunk and returns the number of bytes written.
  18. func emitLiteral(dst, lit []byte) int {
  19. i, n := 0, uint(len(lit)-1)
  20. switch {
  21. case n < 60:
  22. dst[0] = uint8(n)<<2 | tagLiteral
  23. i = 1
  24. case n < 1<<8:
  25. dst[0] = 60<<2 | tagLiteral
  26. dst[1] = uint8(n)
  27. i = 2
  28. case n < 1<<16:
  29. dst[0] = 61<<2 | tagLiteral
  30. dst[1] = uint8(n)
  31. dst[2] = uint8(n >> 8)
  32. i = 3
  33. case n < 1<<24:
  34. dst[0] = 62<<2 | tagLiteral
  35. dst[1] = uint8(n)
  36. dst[2] = uint8(n >> 8)
  37. dst[3] = uint8(n >> 16)
  38. i = 4
  39. case int64(n) < 1<<32:
  40. dst[0] = 63<<2 | tagLiteral
  41. dst[1] = uint8(n)
  42. dst[2] = uint8(n >> 8)
  43. dst[3] = uint8(n >> 16)
  44. dst[4] = uint8(n >> 24)
  45. i = 5
  46. default:
  47. panic("snappy: source buffer is too long")
  48. }
  49. if copy(dst[i:], lit) != len(lit) {
  50. panic("snappy: destination buffer is too short")
  51. }
  52. return i + len(lit)
  53. }
  54. // emitCopy writes a copy chunk and returns the number of bytes written.
  55. func emitCopy(dst []byte, offset, length int32) int {
  56. i := 0
  57. // The maximum length for a single tagCopy1 or tagCopy2 op is 64 bytes. The
  58. // threshold for this loop is a little higher (at 68 = 64 + 4), and the
  59. // length emitted down below is is a little lower (at 60 = 64 - 4), because
  60. // it's shorter to encode a length 67 copy as a length 60 tagCopy2 followed
  61. // by a length 7 tagCopy1 (which encodes as 3+2 bytes) than to encode it as
  62. // a length 64 tagCopy2 followed by a length 3 tagCopy2 (which encodes as
  63. // 3+3 bytes). The magic 4 in the 64±4 is because the minimum length for a
  64. // tagCopy1 op is 4 bytes, which is why a length 3 copy has to be an
  65. // encodes-as-3-bytes tagCopy2 instead of an encodes-as-2-bytes tagCopy1.
  66. for length >= 68 {
  67. // Emit a length 64 copy, encoded as 3 bytes.
  68. dst[i+0] = 63<<2 | tagCopy2
  69. dst[i+1] = uint8(offset)
  70. dst[i+2] = uint8(offset >> 8)
  71. i += 3
  72. length -= 64
  73. }
  74. if length > 64 {
  75. // Emit a length 60 copy, encoded as 3 bytes.
  76. dst[i+0] = 59<<2 | tagCopy2
  77. dst[i+1] = uint8(offset)
  78. dst[i+2] = uint8(offset >> 8)
  79. i += 3
  80. length -= 60
  81. }
  82. if length >= 12 || offset >= 2048 {
  83. // Emit the remaining copy, encoded as 3 bytes.
  84. dst[i+0] = uint8(length-1)<<2 | tagCopy2
  85. dst[i+1] = uint8(offset)
  86. dst[i+2] = uint8(offset >> 8)
  87. return i + 3
  88. }
  89. // Emit the remaining copy, encoded as 2 bytes.
  90. dst[i+0] = uint8(offset>>8)<<5 | uint8(length-4)<<2 | tagCopy1
  91. dst[i+1] = uint8(offset)
  92. return i + 2
  93. }
  94. // Encode returns the encoded form of src. The returned slice may be a sub-
  95. // slice of dst if dst was large enough to hold the entire encoded block.
  96. // Otherwise, a newly allocated slice will be returned.
  97. //
  98. // It is valid to pass a nil dst.
  99. func Encode(dst, src []byte) []byte {
  100. if n := MaxEncodedLen(len(src)); n < 0 {
  101. panic(ErrTooLarge)
  102. } else if len(dst) < n {
  103. dst = make([]byte, n)
  104. }
  105. // The block starts with the varint-encoded length of the decompressed bytes.
  106. d := binary.PutUvarint(dst, uint64(len(src)))
  107. for len(src) > 0 {
  108. p := src
  109. src = nil
  110. if len(p) > maxBlockSize {
  111. p, src = p[:maxBlockSize], p[maxBlockSize:]
  112. }
  113. d += encodeBlock(dst[d:], p)
  114. }
  115. return dst[:d]
  116. }
  117. // encodeBlock encodes a non-empty src to a guaranteed-large-enough dst. It
  118. // assumes that the varint-encoded length of the decompressed bytes has already
  119. // been written.
  120. //
  121. // It also assumes that:
  122. // len(dst) >= MaxEncodedLen(len(src)) &&
  123. // 0 < len(src) && len(src) <= maxBlockSize
  124. func encodeBlock(dst, src []byte) (d int) {
  125. // Return early if src is short.
  126. if len(src) <= 4 {
  127. return emitLiteral(dst, src)
  128. }
  129. // Initialize the hash table. Its size ranges from 1<<8 to 1<<14 inclusive.
  130. const maxTableSize = 1 << 14
  131. shift, tableSize := uint(32-8), 1<<8
  132. for tableSize < maxTableSize && tableSize < len(src) {
  133. shift--
  134. tableSize *= 2
  135. }
  136. var table [maxTableSize]int32
  137. // Iterate over the source bytes.
  138. var (
  139. s int32 // The iterator position.
  140. t int32 // The last position with the same hash as s.
  141. lit int32 // The start position of any pending literal bytes.
  142. // Copied from the C++ snappy implementation:
  143. //
  144. // Heuristic match skipping: If 32 bytes are scanned with no matches
  145. // found, start looking only at every other byte. If 32 more bytes are
  146. // scanned, look at every third byte, etc.. When a match is found,
  147. // immediately go back to looking at every byte. This is a small loss
  148. // (~5% performance, ~0.1% density) for compressible data due to more
  149. // bookkeeping, but for non-compressible data (such as JPEG) it's a
  150. // huge win since the compressor quickly "realizes" the data is
  151. // incompressible and doesn't bother looking for matches everywhere.
  152. //
  153. // The "skip" variable keeps track of how many bytes there are since
  154. // the last match; dividing it by 32 (ie. right-shifting by five) gives
  155. // the number of bytes to move ahead for each iteration.
  156. skip uint32 = 32
  157. )
  158. for uint32(s+3) < uint32(len(src)) { // The uint32 conversions catch overflow from the +3.
  159. // Update the hash table.
  160. h := load32(src, s)
  161. p := &table[(h*0x1e35a7bd)>>shift]
  162. // We need to to store values in [-1, inf) in table. To save
  163. // some initialization time, (re)use the table's zero value
  164. // and shift the values against this zero: add 1 on writes,
  165. // subtract 1 on reads.
  166. t, *p = *p-1, s+1
  167. // If t is invalid or src[s:s+4] differs from src[t:t+4], accumulate a literal byte.
  168. if t < 0 || s-t >= maxOffset || h != load32(src, t) {
  169. s += int32(skip >> 5)
  170. skip++
  171. continue
  172. }
  173. skip = 32
  174. // Otherwise, we have a match. First, emit any pending literal bytes.
  175. if lit != s {
  176. d += emitLiteral(dst[d:], src[lit:s])
  177. }
  178. // Extend the match to be as long as possible.
  179. s0 := s
  180. s, t = s+4, t+4
  181. for int(s) < len(src) && src[s] == src[t] {
  182. s++
  183. t++
  184. }
  185. // Emit the copied bytes.
  186. d += emitCopy(dst[d:], s-t, s-s0)
  187. lit = s
  188. }
  189. // Emit any final pending literal bytes and return.
  190. if int(lit) != len(src) {
  191. d += emitLiteral(dst[d:], src[lit:])
  192. }
  193. return d
  194. }
  195. // MaxEncodedLen returns the maximum length of a snappy block, given its
  196. // uncompressed length.
  197. //
  198. // It will return a negative value if srcLen is too large to encode.
  199. func MaxEncodedLen(srcLen int) int {
  200. n := uint64(srcLen)
  201. if n > 0xffffffff {
  202. return -1
  203. }
  204. // Compressed data can be defined as:
  205. // compressed := item* literal*
  206. // item := literal* copy
  207. //
  208. // The trailing literal sequence has a space blowup of at most 62/60
  209. // since a literal of length 60 needs one tag byte + one extra byte
  210. // for length information.
  211. //
  212. // Item blowup is trickier to measure. Suppose the "copy" op copies
  213. // 4 bytes of data. Because of a special check in the encoding code,
  214. // we produce a 4-byte copy only if the offset is < 65536. Therefore
  215. // the copy op takes 3 bytes to encode, and this type of item leads
  216. // to at most the 62/60 blowup for representing literals.
  217. //
  218. // Suppose the "copy" op copies 5 bytes of data. If the offset is big
  219. // enough, it will take 5 bytes to encode the copy op. Therefore the
  220. // worst case here is a one-byte literal followed by a five-byte copy.
  221. // That is, 6 bytes of input turn into 7 bytes of "compressed" data.
  222. //
  223. // This last factor dominates the blowup, so the final estimate is:
  224. n = 32 + n + n/6
  225. if n > 0xffffffff {
  226. return -1
  227. }
  228. return int(n)
  229. }
  230. var errClosed = errors.New("snappy: Writer is closed")
  231. // NewWriter returns a new Writer that compresses to w.
  232. //
  233. // The Writer returned does not buffer writes. There is no need to Flush or
  234. // Close such a Writer.
  235. //
  236. // Deprecated: the Writer returned is not suitable for many small writes, only
  237. // for few large writes. Use NewBufferedWriter instead, which is efficient
  238. // regardless of the frequency and shape of the writes, and remember to Close
  239. // that Writer when done.
  240. func NewWriter(w io.Writer) *Writer {
  241. return &Writer{
  242. w: w,
  243. obuf: make([]byte, obufLen),
  244. }
  245. }
  246. // NewBufferedWriter returns a new Writer that compresses to w, using the
  247. // framing format described at
  248. // https://github.com/google/snappy/blob/master/framing_format.txt
  249. //
  250. // The Writer returned buffers writes. Users must call Close to guarantee all
  251. // data has been forwarded to the underlying io.Writer. They may also call
  252. // Flush zero or more times before calling Close.
  253. func NewBufferedWriter(w io.Writer) *Writer {
  254. return &Writer{
  255. w: w,
  256. ibuf: make([]byte, 0, maxBlockSize),
  257. obuf: make([]byte, obufLen),
  258. }
  259. }
  260. // Writer is an io.Writer than can write Snappy-compressed bytes.
  261. type Writer struct {
  262. w io.Writer
  263. err error
  264. // ibuf is a buffer for the incoming (uncompressed) bytes.
  265. //
  266. // Its use is optional. For backwards compatibility, Writers created by the
  267. // NewWriter function have ibuf == nil, do not buffer incoming bytes, and
  268. // therefore do not need to be Flush'ed or Close'd.
  269. ibuf []byte
  270. // obuf is a buffer for the outgoing (compressed) bytes.
  271. obuf []byte
  272. // wroteStreamHeader is whether we have written the stream header.
  273. wroteStreamHeader bool
  274. }
  275. // Reset discards the writer's state and switches the Snappy writer to write to
  276. // w. This permits reusing a Writer rather than allocating a new one.
  277. func (w *Writer) Reset(writer io.Writer) {
  278. w.w = writer
  279. w.err = nil
  280. if w.ibuf != nil {
  281. w.ibuf = w.ibuf[:0]
  282. }
  283. w.wroteStreamHeader = false
  284. }
  285. // Write satisfies the io.Writer interface.
  286. func (w *Writer) Write(p []byte) (nRet int, errRet error) {
  287. if w.ibuf == nil {
  288. // Do not buffer incoming bytes. This does not perform or compress well
  289. // if the caller of Writer.Write writes many small slices. This
  290. // behavior is therefore deprecated, but still supported for backwards
  291. // compatibility with code that doesn't explicitly Flush or Close.
  292. return w.write(p)
  293. }
  294. // The remainder of this method is based on bufio.Writer.Write from the
  295. // standard library.
  296. for len(p) > (cap(w.ibuf)-len(w.ibuf)) && w.err == nil {
  297. var n int
  298. if len(w.ibuf) == 0 {
  299. // Large write, empty buffer.
  300. // Write directly from p to avoid copy.
  301. n, _ = w.write(p)
  302. } else {
  303. n = copy(w.ibuf[len(w.ibuf):cap(w.ibuf)], p)
  304. w.ibuf = w.ibuf[:len(w.ibuf)+n]
  305. w.Flush()
  306. }
  307. nRet += n
  308. p = p[n:]
  309. }
  310. if w.err != nil {
  311. return nRet, w.err
  312. }
  313. n := copy(w.ibuf[len(w.ibuf):cap(w.ibuf)], p)
  314. w.ibuf = w.ibuf[:len(w.ibuf)+n]
  315. nRet += n
  316. return nRet, nil
  317. }
  318. func (w *Writer) write(p []byte) (nRet int, errRet error) {
  319. if w.err != nil {
  320. return 0, w.err
  321. }
  322. for len(p) > 0 {
  323. obufStart := len(magicChunk)
  324. if !w.wroteStreamHeader {
  325. w.wroteStreamHeader = true
  326. copy(w.obuf, magicChunk)
  327. obufStart = 0
  328. }
  329. var uncompressed []byte
  330. if len(p) > maxBlockSize {
  331. uncompressed, p = p[:maxBlockSize], p[maxBlockSize:]
  332. } else {
  333. uncompressed, p = p, nil
  334. }
  335. checksum := crc(uncompressed)
  336. // Compress the buffer, discarding the result if the improvement
  337. // isn't at least 12.5%.
  338. compressed := Encode(w.obuf[obufHeaderLen:], uncompressed)
  339. chunkType := uint8(chunkTypeCompressedData)
  340. chunkLen := 4 + len(compressed)
  341. obufEnd := obufHeaderLen + len(compressed)
  342. if len(compressed) >= len(uncompressed)-len(uncompressed)/8 {
  343. chunkType = chunkTypeUncompressedData
  344. chunkLen = 4 + len(uncompressed)
  345. obufEnd = obufHeaderLen
  346. }
  347. // Fill in the per-chunk header that comes before the body.
  348. w.obuf[len(magicChunk)+0] = chunkType
  349. w.obuf[len(magicChunk)+1] = uint8(chunkLen >> 0)
  350. w.obuf[len(magicChunk)+2] = uint8(chunkLen >> 8)
  351. w.obuf[len(magicChunk)+3] = uint8(chunkLen >> 16)
  352. w.obuf[len(magicChunk)+4] = uint8(checksum >> 0)
  353. w.obuf[len(magicChunk)+5] = uint8(checksum >> 8)
  354. w.obuf[len(magicChunk)+6] = uint8(checksum >> 16)
  355. w.obuf[len(magicChunk)+7] = uint8(checksum >> 24)
  356. if _, err := w.w.Write(w.obuf[obufStart:obufEnd]); err != nil {
  357. w.err = err
  358. return nRet, err
  359. }
  360. if chunkType == chunkTypeUncompressedData {
  361. if _, err := w.w.Write(uncompressed); err != nil {
  362. w.err = err
  363. return nRet, err
  364. }
  365. }
  366. nRet += len(uncompressed)
  367. }
  368. return nRet, nil
  369. }
  370. // Flush flushes the Writer to its underlying io.Writer.
  371. func (w *Writer) Flush() error {
  372. if w.err != nil {
  373. return w.err
  374. }
  375. if len(w.ibuf) == 0 {
  376. return nil
  377. }
  378. w.write(w.ibuf)
  379. w.ibuf = w.ibuf[:0]
  380. return w.err
  381. }
  382. // Close calls Flush and then closes the Writer.
  383. func (w *Writer) Close() error {
  384. w.Flush()
  385. ret := w.err
  386. if w.err == nil {
  387. w.err = errClosed
  388. }
  389. return ret
  390. }