| 1 |
package flate |
| 2 |
|
| 3 |
import ( |
| 4 |
"io" |
| 5 |
"math" |
| 6 |
"sync" |
| 7 |
|
| 8 |
"github.com/klauspost/compress/internal/le" |
| 9 |
) |
| 10 |
|
| 11 |
const ( |
| 12 |
maxStatelessBlock = math.MaxInt16 |
| 13 |
// dictionary will be taken from maxStatelessBlock, so limit it. |
| 14 |
maxStatelessDict = 8 << 10 |
| 15 |
|
| 16 |
slTableBits = 13 |
| 17 |
slTableSize = 1 << slTableBits |
| 18 |
slTableShift = 32 - slTableBits |
| 19 |
) |
| 20 |
|
| 21 |
type statelessWriter struct { |
| 22 |
dst io.Writer |
| 23 |
closed bool |
| 24 |
} |
| 25 |
|
| 26 |
func (s *statelessWriter) Close() error { |
| 27 |
if s.closed { |
| 28 |
return nil |
| 29 |
} |
| 30 |
s.closed = true |
| 31 |
// Emit EOF block |
| 32 |
return StatelessDeflate(s.dst, nil, true, nil) |
| 33 |
} |
| 34 |
|
| 35 |
func (s *statelessWriter) Write(p []byte) (n int, err error) { |
| 36 |
err = StatelessDeflate(s.dst, p, false, nil) |
| 37 |
if err != nil { |
| 38 |
return 0, err |
| 39 |
} |
| 40 |
return len(p), nil |
| 41 |
} |
| 42 |
|
| 43 |
func (s *statelessWriter) Reset(w io.Writer) { |
| 44 |
s.dst = w |
| 45 |
s.closed = false |
| 46 |
} |
| 47 |
|
| 48 |
// NewStatelessWriter will do compression but without maintaining any state |
| 49 |
// between Write calls. |
| 50 |
// There will be no memory kept between Write calls, |
| 51 |
// but compression and speed will be suboptimal. |
| 52 |
// Because of this, the size of actual Write calls will affect output size. |
| 53 |
func NewStatelessWriter(dst io.Writer) io.WriteCloser { |
| 54 |
return &statelessWriter{dst: dst} |
| 55 |
} |
| 56 |
|
| 57 |
// bitWriterPool contains bit writers that can be reused. |
| 58 |
var bitWriterPool = sync.Pool{ |
| 59 |
New: func() any { |
| 60 |
return newHuffmanBitWriter(nil) |
| 61 |
}, |
| 62 |
} |
| 63 |
|
| 64 |
// tokensPool contains tokens struct objects that can be reused |
| 65 |
var tokensPool = sync.Pool{ |
| 66 |
New: func() any { |
| 67 |
return &tokens{} |
| 68 |
}, |
| 69 |
} |
| 70 |
|
| 71 |
// StatelessDeflate allows compressing directly to a Writer without retaining state. |
| 72 |
// When returning everything will be flushed. |
| 73 |
// Up to 8KB of an optional dictionary can be given which is presumed to precede the block. |
| 74 |
// Longer dictionaries will be truncated and will still produce valid output. |
| 75 |
// Sending nil dictionary is perfectly fine. |
| 76 |
func StatelessDeflate(out io.Writer, in []byte, eof bool, dict []byte) error { |
| 77 |
bw := bitWriterPool.Get().(*huffmanBitWriter) |
| 78 |
bw.reset(out) |
| 79 |
defer func() { |
| 80 |
// don't keep a reference to our output |
| 81 |
bw.reset(nil) |
| 82 |
bitWriterPool.Put(bw) |
| 83 |
}() |
| 84 |
if eof && len(in) == 0 { |
| 85 |
// Just write an EOF block. |
| 86 |
// Could be faster... |
| 87 |
bw.writeStoredHeader(0, true) |
| 88 |
bw.flush() |
| 89 |
return bw.err |
| 90 |
} |
| 91 |
|
| 92 |
// Truncate dict |
| 93 |
if len(dict) > maxStatelessDict { |
| 94 |
dict = dict[len(dict)-maxStatelessDict:] |
| 95 |
} |
| 96 |
|
| 97 |
// For subsequent loops, keep shallow dict reference to avoid alloc+copy. |
| 98 |
var inDict []byte |
| 99 |
|
| 100 |
dst := tokensPool.Get().(*tokens) |
| 101 |
dst.Reset() |
| 102 |
defer func() { |
| 103 |
tokensPool.Put(dst) |
| 104 |
}() |
| 105 |
|
| 106 |
for len(in) > 0 { |
| 107 |
todo := in |
| 108 |
if len(inDict) > 0 { |
| 109 |
if len(todo) > maxStatelessBlock-maxStatelessDict { |
| 110 |
todo = todo[:maxStatelessBlock-maxStatelessDict] |
| 111 |
} |
| 112 |
} else if len(todo) > maxStatelessBlock-len(dict) { |
| 113 |
todo = todo[:maxStatelessBlock-len(dict)] |
| 114 |
} |
| 115 |
inOrg := in |
| 116 |
in = in[len(todo):] |
| 117 |
uncompressed := todo |
| 118 |
if len(dict) > 0 { |
| 119 |
// combine dict and source |
| 120 |
bufLen := len(todo) + len(dict) |
| 121 |
combined := make([]byte, bufLen) |
| 122 |
copy(combined, dict) |
| 123 |
copy(combined[len(dict):], todo) |
| 124 |
todo = combined |
| 125 |
} |
| 126 |
// Compress |
| 127 |
if len(inDict) == 0 { |
| 128 |
statelessEnc(dst, todo, int16(len(dict))) |
| 129 |
} else { |
| 130 |
statelessEnc(dst, inDict[:maxStatelessDict+len(todo)], maxStatelessDict) |
| 131 |
} |
| 132 |
isEof := eof && len(in) == 0 |
| 133 |
|
| 134 |
if dst.n == 0 { |
| 135 |
bw.writeStoredHeader(len(uncompressed), isEof) |
| 136 |
if bw.err != nil { |
| 137 |
return bw.err |
| 138 |
} |
| 139 |
bw.writeBytes(uncompressed) |
| 140 |
} else if int(dst.n) > len(uncompressed)-len(uncompressed)>>4 { |
| 141 |
// If we removed less than 1/16th, huffman compress the block. |
| 142 |
bw.writeBlockHuff(isEof, uncompressed, len(in) == 0) |
| 143 |
} else { |
| 144 |
bw.writeBlockDynamic(dst, isEof, uncompressed, len(in) == 0) |
| 145 |
} |
| 146 |
if len(in) > 0 { |
| 147 |
// Retain a dict if we have more |
| 148 |
inDict = inOrg[len(uncompressed)-maxStatelessDict:] |
| 149 |
dict = nil |
| 150 |
dst.Reset() |
| 151 |
} |
| 152 |
if bw.err != nil { |
| 153 |
return bw.err |
| 154 |
} |
| 155 |
} |
| 156 |
if !eof { |
| 157 |
// Align, only a stored block can do that. |
| 158 |
bw.writeStoredHeader(0, false) |
| 159 |
} |
| 160 |
bw.flush() |
| 161 |
return bw.err |
| 162 |
} |
| 163 |
|
| 164 |
func hashSL(u uint32) uint32 { |
| 165 |
return (u * 0x1e35a7bd) >> slTableShift |
| 166 |
} |
| 167 |
|
| 168 |
func load3216(b []byte, i int16) uint32 { |
| 169 |
return le.Load32(b, i) |
| 170 |
} |
| 171 |
|
| 172 |
func load6416(b []byte, i int16) uint64 { |
| 173 |
return le.Load64(b, i) |
| 174 |
} |
| 175 |
|
| 176 |
func statelessEnc(dst *tokens, src []byte, startAt int16) { |
| 177 |
const ( |
| 178 |
inputMargin = 12 - 1 |
| 179 |
minNonLiteralBlockSize = 1 + 1 + inputMargin |
| 180 |
) |
| 181 |
|
| 182 |
type tableEntry struct { |
| 183 |
offset int16 |
| 184 |
} |
| 185 |
|
| 186 |
var table [slTableSize]tableEntry |
| 187 |
|
| 188 |
// This check isn't in the Snappy implementation, but there, the caller |
| 189 |
// instead of the callee handles this case. |
| 190 |
if len(src)-int(startAt) < minNonLiteralBlockSize { |
| 191 |
// We do not fill the token table. |
| 192 |
// This will be picked up by caller. |
| 193 |
dst.n = 0 |
| 194 |
return |
| 195 |
} |
| 196 |
// Index until startAt |
| 197 |
if startAt > 0 { |
| 198 |
cv := load3232(src, 0) |
| 199 |
for i := range startAt { |
| 200 |
table[hashSL(cv)] = tableEntry{offset: i} |
| 201 |
cv = (cv >> 8) | (uint32(src[i+4]) << 24) |
| 202 |
} |
| 203 |
} |
| 204 |
|
| 205 |
s := startAt + 1 |
| 206 |
nextEmit := startAt |
| 207 |
// sLimit is when to stop looking for offset/length copies. The inputMargin |
| 208 |
// lets us use a fast path for emitLiteral in the main loop, while we are |
| 209 |
// looking for copies. |
| 210 |
sLimit := int16(len(src) - inputMargin) |
| 211 |
|
| 212 |
// nextEmit is where in src the next emitLiteral should start from. |
| 213 |
cv := load3216(src, s) |
| 214 |
|
| 215 |
for { |
| 216 |
const skipLog = 5 |
| 217 |
const doEvery = 2 |
| 218 |
|
| 219 |
nextS := s |
| 220 |
var candidate tableEntry |
| 221 |
for { |
| 222 |
nextHash := hashSL(cv) |
| 223 |
candidate = table[nextHash] |
| 224 |
nextS = s + doEvery + (s-nextEmit)>>skipLog |
| 225 |
if nextS > sLimit || nextS <= 0 { |
| 226 |
goto emitRemainder |
| 227 |
} |
| 228 |
|
| 229 |
now := load6416(src, nextS) |
| 230 |
table[nextHash] = tableEntry{offset: s} |
| 231 |
nextHash = hashSL(uint32(now)) |
| 232 |
|
| 233 |
if cv == load3216(src, candidate.offset) { |
| 234 |
table[nextHash] = tableEntry{offset: nextS} |
| 235 |
break |
| 236 |
} |
| 237 |
|
| 238 |
// Do one right away... |
| 239 |
cv = uint32(now) |
| 240 |
s = nextS |
| 241 |
nextS++ |
| 242 |
candidate = table[nextHash] |
| 243 |
now >>= 8 |
| 244 |
table[nextHash] = tableEntry{offset: s} |
| 245 |
|
| 246 |
if cv == load3216(src, candidate.offset) { |
| 247 |
table[nextHash] = tableEntry{offset: nextS} |
| 248 |
break |
| 249 |
} |
| 250 |
cv = uint32(now) |
| 251 |
s = nextS |
| 252 |
} |
| 253 |
|
| 254 |
// A 4-byte match has been found. We'll later see if more than 4 bytes |
| 255 |
// match. But, prior to the match, src[nextEmit:s] are unmatched. Emit |
| 256 |
// them as literal bytes. |
| 257 |
for { |
| 258 |
// Invariant: we have a 4-byte match at s, and no need to emit any |
| 259 |
// literal bytes prior to s. |
| 260 |
|
| 261 |
// Extend the 4-byte match as long as possible. |
| 262 |
t := candidate.offset |
| 263 |
l := int16(matchLen(src[s+4:], src[t+4:]) + 4) |
| 264 |
|
| 265 |
// Extend backwards |
| 266 |
for t > 0 && s > nextEmit && src[t-1] == src[s-1] { |
| 267 |
s-- |
| 268 |
t-- |
| 269 |
l++ |
| 270 |
} |
| 271 |
if nextEmit < s { |
| 272 |
if false { |
| 273 |
emitLiteral(dst, src[nextEmit:s]) |
| 274 |
} else { |
| 275 |
for _, v := range src[nextEmit:s] { |
| 276 |
dst.tokens[dst.n] = token(v) |
| 277 |
dst.litHist[v]++ |
| 278 |
dst.n++ |
| 279 |
} |
| 280 |
} |
| 281 |
} |
| 282 |
|
| 283 |
// Save the match found |
| 284 |
dst.AddMatchLong(int32(l), uint32(s-t-baseMatchOffset)) |
| 285 |
s += l |
| 286 |
nextEmit = s |
| 287 |
if nextS >= s { |
| 288 |
s = nextS + 1 |
| 289 |
} |
| 290 |
if s >= sLimit { |
| 291 |
goto emitRemainder |
| 292 |
} |
| 293 |
|
| 294 |
// We could immediately start working at s now, but to improve |
| 295 |
// compression we first update the hash table at s-2 and at s. If |
| 296 |
// another emitCopy is not our next move, also calculate nextHash |
| 297 |
// at s+1. At least on GOARCH=amd64, these three hash calculations |
| 298 |
// are faster as one load64 call (with some shifts) instead of |
| 299 |
// three load32 calls. |
| 300 |
x := load6416(src, s-2) |
| 301 |
o := s - 2 |
| 302 |
prevHash := hashSL(uint32(x)) |
| 303 |
table[prevHash] = tableEntry{offset: o} |
| 304 |
x >>= 16 |
| 305 |
currHash := hashSL(uint32(x)) |
| 306 |
candidate = table[currHash] |
| 307 |
table[currHash] = tableEntry{offset: o + 2} |
| 308 |
|
| 309 |
if uint32(x) != load3216(src, candidate.offset) { |
| 310 |
cv = uint32(x >> 8) |
| 311 |
s++ |
| 312 |
break |
| 313 |
} |
| 314 |
} |
| 315 |
} |
| 316 |
|
| 317 |
emitRemainder: |
| 318 |
if int(nextEmit) < len(src) { |
| 319 |
// If nothing was added, don't encode literals. |
| 320 |
if dst.n == 0 { |
| 321 |
return |
| 322 |
} |
| 323 |
emitLiteral(dst, src[nextEmit:]) |
| 324 |
} |
| 325 |
} |