encode.go 12 KB

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