You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

403 lines
12 KiB

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