encode.go 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258
  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. "io"
  8. )
  9. // We limit how far copy back-references can go, the same as the C++ code.
  10. const maxOffset = 1 << 15
  11. // emitLiteral writes a literal chunk and returns the number of bytes written.
  12. func emitLiteral(dst, lit []byte) int {
  13. i, n := 0, uint(len(lit)-1)
  14. switch {
  15. case n < 60:
  16. dst[0] = uint8(n)<<2 | tagLiteral
  17. i = 1
  18. case n < 1<<8:
  19. dst[0] = 60<<2 | tagLiteral
  20. dst[1] = uint8(n)
  21. i = 2
  22. case n < 1<<16:
  23. dst[0] = 61<<2 | tagLiteral
  24. dst[1] = uint8(n)
  25. dst[2] = uint8(n >> 8)
  26. i = 3
  27. case n < 1<<24:
  28. dst[0] = 62<<2 | tagLiteral
  29. dst[1] = uint8(n)
  30. dst[2] = uint8(n >> 8)
  31. dst[3] = uint8(n >> 16)
  32. i = 4
  33. case int64(n) < 1<<32:
  34. dst[0] = 63<<2 | tagLiteral
  35. dst[1] = uint8(n)
  36. dst[2] = uint8(n >> 8)
  37. dst[3] = uint8(n >> 16)
  38. dst[4] = uint8(n >> 24)
  39. i = 5
  40. default:
  41. panic("snappy: source buffer is too long")
  42. }
  43. if copy(dst[i:], lit) != len(lit) {
  44. panic("snappy: destination buffer is too short")
  45. }
  46. return i + len(lit)
  47. }
  48. // emitCopy writes a copy chunk and returns the number of bytes written.
  49. func emitCopy(dst []byte, offset, length int) int {
  50. i := 0
  51. for length > 0 {
  52. x := length - 4
  53. if 0 <= x && x < 1<<3 && offset < 1<<11 {
  54. dst[i+0] = uint8(offset>>8)&0x07<<5 | uint8(x)<<2 | tagCopy1
  55. dst[i+1] = uint8(offset)
  56. i += 2
  57. break
  58. }
  59. x = length
  60. if x > 1<<6 {
  61. x = 1 << 6
  62. }
  63. dst[i+0] = uint8(x-1)<<2 | tagCopy2
  64. dst[i+1] = uint8(offset)
  65. dst[i+2] = uint8(offset >> 8)
  66. i += 3
  67. length -= x
  68. }
  69. return i
  70. }
  71. // Encode returns the encoded form of src. The returned slice may be a sub-
  72. // slice of dst if dst was large enough to hold the entire encoded block.
  73. // Otherwise, a newly allocated slice will be returned.
  74. // It is valid to pass a nil dst.
  75. func Encode(dst, src []byte) ([]byte, error) {
  76. if n := MaxEncodedLen(len(src)); len(dst) < n {
  77. dst = make([]byte, n)
  78. }
  79. // The block starts with the varint-encoded length of the decompressed bytes.
  80. d := binary.PutUvarint(dst, uint64(len(src)))
  81. // Return early if src is short.
  82. if len(src) <= 4 {
  83. if len(src) != 0 {
  84. d += emitLiteral(dst[d:], src)
  85. }
  86. return dst[:d], nil
  87. }
  88. // Initialize the hash table. Its size ranges from 1<<8 to 1<<14 inclusive.
  89. const maxTableSize = 1 << 14
  90. shift, tableSize := uint(32-8), 1<<8
  91. for tableSize < maxTableSize && tableSize < len(src) {
  92. shift--
  93. tableSize *= 2
  94. }
  95. var table [maxTableSize]int
  96. // Iterate over the source bytes.
  97. var (
  98. s int // The iterator position.
  99. t int // The last position with the same hash as s.
  100. lit int // The start position of any pending literal bytes.
  101. )
  102. for s+3 < len(src) {
  103. // Update the hash table.
  104. b0, b1, b2, b3 := src[s], src[s+1], src[s+2], src[s+3]
  105. h := uint32(b0) | uint32(b1)<<8 | uint32(b2)<<16 | uint32(b3)<<24
  106. p := &table[(h*0x1e35a7bd)>>shift]
  107. // We need to to store values in [-1, inf) in table. To save
  108. // some initialization time, (re)use the table's zero value
  109. // and shift the values against this zero: add 1 on writes,
  110. // subtract 1 on reads.
  111. t, *p = *p-1, s+1
  112. // If t is invalid or src[s:s+4] differs from src[t:t+4], accumulate a literal byte.
  113. if t < 0 || s-t >= maxOffset || b0 != src[t] || b1 != src[t+1] || b2 != src[t+2] || b3 != src[t+3] {
  114. s++
  115. continue
  116. }
  117. // Otherwise, we have a match. First, emit any pending literal bytes.
  118. if lit != s {
  119. d += emitLiteral(dst[d:], src[lit:s])
  120. }
  121. // Extend the match to be as long as possible.
  122. s0 := s
  123. s, t = s+4, t+4
  124. for s < len(src) && src[s] == src[t] {
  125. s++
  126. t++
  127. }
  128. // Emit the copied bytes.
  129. d += emitCopy(dst[d:], s-t, s-s0)
  130. lit = s
  131. }
  132. // Emit any final pending literal bytes and return.
  133. if lit != len(src) {
  134. d += emitLiteral(dst[d:], src[lit:])
  135. }
  136. return dst[:d], nil
  137. }
  138. // MaxEncodedLen returns the maximum length of a snappy block, given its
  139. // uncompressed length.
  140. func MaxEncodedLen(srcLen int) int {
  141. // Compressed data can be defined as:
  142. // compressed := item* literal*
  143. // item := literal* copy
  144. //
  145. // The trailing literal sequence has a space blowup of at most 62/60
  146. // since a literal of length 60 needs one tag byte + one extra byte
  147. // for length information.
  148. //
  149. // Item blowup is trickier to measure. Suppose the "copy" op copies
  150. // 4 bytes of data. Because of a special check in the encoding code,
  151. // we produce a 4-byte copy only if the offset is < 65536. Therefore
  152. // the copy op takes 3 bytes to encode, and this type of item leads
  153. // to at most the 62/60 blowup for representing literals.
  154. //
  155. // Suppose the "copy" op copies 5 bytes of data. If the offset is big
  156. // enough, it will take 5 bytes to encode the copy op. Therefore the
  157. // worst case here is a one-byte literal followed by a five-byte copy.
  158. // That is, 6 bytes of input turn into 7 bytes of "compressed" data.
  159. //
  160. // This last factor dominates the blowup, so the final estimate is:
  161. return 32 + srcLen + srcLen/6
  162. }
  163. // NewWriter returns a new Writer that compresses to w, using the framing
  164. // format described at
  165. // https://code.google.com/p/snappy/source/browse/trunk/framing_format.txt
  166. func NewWriter(w io.Writer) *Writer {
  167. return &Writer{
  168. w: w,
  169. enc: make([]byte, MaxEncodedLen(maxUncompressedChunkLen)),
  170. }
  171. }
  172. // Writer is an io.Writer than can write Snappy-compressed bytes.
  173. type Writer struct {
  174. w io.Writer
  175. err error
  176. enc []byte
  177. buf [checksumSize + chunkHeaderSize]byte
  178. wroteHeader bool
  179. }
  180. // Reset discards the writer's state and switches the Snappy writer to write to
  181. // w. This permits reusing a Writer rather than allocating a new one.
  182. func (w *Writer) Reset(writer io.Writer) {
  183. w.w = writer
  184. w.err = nil
  185. w.wroteHeader = false
  186. }
  187. // Write satisfies the io.Writer interface.
  188. func (w *Writer) Write(p []byte) (n int, errRet error) {
  189. if w.err != nil {
  190. return 0, w.err
  191. }
  192. if !w.wroteHeader {
  193. copy(w.enc, magicChunk)
  194. if _, err := w.w.Write(w.enc[:len(magicChunk)]); err != nil {
  195. w.err = err
  196. return n, err
  197. }
  198. w.wroteHeader = true
  199. }
  200. for len(p) > 0 {
  201. var uncompressed []byte
  202. if len(p) > maxUncompressedChunkLen {
  203. uncompressed, p = p[:maxUncompressedChunkLen], p[maxUncompressedChunkLen:]
  204. } else {
  205. uncompressed, p = p, nil
  206. }
  207. checksum := crc(uncompressed)
  208. // Compress the buffer, discarding the result if the improvement
  209. // isn't at least 12.5%.
  210. chunkType := uint8(chunkTypeCompressedData)
  211. chunkBody, err := Encode(w.enc, uncompressed)
  212. if err != nil {
  213. w.err = err
  214. return n, err
  215. }
  216. if len(chunkBody) >= len(uncompressed)-len(uncompressed)/8 {
  217. chunkType, chunkBody = chunkTypeUncompressedData, uncompressed
  218. }
  219. chunkLen := 4 + len(chunkBody)
  220. w.buf[0] = chunkType
  221. w.buf[1] = uint8(chunkLen >> 0)
  222. w.buf[2] = uint8(chunkLen >> 8)
  223. w.buf[3] = uint8(chunkLen >> 16)
  224. w.buf[4] = uint8(checksum >> 0)
  225. w.buf[5] = uint8(checksum >> 8)
  226. w.buf[6] = uint8(checksum >> 16)
  227. w.buf[7] = uint8(checksum >> 24)
  228. if _, err = w.w.Write(w.buf[:]); err != nil {
  229. w.err = err
  230. return n, err
  231. }
  232. if _, err = w.w.Write(chunkBody); err != nil {
  233. w.err = err
  234. return n, err
  235. }
  236. n += len(uncompressed)
  237. }
  238. return n, nil
  239. }