encode.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357
  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 int) 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. // It is valid to pass a nil dst.
  76. func Encode(dst, src []byte) []byte {
  77. if n := MaxEncodedLen(len(src)); len(dst) < n {
  78. dst = make([]byte, n)
  79. }
  80. // The block starts with the varint-encoded length of the decompressed bytes.
  81. d := binary.PutUvarint(dst, uint64(len(src)))
  82. // Return early if src is short.
  83. if len(src) <= 4 {
  84. if len(src) != 0 {
  85. d += emitLiteral(dst[d:], src)
  86. }
  87. return dst[:d]
  88. }
  89. // Initialize the hash table. Its size ranges from 1<<8 to 1<<14 inclusive.
  90. const maxTableSize = 1 << 14
  91. shift, tableSize := uint(32-8), 1<<8
  92. for tableSize < maxTableSize && tableSize < len(src) {
  93. shift--
  94. tableSize *= 2
  95. }
  96. var table [maxTableSize]int
  97. // Iterate over the source bytes.
  98. var (
  99. s int // The iterator position.
  100. t int // The last position with the same hash as s.
  101. lit int // The start position of any pending literal bytes.
  102. )
  103. for s+3 < len(src) {
  104. // Update the hash table.
  105. b0, b1, b2, b3 := src[s], src[s+1], src[s+2], src[s+3]
  106. h := uint32(b0) | uint32(b1)<<8 | uint32(b2)<<16 | uint32(b3)<<24
  107. p := &table[(h*0x1e35a7bd)>>shift]
  108. // We need to to store values in [-1, inf) in table. To save
  109. // some initialization time, (re)use the table's zero value
  110. // and shift the values against this zero: add 1 on writes,
  111. // subtract 1 on reads.
  112. t, *p = *p-1, s+1
  113. // If t is invalid or src[s:s+4] differs from src[t:t+4], accumulate a literal byte.
  114. if t < 0 || s-t >= maxOffset || b0 != src[t] || b1 != src[t+1] || b2 != src[t+2] || b3 != src[t+3] {
  115. // Skip multiple bytes if the last match was >= 32 bytes prior.
  116. s += 1 + (s-lit)>>5
  117. continue
  118. }
  119. // Otherwise, we have a match. First, emit any pending literal bytes.
  120. if lit != s {
  121. d += emitLiteral(dst[d:], src[lit:s])
  122. }
  123. // Extend the match to be as long as possible.
  124. s0 := s
  125. s, t = s+4, t+4
  126. for s < len(src) && src[s] == src[t] {
  127. s++
  128. t++
  129. }
  130. // Emit the copied bytes.
  131. d += emitCopy(dst[d:], s-t, s-s0)
  132. lit = s
  133. }
  134. // Emit any final pending literal bytes and return.
  135. if lit != len(src) {
  136. d += emitLiteral(dst[d:], src[lit:])
  137. }
  138. return dst[:d]
  139. }
  140. // MaxEncodedLen returns the maximum length of a snappy block, given its
  141. // uncompressed length.
  142. func MaxEncodedLen(srcLen int) int {
  143. // Compressed data can be defined as:
  144. // compressed := item* literal*
  145. // item := literal* copy
  146. //
  147. // The trailing literal sequence has a space blowup of at most 62/60
  148. // since a literal of length 60 needs one tag byte + one extra byte
  149. // for length information.
  150. //
  151. // Item blowup is trickier to measure. Suppose the "copy" op copies
  152. // 4 bytes of data. Because of a special check in the encoding code,
  153. // we produce a 4-byte copy only if the offset is < 65536. Therefore
  154. // the copy op takes 3 bytes to encode, and this type of item leads
  155. // to at most the 62/60 blowup for representing literals.
  156. //
  157. // Suppose the "copy" op copies 5 bytes of data. If the offset is big
  158. // enough, it will take 5 bytes to encode the copy op. Therefore the
  159. // worst case here is a one-byte literal followed by a five-byte copy.
  160. // That is, 6 bytes of input turn into 7 bytes of "compressed" data.
  161. //
  162. // This last factor dominates the blowup, so the final estimate is:
  163. return 32 + srcLen + srcLen/6
  164. }
  165. var errClosed = errors.New("snappy: Writer is closed")
  166. // NewWriter returns a new Writer that compresses to w.
  167. //
  168. // The Writer returned does not buffer writes. There is no need to Flush or
  169. // Close such a Writer.
  170. //
  171. // Deprecated: the Writer returned is not suitable for many small writes, only
  172. // for few large writes. Use NewBufferedWriter instead, which is efficient
  173. // regardless of the frequency and shape of the writes, and remember to Close
  174. // that Writer when done.
  175. func NewWriter(w io.Writer) *Writer {
  176. return &Writer{
  177. w: w,
  178. obuf: make([]byte, MaxEncodedLen(maxUncompressedChunkLen)),
  179. }
  180. }
  181. // NewBufferedWriter returns a new Writer that compresses to w, using the
  182. // framing format described at
  183. // https://github.com/google/snappy/blob/master/framing_format.txt
  184. //
  185. // The Writer returned buffers writes. Users must call Close to guarantee all
  186. // data has been forwarded to the underlying io.Writer. They may also call
  187. // Flush zero or more times before calling Close.
  188. func NewBufferedWriter(w io.Writer) *Writer {
  189. return &Writer{
  190. w: w,
  191. ibuf: make([]byte, 0, maxUncompressedChunkLen),
  192. obuf: make([]byte, MaxEncodedLen(maxUncompressedChunkLen)),
  193. }
  194. }
  195. // Writer is an io.Writer than can write Snappy-compressed bytes.
  196. type Writer struct {
  197. w io.Writer
  198. err error
  199. // ibuf is a buffer for the incoming (uncompressed) bytes.
  200. //
  201. // Its use is optional. For backwards compatibility, Writers created by the
  202. // NewWriter function have ibuf == nil, do not buffer incoming bytes, and
  203. // therefore do not need to be Flush'ed or Close'd.
  204. ibuf []byte
  205. // obuf is a buffer for the outgoing (compressed) bytes.
  206. obuf []byte
  207. // chunkHeaderBuf is a buffer for the per-chunk header (chunk type, length
  208. // and checksum), not to be confused with the magic string that forms the
  209. // stream header.
  210. chunkHeaderBuf [checksumSize + chunkHeaderSize]byte
  211. // wroteStreamHeader is whether we have written the stream header.
  212. wroteStreamHeader bool
  213. }
  214. // Reset discards the writer's state and switches the Snappy writer to write to
  215. // w. This permits reusing a Writer rather than allocating a new one.
  216. func (w *Writer) Reset(writer io.Writer) {
  217. w.w = writer
  218. w.err = nil
  219. if w.ibuf != nil {
  220. w.ibuf = w.ibuf[:0]
  221. }
  222. w.wroteStreamHeader = false
  223. }
  224. // Write satisfies the io.Writer interface.
  225. func (w *Writer) Write(p []byte) (nRet int, errRet error) {
  226. if w.ibuf == nil {
  227. // Do not buffer incoming bytes. This does not perform or compress well
  228. // if the caller of Writer.Write writes many small slices. This
  229. // behavior is therefore deprecated, but still supported for backwards
  230. // compatibility with code that doesn't explicitly Flush or Close.
  231. return w.write(p)
  232. }
  233. // The remainder of this method is based on bufio.Writer.Write from the
  234. // standard library.
  235. for len(p) > (cap(w.ibuf)-len(w.ibuf)) && w.err == nil {
  236. var n int
  237. if len(w.ibuf) == 0 {
  238. // Large write, empty buffer.
  239. // Write directly from p to avoid copy.
  240. n, _ = w.write(p)
  241. } else {
  242. n = copy(w.ibuf[len(w.ibuf):cap(w.ibuf)], p)
  243. w.ibuf = w.ibuf[:len(w.ibuf)+n]
  244. w.Flush()
  245. }
  246. nRet += n
  247. p = p[n:]
  248. }
  249. if w.err != nil {
  250. return nRet, w.err
  251. }
  252. n := copy(w.ibuf[len(w.ibuf):cap(w.ibuf)], p)
  253. w.ibuf = w.ibuf[:len(w.ibuf)+n]
  254. nRet += n
  255. return nRet, nil
  256. }
  257. func (w *Writer) write(p []byte) (nRet int, errRet error) {
  258. if w.err != nil {
  259. return 0, w.err
  260. }
  261. if !w.wroteStreamHeader {
  262. if copy(w.obuf, magicChunk) != len(magicChunk) {
  263. panic("unreachable")
  264. }
  265. if _, err := w.w.Write(w.obuf[:len(magicChunk)]); err != nil {
  266. w.err = err
  267. return nRet, err
  268. }
  269. w.wroteStreamHeader = true
  270. }
  271. for len(p) > 0 {
  272. var uncompressed []byte
  273. if len(p) > maxUncompressedChunkLen {
  274. uncompressed, p = p[:maxUncompressedChunkLen], p[maxUncompressedChunkLen:]
  275. } else {
  276. uncompressed, p = p, nil
  277. }
  278. checksum := crc(uncompressed)
  279. // Compress the buffer, discarding the result if the improvement
  280. // isn't at least 12.5%.
  281. chunkType := uint8(chunkTypeCompressedData)
  282. chunkBody := Encode(w.obuf, uncompressed)
  283. if len(chunkBody) >= len(uncompressed)-len(uncompressed)/8 {
  284. chunkType, chunkBody = chunkTypeUncompressedData, uncompressed
  285. }
  286. chunkLen := 4 + len(chunkBody)
  287. w.chunkHeaderBuf[0] = chunkType
  288. w.chunkHeaderBuf[1] = uint8(chunkLen >> 0)
  289. w.chunkHeaderBuf[2] = uint8(chunkLen >> 8)
  290. w.chunkHeaderBuf[3] = uint8(chunkLen >> 16)
  291. w.chunkHeaderBuf[4] = uint8(checksum >> 0)
  292. w.chunkHeaderBuf[5] = uint8(checksum >> 8)
  293. w.chunkHeaderBuf[6] = uint8(checksum >> 16)
  294. w.chunkHeaderBuf[7] = uint8(checksum >> 24)
  295. if _, err := w.w.Write(w.chunkHeaderBuf[:]); err != nil {
  296. w.err = err
  297. return nRet, err
  298. }
  299. if _, err := w.w.Write(chunkBody); err != nil {
  300. w.err = err
  301. return nRet, err
  302. }
  303. nRet += len(uncompressed)
  304. }
  305. return nRet, nil
  306. }
  307. // Flush flushes the Writer to its underlying io.Writer.
  308. func (w *Writer) Flush() error {
  309. if w.err != nil {
  310. return w.err
  311. }
  312. if len(w.ibuf) == 0 {
  313. return nil
  314. }
  315. w.write(w.ibuf)
  316. w.ibuf = w.ibuf[:0]
  317. return w.err
  318. }
  319. // Close calls Flush and then closes the Writer.
  320. func (w *Writer) Close() error {
  321. w.Flush()
  322. ret := w.err
  323. if w.err == nil {
  324. w.err = errClosed
  325. }
  326. return ret
  327. }