encode.go 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287
  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. func Encode(dst, src []byte) []byte {
  16. if n := MaxEncodedLen(len(src)); n < 0 {
  17. panic(ErrTooLarge)
  18. } else if len(dst) < n {
  19. dst = make([]byte, n)
  20. }
  21. // The block starts with the varint-encoded length of the decompressed bytes.
  22. d := binary.PutUvarint(dst, uint64(len(src)))
  23. for len(src) > 0 {
  24. p := src
  25. src = nil
  26. if len(p) > maxBlockSize {
  27. p, src = p[:maxBlockSize], p[maxBlockSize:]
  28. }
  29. if len(p) < minNonLiteralBlockSize {
  30. d += emitLiteral(dst[d:], p)
  31. } else {
  32. d += encodeBlock(dst[d:], p)
  33. }
  34. }
  35. return dst[:d]
  36. }
  37. // inputMargin is the minimum number of extra input bytes to keep, inside
  38. // encodeBlock's inner loop. On some architectures, this margin lets us
  39. // implement a fast path for emitLiteral, where the copy of short (<= 16 byte)
  40. // literals can be implemented as a single load to and store from a 16-byte
  41. // register. That literal's actual length can be as short as 1 byte, so this
  42. // can copy up to 15 bytes too much, but that's OK as subsequent iterations of
  43. // the encoding loop will fix up the copy overrun, and this inputMargin ensures
  44. // that we don't overrun the dst and src buffers.
  45. //
  46. // TODO: implement this fast path.
  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 than can write Snappy-compressed bytes.
  132. type Writer struct {
  133. w io.Writer
  134. err error
  135. // ibuf is a buffer for the incoming (uncompressed) bytes.
  136. //
  137. // Its use is optional. For backwards compatibility, Writers created by the
  138. // NewWriter function have ibuf == nil, do not buffer incoming bytes, and
  139. // therefore do not need to be Flush'ed or Close'd.
  140. ibuf []byte
  141. // obuf is a buffer for the outgoing (compressed) bytes.
  142. obuf []byte
  143. // wroteStreamHeader is whether we have written the stream header.
  144. wroteStreamHeader bool
  145. }
  146. // Reset discards the writer's state and switches the Snappy writer to write to
  147. // w. This permits reusing a Writer rather than allocating a new one.
  148. func (w *Writer) Reset(writer io.Writer) {
  149. w.w = writer
  150. w.err = nil
  151. if w.ibuf != nil {
  152. w.ibuf = w.ibuf[:0]
  153. }
  154. w.wroteStreamHeader = false
  155. }
  156. // Write satisfies the io.Writer interface.
  157. func (w *Writer) Write(p []byte) (nRet int, errRet error) {
  158. if w.ibuf == nil {
  159. // Do not buffer incoming bytes. This does not perform or compress well
  160. // if the caller of Writer.Write writes many small slices. This
  161. // behavior is therefore deprecated, but still supported for backwards
  162. // compatibility with code that doesn't explicitly Flush or Close.
  163. return w.write(p)
  164. }
  165. // The remainder of this method is based on bufio.Writer.Write from the
  166. // standard library.
  167. for len(p) > (cap(w.ibuf)-len(w.ibuf)) && w.err == nil {
  168. var n int
  169. if len(w.ibuf) == 0 {
  170. // Large write, empty buffer.
  171. // Write directly from p to avoid copy.
  172. n, _ = w.write(p)
  173. } else {
  174. n = copy(w.ibuf[len(w.ibuf):cap(w.ibuf)], p)
  175. w.ibuf = w.ibuf[:len(w.ibuf)+n]
  176. w.Flush()
  177. }
  178. nRet += n
  179. p = p[n:]
  180. }
  181. if w.err != nil {
  182. return nRet, w.err
  183. }
  184. n := copy(w.ibuf[len(w.ibuf):cap(w.ibuf)], p)
  185. w.ibuf = w.ibuf[:len(w.ibuf)+n]
  186. nRet += n
  187. return nRet, nil
  188. }
  189. func (w *Writer) write(p []byte) (nRet int, errRet error) {
  190. if w.err != nil {
  191. return 0, w.err
  192. }
  193. for len(p) > 0 {
  194. obufStart := len(magicChunk)
  195. if !w.wroteStreamHeader {
  196. w.wroteStreamHeader = true
  197. copy(w.obuf, magicChunk)
  198. obufStart = 0
  199. }
  200. var uncompressed []byte
  201. if len(p) > maxBlockSize {
  202. uncompressed, p = p[:maxBlockSize], p[maxBlockSize:]
  203. } else {
  204. uncompressed, p = p, nil
  205. }
  206. checksum := crc(uncompressed)
  207. // Compress the buffer, discarding the result if the improvement
  208. // isn't at least 12.5%.
  209. compressed := Encode(w.obuf[obufHeaderLen:], uncompressed)
  210. chunkType := uint8(chunkTypeCompressedData)
  211. chunkLen := 4 + len(compressed)
  212. obufEnd := obufHeaderLen + len(compressed)
  213. if len(compressed) >= len(uncompressed)-len(uncompressed)/8 {
  214. chunkType = chunkTypeUncompressedData
  215. chunkLen = 4 + len(uncompressed)
  216. obufEnd = obufHeaderLen
  217. }
  218. // Fill in the per-chunk header that comes before the body.
  219. w.obuf[len(magicChunk)+0] = chunkType
  220. w.obuf[len(magicChunk)+1] = uint8(chunkLen >> 0)
  221. w.obuf[len(magicChunk)+2] = uint8(chunkLen >> 8)
  222. w.obuf[len(magicChunk)+3] = uint8(chunkLen >> 16)
  223. w.obuf[len(magicChunk)+4] = uint8(checksum >> 0)
  224. w.obuf[len(magicChunk)+5] = uint8(checksum >> 8)
  225. w.obuf[len(magicChunk)+6] = uint8(checksum >> 16)
  226. w.obuf[len(magicChunk)+7] = uint8(checksum >> 24)
  227. if _, err := w.w.Write(w.obuf[obufStart:obufEnd]); err != nil {
  228. w.err = err
  229. return nRet, err
  230. }
  231. if chunkType == chunkTypeUncompressedData {
  232. if _, err := w.w.Write(uncompressed); err != nil {
  233. w.err = err
  234. return nRet, err
  235. }
  236. }
  237. nRet += len(uncompressed)
  238. }
  239. return nRet, nil
  240. }
  241. // Flush flushes the Writer to its underlying io.Writer.
  242. func (w *Writer) Flush() error {
  243. if w.err != nil {
  244. return w.err
  245. }
  246. if len(w.ibuf) == 0 {
  247. return nil
  248. }
  249. w.write(w.ibuf)
  250. w.ibuf = w.ibuf[:0]
  251. return w.err
  252. }
  253. // Close calls Flush and then closes the Writer.
  254. func (w *Writer) Close() error {
  255. w.Flush()
  256. ret := w.err
  257. if w.err == nil {
  258. w.err = errClosed
  259. }
  260. return ret
  261. }