encode.go 12 KB

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