encode.go 8.9 KB

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