encode.go 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289
  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. // Encode returns the encoded form of src. The returned slice may be a sub-
  11. // slice of dst if dst was large enough to hold the entire encoded block.
  12. // Otherwise, a newly allocated slice will be returned.
  13. //
  14. // The dst and src must not overlap. It is valid to pass a nil dst.
  15. //
  16. // Encode handles the Snappy block format, not the Snappy stream format.
  17. func Encode(dst, src []byte) []byte {
  18. if n := MaxEncodedLen(len(src)); n < 0 {
  19. panic(ErrTooLarge)
  20. } else if len(dst) < n {
  21. dst = make([]byte, n)
  22. }
  23. // The block starts with the varint-encoded length of the decompressed bytes.
  24. d := binary.PutUvarint(dst, uint64(len(src)))
  25. for len(src) > 0 {
  26. p := src
  27. src = nil
  28. if len(p) > maxBlockSize {
  29. p, src = p[:maxBlockSize], p[maxBlockSize:]
  30. }
  31. if len(p) < minNonLiteralBlockSize {
  32. d += emitLiteral(dst[d:], p)
  33. } else {
  34. d += encodeBlock(dst[d:], p)
  35. }
  36. }
  37. return dst[:d]
  38. }
  39. // inputMargin is the minimum number of extra input bytes to keep, inside
  40. // encodeBlock's inner loop. On some architectures, this margin lets us
  41. // implement a fast path for emitLiteral, where the copy of short (<= 16 byte)
  42. // literals can be implemented as a single load to and store from a 16-byte
  43. // register. That literal's actual length can be as short as 1 byte, so this
  44. // can copy up to 15 bytes too much, but that's OK as subsequent iterations of
  45. // the encoding loop will fix up the copy overrun, and this inputMargin ensures
  46. // that we don't overrun the dst and src buffers.
  47. const inputMargin = 16 - 1
  48. // minNonLiteralBlockSize is the minimum size of the input to encodeBlock that
  49. // could be encoded with a copy tag. This is the minimum with respect to the
  50. // algorithm used by encodeBlock, not a minimum enforced by the file format.
  51. //
  52. // The encoded output must start with at least a 1 byte literal, as there are
  53. // no previous bytes to copy. A minimal (1 byte) copy after that, generated
  54. // from an emitCopy call in encodeBlock's main loop, would require at least
  55. // another inputMargin bytes, for the reason above: we want any emitLiteral
  56. // calls inside encodeBlock's main loop to use the fast path if possible, which
  57. // requires being able to overrun by inputMargin bytes. Thus,
  58. // minNonLiteralBlockSize equals 1 + 1 + inputMargin.
  59. //
  60. // The C++ code doesn't use this exact threshold, but it could, as discussed at
  61. // https://groups.google.com/d/topic/snappy-compression/oGbhsdIJSJ8/discussion
  62. // The difference between Go (2+inputMargin) and C++ (inputMargin) is purely an
  63. // optimization. It should not affect the encoded form. This is tested by
  64. // TestSameEncodingAsCppShortCopies.
  65. const minNonLiteralBlockSize = 1 + 1 + inputMargin
  66. // MaxEncodedLen returns the maximum length of a snappy block, given its
  67. // uncompressed length.
  68. //
  69. // It will return a negative value if srcLen is too large to encode.
  70. func MaxEncodedLen(srcLen int) int {
  71. n := uint64(srcLen)
  72. if n > 0xffffffff {
  73. return -1
  74. }
  75. // Compressed data can be defined as:
  76. // compressed := item* literal*
  77. // item := literal* copy
  78. //
  79. // The trailing literal sequence has a space blowup of at most 62/60
  80. // since a literal of length 60 needs one tag byte + one extra byte
  81. // for length information.
  82. //
  83. // Item blowup is trickier to measure. Suppose the "copy" op copies
  84. // 4 bytes of data. Because of a special check in the encoding code,
  85. // we produce a 4-byte copy only if the offset is < 65536. Therefore
  86. // the copy op takes 3 bytes to encode, and this type of item leads
  87. // to at most the 62/60 blowup for representing literals.
  88. //
  89. // Suppose the "copy" op copies 5 bytes of data. If the offset is big
  90. // enough, it will take 5 bytes to encode the copy op. Therefore the
  91. // worst case here is a one-byte literal followed by a five-byte copy.
  92. // That is, 6 bytes of input turn into 7 bytes of "compressed" data.
  93. //
  94. // This last factor dominates the blowup, so the final estimate is:
  95. n = 32 + n + n/6
  96. if n > 0xffffffff {
  97. return -1
  98. }
  99. return int(n)
  100. }
  101. var errClosed = errors.New("snappy: Writer is closed")
  102. // NewWriter returns a new Writer that compresses to w.
  103. //
  104. // The Writer returned does not buffer writes. There is no need to Flush or
  105. // Close such a Writer.
  106. //
  107. // Deprecated: the Writer returned is not suitable for many small writes, only
  108. // for few large writes. Use NewBufferedWriter instead, which is efficient
  109. // regardless of the frequency and shape of the writes, and remember to Close
  110. // that Writer when done.
  111. func NewWriter(w io.Writer) *Writer {
  112. return &Writer{
  113. w: w,
  114. obuf: make([]byte, obufLen),
  115. }
  116. }
  117. // NewBufferedWriter returns a new Writer that compresses to w, using the
  118. // framing format described at
  119. // https://github.com/google/snappy/blob/master/framing_format.txt
  120. //
  121. // The Writer returned buffers writes. Users must call Close to guarantee all
  122. // data has been forwarded to the underlying io.Writer. They may also call
  123. // Flush zero or more times before calling Close.
  124. func NewBufferedWriter(w io.Writer) *Writer {
  125. return &Writer{
  126. w: w,
  127. ibuf: make([]byte, 0, maxBlockSize),
  128. obuf: make([]byte, obufLen),
  129. }
  130. }
  131. // Writer is an io.Writer that can write Snappy-compressed bytes.
  132. //
  133. // Writer handles the Snappy stream format, not the Snappy block format.
  134. type Writer struct {
  135. w io.Writer
  136. err error
  137. // ibuf is a buffer for the incoming (uncompressed) bytes.
  138. //
  139. // Its use is optional. For backwards compatibility, Writers created by the
  140. // NewWriter function have ibuf == nil, do not buffer incoming bytes, and
  141. // therefore do not need to be Flush'ed or Close'd.
  142. ibuf []byte
  143. // obuf is a buffer for the outgoing (compressed) bytes.
  144. obuf []byte
  145. // wroteStreamHeader is whether we have written the stream header.
  146. wroteStreamHeader bool
  147. }
  148. // Reset discards the writer's state and switches the Snappy writer to write to
  149. // w. This permits reusing a Writer rather than allocating a new one.
  150. func (w *Writer) Reset(writer io.Writer) {
  151. w.w = writer
  152. w.err = nil
  153. if w.ibuf != nil {
  154. w.ibuf = w.ibuf[:0]
  155. }
  156. w.wroteStreamHeader = false
  157. }
  158. // Write satisfies the io.Writer interface.
  159. func (w *Writer) Write(p []byte) (nRet int, errRet error) {
  160. if w.ibuf == nil {
  161. // Do not buffer incoming bytes. This does not perform or compress well
  162. // if the caller of Writer.Write writes many small slices. This
  163. // behavior is therefore deprecated, but still supported for backwards
  164. // compatibility with code that doesn't explicitly Flush or Close.
  165. return w.write(p)
  166. }
  167. // The remainder of this method is based on bufio.Writer.Write from the
  168. // standard library.
  169. for len(p) > (cap(w.ibuf)-len(w.ibuf)) && w.err == nil {
  170. var n int
  171. if len(w.ibuf) == 0 {
  172. // Large write, empty buffer.
  173. // Write directly from p to avoid copy.
  174. n, _ = w.write(p)
  175. } else {
  176. n = copy(w.ibuf[len(w.ibuf):cap(w.ibuf)], p)
  177. w.ibuf = w.ibuf[:len(w.ibuf)+n]
  178. w.Flush()
  179. }
  180. nRet += n
  181. p = p[n:]
  182. }
  183. if w.err != nil {
  184. return nRet, w.err
  185. }
  186. n := copy(w.ibuf[len(w.ibuf):cap(w.ibuf)], p)
  187. w.ibuf = w.ibuf[:len(w.ibuf)+n]
  188. nRet += n
  189. return nRet, nil
  190. }
  191. func (w *Writer) write(p []byte) (nRet int, errRet error) {
  192. if w.err != nil {
  193. return 0, w.err
  194. }
  195. for len(p) > 0 {
  196. obufStart := len(magicChunk)
  197. if !w.wroteStreamHeader {
  198. w.wroteStreamHeader = true
  199. copy(w.obuf, magicChunk)
  200. obufStart = 0
  201. }
  202. var uncompressed []byte
  203. if len(p) > maxBlockSize {
  204. uncompressed, p = p[:maxBlockSize], p[maxBlockSize:]
  205. } else {
  206. uncompressed, p = p, nil
  207. }
  208. checksum := crc(uncompressed)
  209. // Compress the buffer, discarding the result if the improvement
  210. // isn't at least 12.5%.
  211. compressed := Encode(w.obuf[obufHeaderLen:], uncompressed)
  212. chunkType := uint8(chunkTypeCompressedData)
  213. chunkLen := 4 + len(compressed)
  214. obufEnd := obufHeaderLen + len(compressed)
  215. if len(compressed) >= len(uncompressed)-len(uncompressed)/8 {
  216. chunkType = chunkTypeUncompressedData
  217. chunkLen = 4 + len(uncompressed)
  218. obufEnd = obufHeaderLen
  219. }
  220. // Fill in the per-chunk header that comes before the body.
  221. w.obuf[len(magicChunk)+0] = chunkType
  222. w.obuf[len(magicChunk)+1] = uint8(chunkLen >> 0)
  223. w.obuf[len(magicChunk)+2] = uint8(chunkLen >> 8)
  224. w.obuf[len(magicChunk)+3] = uint8(chunkLen >> 16)
  225. w.obuf[len(magicChunk)+4] = uint8(checksum >> 0)
  226. w.obuf[len(magicChunk)+5] = uint8(checksum >> 8)
  227. w.obuf[len(magicChunk)+6] = uint8(checksum >> 16)
  228. w.obuf[len(magicChunk)+7] = uint8(checksum >> 24)
  229. if _, err := w.w.Write(w.obuf[obufStart:obufEnd]); err != nil {
  230. w.err = err
  231. return nRet, err
  232. }
  233. if chunkType == chunkTypeUncompressedData {
  234. if _, err := w.w.Write(uncompressed); err != nil {
  235. w.err = err
  236. return nRet, err
  237. }
  238. }
  239. nRet += len(uncompressed)
  240. }
  241. return nRet, nil
  242. }
  243. // Flush flushes the Writer to its underlying io.Writer.
  244. func (w *Writer) Flush() error {
  245. if w.err != nil {
  246. return w.err
  247. }
  248. if len(w.ibuf) == 0 {
  249. return nil
  250. }
  251. w.write(w.ibuf)
  252. w.ibuf = w.ibuf[:0]
  253. return w.err
  254. }
  255. // Close calls Flush and then closes the Writer.
  256. func (w *Writer) Close() error {
  257. w.Flush()
  258. ret := w.err
  259. if w.err == nil {
  260. w.err = errClosed
  261. }
  262. return ret
  263. }