encode.go 9.1 KB

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