encode.go 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255
  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 {
  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]
  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. // Skip multiple bytes if the last match was >= 32 bytes prior.
  115. s += 1 + (s-lit)>>5
  116. continue
  117. }
  118. // Otherwise, we have a match. First, emit any pending literal bytes.
  119. if lit != s {
  120. d += emitLiteral(dst[d:], src[lit:s])
  121. }
  122. // Extend the match to be as long as possible.
  123. s0 := s
  124. s, t = s+4, t+4
  125. for s < len(src) && src[s] == src[t] {
  126. s++
  127. t++
  128. }
  129. // Emit the copied bytes.
  130. d += emitCopy(dst[d:], s-t, s-s0)
  131. lit = s
  132. }
  133. // Emit any final pending literal bytes and return.
  134. if lit != len(src) {
  135. d += emitLiteral(dst[d:], src[lit:])
  136. }
  137. return dst[:d]
  138. }
  139. // MaxEncodedLen returns the maximum length of a snappy block, given its
  140. // uncompressed length.
  141. func MaxEncodedLen(srcLen int) int {
  142. // Compressed data can be defined as:
  143. // compressed := item* literal*
  144. // item := literal* copy
  145. //
  146. // The trailing literal sequence has a space blowup of at most 62/60
  147. // since a literal of length 60 needs one tag byte + one extra byte
  148. // for length information.
  149. //
  150. // Item blowup is trickier to measure. Suppose the "copy" op copies
  151. // 4 bytes of data. Because of a special check in the encoding code,
  152. // we produce a 4-byte copy only if the offset is < 65536. Therefore
  153. // the copy op takes 3 bytes to encode, and this type of item leads
  154. // to at most the 62/60 blowup for representing literals.
  155. //
  156. // Suppose the "copy" op copies 5 bytes of data. If the offset is big
  157. // enough, it will take 5 bytes to encode the copy op. Therefore the
  158. // worst case here is a one-byte literal followed by a five-byte copy.
  159. // That is, 6 bytes of input turn into 7 bytes of "compressed" data.
  160. //
  161. // This last factor dominates the blowup, so the final estimate is:
  162. return 32 + srcLen + srcLen/6
  163. }
  164. // NewWriter returns a new Writer that compresses to w, using the framing
  165. // format described at
  166. // https://github.com/google/snappy/blob/master/framing_format.txt
  167. func NewWriter(w io.Writer) *Writer {
  168. return &Writer{
  169. w: w,
  170. enc: make([]byte, MaxEncodedLen(maxUncompressedChunkLen)),
  171. }
  172. }
  173. // Writer is an io.Writer than can write Snappy-compressed bytes.
  174. type Writer struct {
  175. w io.Writer
  176. err error
  177. enc []byte
  178. buf [checksumSize + chunkHeaderSize]byte
  179. wroteHeader bool
  180. }
  181. // Reset discards the writer's state and switches the Snappy writer to write to
  182. // w. This permits reusing a Writer rather than allocating a new one.
  183. func (w *Writer) Reset(writer io.Writer) {
  184. w.w = writer
  185. w.err = nil
  186. w.wroteHeader = false
  187. }
  188. // Write satisfies the io.Writer interface.
  189. func (w *Writer) Write(p []byte) (n int, errRet error) {
  190. if w.err != nil {
  191. return 0, w.err
  192. }
  193. if !w.wroteHeader {
  194. copy(w.enc, magicChunk)
  195. if _, err := w.w.Write(w.enc[:len(magicChunk)]); err != nil {
  196. w.err = err
  197. return n, err
  198. }
  199. w.wroteHeader = true
  200. }
  201. for len(p) > 0 {
  202. var uncompressed []byte
  203. if len(p) > maxUncompressedChunkLen {
  204. uncompressed, p = p[:maxUncompressedChunkLen], p[maxUncompressedChunkLen:]
  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. chunkType := uint8(chunkTypeCompressedData)
  212. chunkBody := Encode(w.enc, uncompressed)
  213. if len(chunkBody) >= len(uncompressed)-len(uncompressed)/8 {
  214. chunkType, chunkBody = chunkTypeUncompressedData, uncompressed
  215. }
  216. chunkLen := 4 + len(chunkBody)
  217. w.buf[0] = chunkType
  218. w.buf[1] = uint8(chunkLen >> 0)
  219. w.buf[2] = uint8(chunkLen >> 8)
  220. w.buf[3] = uint8(chunkLen >> 16)
  221. w.buf[4] = uint8(checksum >> 0)
  222. w.buf[5] = uint8(checksum >> 8)
  223. w.buf[6] = uint8(checksum >> 16)
  224. w.buf[7] = uint8(checksum >> 24)
  225. if _, err := w.w.Write(w.buf[:]); err != nil {
  226. w.err = err
  227. return n, err
  228. }
  229. if _, err := w.w.Write(chunkBody); err != nil {
  230. w.err = err
  231. return n, err
  232. }
  233. n += len(uncompressed)
  234. }
  235. return n, nil
  236. }