| 1 |
// Copyright 2019+ Klaus Post. All rights reserved. |
| 2 |
// License information can be found in the LICENSE file. |
| 3 |
// Based on work by Yann Collet, released under BSD License. |
| 4 |
|
| 5 |
package zstd |
| 6 |
|
| 7 |
import ( |
| 8 |
"crypto/rand" |
| 9 |
"errors" |
| 10 |
"fmt" |
| 11 |
"io" |
| 12 |
"math" |
| 13 |
rdebug "runtime/debug" |
| 14 |
"sync" |
| 15 |
|
| •16 |
"github.com/cespare/xxhash/v2" |
| 17 |
) |
| 18 |
|
| 19 |
// Encoder provides encoding to Zstandard. |
| 20 |
// An Encoder can be used for either compressing a stream via the |
| 21 |
// io.WriteCloser interface supported by the Encoder or as multiple independent |
| 22 |
// tasks via the EncodeAll function. |
| 23 |
// Smaller encodes are encouraged to use the EncodeAll function. |
| 24 |
// Use NewWriter to create a new instance. |
| 25 |
type Encoder struct { |
| 26 |
o encoderOptions |
| 27 |
encoders chan encoder |
| 28 |
state encoderState |
| 29 |
init sync.Once |
| 30 |
} |
| 31 |
|
| 32 |
type encoder interface { |
| 33 |
Encode(blk *blockEnc, src []byte) |
| 34 |
EncodeNoHist(blk *blockEnc, src []byte) |
| 35 |
Block() *blockEnc |
| 36 |
CRC() *xxhash.Digest |
| 37 |
AppendCRC([]byte) []byte |
| 38 |
WindowSize(size int64) int32 |
| 39 |
UseBlock(*blockEnc) |
| 40 |
Reset(d *dict, singleBlock bool) |
| 41 |
ResetPrefix(prefix []byte) |
| 42 |
} |
| 43 |
|
| 44 |
type encoderState struct { |
| 45 |
w io.Writer |
| 46 |
filling []byte |
| 47 |
current []byte |
| 48 |
previous []byte |
| 49 |
encoder encoder |
| 50 |
writing *blockEnc |
| 51 |
err error |
| 52 |
writeErr error |
| 53 |
nWritten int64 |
| 54 |
nInput int64 |
| 55 |
frameContentSize int64 |
| 56 |
headerWritten bool |
| 57 |
eofWritten bool |
| 58 |
fullFrameWritten bool |
| 59 |
|
| 60 |
// This waitgroup indicates an encode is running. |
| 61 |
wg sync.WaitGroup |
| 62 |
// This waitgroup indicates we have a block encoding/writing. |
| 63 |
wWg sync.WaitGroup |
| 64 |
|
| 65 |
// Parallel job state (used when concurrentBlocks is enabled). |
| 66 |
jobs jobState |
| 67 |
} |
| 68 |
|
| 69 |
// NewWriter will create a new Zstandard encoder. |
| 70 |
// If the encoder will be used for encoding blocks a nil writer can be used. |
| 71 |
func NewWriter(w io.Writer, opts ...EOption) (*Encoder, error) { |
| 72 |
initPredefined() |
| 73 |
var e Encoder |
| 74 |
e.o.setDefault() |
| 75 |
for _, o := range opts { |
| 76 |
err := o(&e.o) |
| 77 |
if err != nil { |
| 78 |
return nil, err |
| 79 |
} |
| 80 |
} |
| 81 |
if e.o.concurrentBlocks && (e.o.dict != nil || e.o.concurrent <= 1) { |
| 82 |
e.o.concurrentBlocks = false |
| 83 |
} |
| 84 |
if w != nil { |
| 85 |
e.Reset(w) |
| 86 |
} |
| 87 |
return &e, nil |
| 88 |
} |
| 89 |
|
| 90 |
func (e *Encoder) initialize() { |
| 91 |
if e.o.concurrent == 0 { |
| 92 |
e.o.setDefault() |
| 93 |
} |
| 94 |
e.encoders = make(chan encoder, e.o.concurrent) |
| 95 |
for i := 0; i < e.o.concurrent; i++ { |
| 96 |
enc := e.o.encoder() |
| 97 |
e.encoders <- enc |
| 98 |
} |
| 99 |
} |
| 100 |
|
| 101 |
// Reset will re-initialize the writer and new writes will encode to the supplied writer |
| 102 |
// as a new, independent stream. |
| 103 |
func (e *Encoder) Reset(w io.Writer) { |
| 104 |
s := &e.state |
| 105 |
|
| 106 |
if e.o.concurrentBlocks { |
| 107 |
e.shutdownJobWorkers() |
| 108 |
js := &s.jobs |
| 109 |
js.jobSize = e.o.jobSize() |
| 110 |
js.overlapSize = e.o.overlapSize() |
| 111 |
// js.filling is allocated lazily on first Write/ReadFrom so callers |
| 112 |
// that only use EncodeAll don't pay the (up to ~32 MB) jobSize cost. |
| 113 |
js.filling = js.filling[:0] |
| 114 |
if js.nextPrefix != nil { |
| 115 |
js.putOverlapBuf(js.nextPrefix) |
| 116 |
js.nextPrefix = nil |
| 117 |
} |
| 118 |
js.jobSeq = 0 |
| 119 |
js.flushedSeq = 0 |
| 120 |
js.flusherErr = nil |
| 121 |
js.started = false |
| 122 |
} |
| 123 |
|
| 124 |
s.wg.Wait() |
| 125 |
s.wWg.Wait() |
| 126 |
if cap(s.filling) == 0 { |
| 127 |
s.filling = make([]byte, 0, e.o.blockSize) |
| 128 |
} |
| 129 |
if e.o.concurrent > 1 && !e.o.concurrentBlocks { |
| 130 |
if cap(s.current) == 0 { |
| 131 |
s.current = make([]byte, 0, e.o.blockSize) |
| 132 |
} |
| 133 |
if cap(s.previous) == 0 { |
| 134 |
s.previous = make([]byte, 0, e.o.blockSize) |
| 135 |
} |
| 136 |
s.current = s.current[:0] |
| 137 |
s.previous = s.previous[:0] |
| 138 |
if s.writing == nil { |
| 139 |
s.writing = &blockEnc{lowMem: e.o.lowMem} |
| 140 |
s.writing.init() |
| 141 |
} |
| 142 |
s.writing.initNewEncode() |
| 143 |
} |
| 144 |
if s.encoder == nil { |
| 145 |
s.encoder = e.o.encoder() |
| 146 |
} |
| 147 |
s.filling = s.filling[:0] |
| 148 |
s.encoder.Reset(e.o.dict, false) |
| 149 |
s.headerWritten = false |
| 150 |
s.eofWritten = false |
| 151 |
s.fullFrameWritten = false |
| 152 |
s.w = w |
| 153 |
s.err = nil |
| 154 |
s.nWritten = 0 |
| 155 |
s.nInput = 0 |
| 156 |
s.writeErr = nil |
| 157 |
s.frameContentSize = 0 |
| 158 |
} |
| 159 |
|
| 160 |
// ResetWithOptions will re-initialize the writer and apply the given options |
| 161 |
// as a new, independent stream. |
| 162 |
// Options are applied on top of the existing options. |
| 163 |
// Some options cannot be changed on reset and will return an error. |
| 164 |
func (e *Encoder) ResetWithOptions(w io.Writer, opts ...EOption) error { |
| 165 |
e.o.resetOpt = true |
| 166 |
defer func() { e.o.resetOpt = false }() |
| 167 |
hadDict := e.o.dict != nil |
| 168 |
for _, o := range opts { |
| 169 |
if err := o(&e.o); err != nil { |
| 170 |
return err |
| 171 |
} |
| 172 |
} |
| 173 |
hasDict := e.o.dict != nil |
| 174 |
if e.o.concurrentBlocks && hasDict { |
| 175 |
e.o.concurrentBlocks = false |
| 176 |
} |
| 177 |
if hadDict != hasDict { |
| 178 |
// Dict presence changed — encoder type must be recreated. |
| 179 |
e.state.encoder = nil |
| 180 |
e.init = sync.Once{} |
| 181 |
} |
| 182 |
e.Reset(w) |
| 183 |
return nil |
| 184 |
} |
| 185 |
|
| 186 |
// ResetContentSize will reset and set a content size for the next stream. |
| 187 |
// If the bytes written does not match the size given an error will be returned |
| 188 |
// when calling Close(). |
| 189 |
// This is removed when Reset is called. |
| 190 |
// Sizes <= 0 results in no content size set. |
| 191 |
func (e *Encoder) ResetContentSize(w io.Writer, size int64) { |
| 192 |
e.Reset(w) |
| 193 |
if size >= 0 { |
| 194 |
e.state.frameContentSize = size |
| 195 |
} |
| 196 |
} |
| 197 |
|
| 198 |
// Write data to the encoder. |
| 199 |
// Input data will be buffered and as the buffer fills up |
| 200 |
// content will be compressed and written to the output. |
| 201 |
// When done writing, use Close to flush the remaining output |
| 202 |
// and write CRC if requested. |
| 203 |
func (e *Encoder) Write(p []byte) (n int, err error) { |
| 204 |
s := &e.state |
| 205 |
if s.eofWritten { |
| 206 |
return 0, ErrEncoderClosed |
| 207 |
} |
| 208 |
if e.o.concurrentBlocks { |
| 209 |
return e.writeJobs(p) |
| 210 |
} |
| 211 |
return e.writeBlocks(p) |
| 212 |
} |
| 213 |
|
| 214 |
func (e *Encoder) writeJobs(p []byte) (n int, err error) { |
| 215 |
s := &e.state |
| 216 |
js := &s.jobs |
| 217 |
jobSize := js.jobSize |
| 218 |
if cap(js.filling) == 0 && len(p) > 0 { |
| 219 |
js.filling = make([]byte, 0, jobSize) |
| 220 |
} |
| 221 |
for len(p) > 0 { |
| 222 |
if len(p)+len(js.filling) < jobSize { |
| 223 |
if e.o.crc { |
| 224 |
_, _ = s.encoder.CRC().Write(p) |
| 225 |
} |
| 226 |
js.filling = append(js.filling, p...) |
| 227 |
return n + len(p), nil |
| 228 |
} |
| 229 |
add := p |
| 230 |
if len(p)+len(js.filling) > jobSize { |
| 231 |
add = add[:jobSize-len(js.filling)] |
| 232 |
} |
| 233 |
if e.o.crc { |
| 234 |
_, _ = s.encoder.CRC().Write(add) |
| 235 |
} |
| 236 |
js.filling = append(js.filling, add...) |
| 237 |
p = p[len(add):] |
| 238 |
n += len(add) |
| 239 |
if len(js.filling) < jobSize { |
| 240 |
return n, nil |
| 241 |
} |
| 242 |
if err := e.dispatchJob(false); err != nil { |
| 243 |
return n, err |
| 244 |
} |
| 245 |
} |
| 246 |
return n, nil |
| 247 |
} |
| 248 |
|
| 249 |
func (e *Encoder) writeBlocks(p []byte) (n int, err error) { |
| 250 |
s := &e.state |
| 251 |
for len(p) > 0 { |
| 252 |
if len(p)+len(s.filling) < e.o.blockSize { |
| 253 |
if e.o.crc { |
| 254 |
_, _ = s.encoder.CRC().Write(p) |
| 255 |
} |
| 256 |
s.filling = append(s.filling, p...) |
| 257 |
return n + len(p), nil |
| 258 |
} |
| 259 |
add := p |
| 260 |
if len(p)+len(s.filling) > e.o.blockSize { |
| 261 |
add = add[:e.o.blockSize-len(s.filling)] |
| 262 |
} |
| 263 |
if e.o.crc { |
| 264 |
_, _ = s.encoder.CRC().Write(add) |
| 265 |
} |
| 266 |
s.filling = append(s.filling, add...) |
| 267 |
p = p[len(add):] |
| 268 |
n += len(add) |
| 269 |
if len(s.filling) < e.o.blockSize { |
| 270 |
return n, nil |
| 271 |
} |
| 272 |
err := e.nextBlock(false) |
| 273 |
if err != nil { |
| 274 |
return n, err |
| 275 |
} |
| 276 |
if debugAsserts && len(s.filling) > 0 { |
| 277 |
panic(len(s.filling)) |
| 278 |
} |
| 279 |
} |
| 280 |
return n, nil |
| 281 |
} |
| 282 |
|
| 283 |
// nextBlock will synchronize and start compressing input in e.state.filling. |
| 284 |
// If an error has occurred during encoding it will be returned. |
| 285 |
func (e *Encoder) nextBlock(final bool) error { |
| 286 |
s := &e.state |
| 287 |
// Wait for current block. |
| 288 |
s.wg.Wait() |
| 289 |
if s.err != nil { |
| 290 |
return s.err |
| 291 |
} |
| 292 |
if len(s.filling) > e.o.blockSize { |
| 293 |
return fmt.Errorf("block > maxStoreBlockSize") |
| 294 |
} |
| 295 |
if !s.headerWritten { |
| 296 |
// If we have a single block encode, do a sync compression. |
| 297 |
if final && len(s.filling) == 0 && !e.o.fullZero { |
| 298 |
s.headerWritten = true |
| 299 |
s.fullFrameWritten = true |
| 300 |
s.eofWritten = true |
| 301 |
return nil |
| 302 |
} |
| 303 |
if final && len(s.filling) > 0 { |
| 304 |
s.current = e.encodeAll(s.encoder, s.filling, s.current[:0]) |
| 305 |
var n2 int |
| 306 |
n2, s.err = s.w.Write(s.current) |
| 307 |
if s.err != nil { |
| 308 |
return s.err |
| 309 |
} |
| 310 |
s.nWritten += int64(n2) |
| 311 |
s.nInput += int64(len(s.filling)) |
| 312 |
s.current = s.current[:0] |
| 313 |
s.filling = s.filling[:0] |
| 314 |
s.headerWritten = true |
| 315 |
s.fullFrameWritten = true |
| 316 |
s.eofWritten = true |
| 317 |
return nil |
| 318 |
} |
| 319 |
|
| 320 |
var tmp [maxHeaderSize]byte |
| 321 |
fh := frameHeader{ |
| 322 |
ContentSize: uint64(s.frameContentSize), |
| 323 |
WindowSize: uint32(s.encoder.WindowSize(s.frameContentSize)), |
| 324 |
SingleSegment: false, |
| 325 |
Checksum: e.o.crc, |
| 326 |
DictID: e.o.dict.ID(), |
| 327 |
} |
| 328 |
|
| 329 |
dst := fh.appendTo(tmp[:0]) |
| 330 |
s.headerWritten = true |
| 331 |
s.wWg.Wait() |
| 332 |
var n2 int |
| 333 |
n2, s.err = s.w.Write(dst) |
| 334 |
if s.err != nil { |
| 335 |
return s.err |
| 336 |
} |
| 337 |
s.nWritten += int64(n2) |
| 338 |
} |
| 339 |
if s.eofWritten { |
| 340 |
// Ensure we only write it once. |
| 341 |
final = false |
| 342 |
} |
| 343 |
|
| 344 |
if len(s.filling) == 0 { |
| 345 |
// Final block, but no data. |
| 346 |
if final { |
| 347 |
enc := s.encoder |
| 348 |
blk := enc.Block() |
| 349 |
blk.reset(nil) |
| 350 |
blk.last = true |
| 351 |
blk.encodeRaw(nil) |
| 352 |
s.wWg.Wait() |
| 353 |
_, s.err = s.w.Write(blk.output) |
| 354 |
s.nWritten += int64(len(blk.output)) |
| 355 |
s.eofWritten = true |
| 356 |
} |
| 357 |
return s.err |
| 358 |
} |
| 359 |
|
| 360 |
// SYNC: |
| 361 |
if e.o.concurrent == 1 { |
| 362 |
src := s.filling |
| 363 |
s.nInput += int64(len(s.filling)) |
| 364 |
if debugEncoder { |
| 365 |
println("Adding sync block,", len(src), "bytes, final:", final) |
| 366 |
} |
| 367 |
enc := s.encoder |
| 368 |
blk := enc.Block() |
| 369 |
blk.reset(nil) |
| 370 |
enc.Encode(blk, src) |
| 371 |
blk.last = final |
| 372 |
if final { |
| 373 |
s.eofWritten = true |
| 374 |
} |
| 375 |
|
| 376 |
s.err = blk.encode(src, e.o.noEntropy, !e.o.allLitEntropy) |
| 377 |
if s.err != nil { |
| 378 |
return s.err |
| 379 |
} |
| 380 |
_, s.err = s.w.Write(blk.output) |
| 381 |
s.nWritten += int64(len(blk.output)) |
| 382 |
s.filling = s.filling[:0] |
| 383 |
return s.err |
| 384 |
} |
| 385 |
|
| 386 |
// Move blocks forward. |
| 387 |
s.filling, s.current, s.previous = s.previous[:0], s.filling, s.current |
| 388 |
s.nInput += int64(len(s.current)) |
| 389 |
s.wg.Add(1) |
| 390 |
if final { |
| 391 |
s.eofWritten = true |
| 392 |
} |
| 393 |
go func(src []byte) { |
| 394 |
if debugEncoder { |
| 395 |
println("Adding block,", len(src), "bytes, final:", final) |
| 396 |
} |
| 397 |
defer func() { |
| 398 |
if r := recover(); r != nil { |
| 399 |
s.err = fmt.Errorf("panic while encoding: %v", r) |
| 400 |
rdebug.PrintStack() |
| 401 |
} |
| 402 |
s.wg.Done() |
| 403 |
}() |
| 404 |
enc := s.encoder |
| 405 |
blk := enc.Block() |
| 406 |
enc.Encode(blk, src) |
| 407 |
blk.last = final |
| 408 |
// Wait for pending writes. |
| 409 |
s.wWg.Wait() |
| 410 |
if s.writeErr != nil { |
| 411 |
s.err = s.writeErr |
| 412 |
return |
| 413 |
} |
| 414 |
// Transfer encoders from previous write block. |
| 415 |
blk.swapEncoders(s.writing) |
| 416 |
// Transfer recent offsets to next. |
| 417 |
enc.UseBlock(s.writing) |
| 418 |
s.writing = blk |
| 419 |
s.wWg.Add(1) |
| 420 |
go func() { |
| 421 |
defer func() { |
| 422 |
if r := recover(); r != nil { |
| 423 |
s.writeErr = fmt.Errorf("panic while encoding/writing: %v", r) |
| 424 |
rdebug.PrintStack() |
| 425 |
} |
| 426 |
s.wWg.Done() |
| 427 |
}() |
| 428 |
s.writeErr = blk.encode(src, e.o.noEntropy, !e.o.allLitEntropy) |
| 429 |
if s.writeErr != nil { |
| 430 |
return |
| 431 |
} |
| 432 |
_, s.writeErr = s.w.Write(blk.output) |
| 433 |
s.nWritten += int64(len(blk.output)) |
| 434 |
}() |
| 435 |
}(s.current) |
| 436 |
return nil |
| 437 |
} |
| 438 |
|
| 439 |
// ReadFrom reads data from r until EOF or error. |
| 440 |
// The return value n is the number of bytes read. |
| 441 |
// Any error except io.EOF encountered during the read is also returned. |
| 442 |
// |
| 443 |
// The Copy function uses ReaderFrom if available. |
| 444 |
func (e *Encoder) ReadFrom(r io.Reader) (n int64, err error) { |
| 445 |
if debugEncoder { |
| 446 |
println("Using ReadFrom") |
| 447 |
} |
| 448 |
|
| 449 |
if e.o.concurrentBlocks { |
| 450 |
return e.readFromJobs(r) |
| 451 |
} |
| 452 |
|
| 453 |
// Flush any current writes. |
| 454 |
if len(e.state.filling) > 0 { |
| 455 |
if err := e.nextBlock(false); err != nil { |
| 456 |
return 0, err |
| 457 |
} |
| 458 |
} |
| 459 |
e.state.filling = e.state.filling[:e.o.blockSize] |
| 460 |
src := e.state.filling |
| 461 |
for { |
| 462 |
n2, err := r.Read(src) |
| 463 |
if e.o.crc { |
| 464 |
_, _ = e.state.encoder.CRC().Write(src[:n2]) |
| 465 |
} |
| 466 |
src = src[n2:] |
| 467 |
n += int64(n2) |
| 468 |
switch err { |
| 469 |
case io.EOF: |
| 470 |
e.state.filling = e.state.filling[:len(e.state.filling)-len(src)] |
| 471 |
if debugEncoder { |
| 472 |
println("ReadFrom: got EOF final block:", len(e.state.filling)) |
| 473 |
} |
| 474 |
return n, nil |
| 475 |
case nil: |
| 476 |
default: |
| 477 |
if debugEncoder { |
| 478 |
println("ReadFrom: got error:", err) |
| 479 |
} |
| 480 |
e.state.err = err |
| 481 |
return n, err |
| 482 |
} |
| 483 |
if len(src) > 0 { |
| 484 |
if debugEncoder { |
| 485 |
println("ReadFrom: got space left in source:", len(src)) |
| 486 |
} |
| 487 |
continue |
| 488 |
} |
| 489 |
err = e.nextBlock(false) |
| 490 |
if err != nil { |
| 491 |
return n, err |
| 492 |
} |
| 493 |
e.state.filling = e.state.filling[:e.o.blockSize] |
| 494 |
src = e.state.filling |
| 495 |
} |
| 496 |
} |
| 497 |
|
| 498 |
func (e *Encoder) readFromJobs(r io.Reader) (n int64, err error) { |
| 499 |
js := &e.state.jobs |
| 500 |
jobSize := js.jobSize |
| 501 |
|
| 502 |
// Flush any current filling. |
| 503 |
if len(js.filling) > 0 { |
| 504 |
if err := e.dispatchJob(false); err != nil { |
| 505 |
return 0, err |
| 506 |
} |
| 507 |
} |
| 508 |
|
| 509 |
if cap(js.filling) < jobSize { |
| 510 |
js.filling = make([]byte, 0, jobSize) |
| 511 |
} |
| 512 |
js.filling = js.filling[:jobSize] |
| 513 |
src := js.filling |
| 514 |
for { |
| 515 |
n2, err := r.Read(src) |
| 516 |
if e.o.crc { |
| 517 |
_, _ = e.state.encoder.CRC().Write(src[:n2]) |
| 518 |
} |
| 519 |
src = src[n2:] |
| 520 |
n += int64(n2) |
| 521 |
switch err { |
| 522 |
case io.EOF: |
| 523 |
js.filling = js.filling[:len(js.filling)-len(src)] |
| 524 |
return n, nil |
| 525 |
case nil: |
| 526 |
default: |
| 527 |
e.state.err = err |
| 528 |
return n, err |
| 529 |
} |
| 530 |
if len(src) > 0 { |
| 531 |
continue |
| 532 |
} |
| 533 |
if err = e.dispatchJob(false); err != nil { |
| 534 |
return n, err |
| 535 |
} |
| 536 |
if cap(js.filling) < jobSize { |
| 537 |
js.filling = make([]byte, 0, jobSize) |
| 538 |
} |
| 539 |
js.filling = js.filling[:jobSize] |
| 540 |
src = js.filling |
| 541 |
} |
| 542 |
} |
| 543 |
|
| 544 |
// Flush will send the currently written data to output |
| 545 |
// and block until everything has been written. |
| 546 |
// This should only be used on rare occasions where pushing the currently queued data is critical. |
| 547 |
func (e *Encoder) Flush() error { |
| 548 |
s := &e.state |
| 549 |
if e.o.concurrentBlocks { |
| 550 |
return e.flushJobs() |
| 551 |
} |
| 552 |
if len(s.filling) > 0 { |
| 553 |
err := e.nextBlock(false) |
| 554 |
if err != nil { |
| 555 |
if errors.Is(s.err, ErrEncoderClosed) { |
| 556 |
return nil |
| 557 |
} |
| 558 |
return err |
| 559 |
} |
| 560 |
} |
| 561 |
s.wg.Wait() |
| 562 |
s.wWg.Wait() |
| 563 |
if s.err != nil { |
| 564 |
if errors.Is(s.err, ErrEncoderClosed) { |
| 565 |
return nil |
| 566 |
} |
| 567 |
return s.err |
| 568 |
} |
| 569 |
return s.writeErr |
| 570 |
} |
| 571 |
|
| 572 |
func (e *Encoder) flushJobs() error { |
| 573 |
js := &e.state.jobs |
| 574 |
if len(js.filling) > 0 { |
| 575 |
if err := e.dispatchJob(false); err != nil { |
| 576 |
return err |
| 577 |
} |
| 578 |
} |
| 579 |
e.waitAllJobs() |
| 580 |
js.mu.Lock() |
| 581 |
fErr := js.flusherErr |
| 582 |
js.mu.Unlock() |
| 583 |
return fErr |
| 584 |
} |
| 585 |
|
| 586 |
// Close will flush the final output and close the stream. |
| 587 |
// The function will block until everything has been written. |
| 588 |
// The Encoder can still be re-used after calling this. |
| 589 |
func (e *Encoder) Close() error { |
| 590 |
s := &e.state |
| 591 |
if s.encoder == nil { |
| 592 |
return nil |
| 593 |
} |
| 594 |
if e.o.concurrentBlocks { |
| 595 |
return e.closeJobs() |
| 596 |
} |
| 597 |
if s.w == nil { |
| 598 |
if len(s.filling) == 0 && !s.headerWritten && !s.eofWritten && s.nInput == 0 { |
| 599 |
return nil |
| 600 |
} |
| 601 |
return errors.New("zstd: encoder has no writer") |
| 602 |
} |
| 603 |
|
| 604 |
err := e.nextBlock(true) |
| 605 |
if err != nil { |
| 606 |
if errors.Is(s.err, ErrEncoderClosed) { |
| 607 |
return nil |
| 608 |
} |
| 609 |
return err |
| 610 |
} |
| 611 |
if s.frameContentSize > 0 { |
| 612 |
if s.nInput != s.frameContentSize { |
| 613 |
return fmt.Errorf("frame content size %d given, but %d bytes was written", s.frameContentSize, s.nInput) |
| 614 |
} |
| 615 |
} |
| 616 |
if e.state.fullFrameWritten { |
| 617 |
return s.err |
| 618 |
} |
| 619 |
s.wg.Wait() |
| 620 |
s.wWg.Wait() |
| 621 |
|
| 622 |
if s.err != nil { |
| 623 |
return s.err |
| 624 |
} |
| 625 |
if s.writeErr != nil { |
| 626 |
return s.writeErr |
| 627 |
} |
| 628 |
|
| 629 |
// Write CRC |
| 630 |
if e.o.crc && s.err == nil { |
| 631 |
// heap alloc. |
| 632 |
var tmp [4]byte |
| 633 |
_, s.err = s.w.Write(s.encoder.AppendCRC(tmp[:0])) |
| 634 |
s.nWritten += 4 |
| 635 |
} |
| 636 |
|
| 637 |
// Add padding with content from crypto/rand.Reader |
| 638 |
if s.err == nil && e.o.pad > 0 { |
| 639 |
add := calcSkippableFrame(s.nWritten, int64(e.o.pad)) |
| 640 |
frame, err := skippableFrame(s.filling[:0], add, rand.Reader) |
| 641 |
if err != nil { |
| 642 |
return err |
| 643 |
} |
| 644 |
_, s.err = s.w.Write(frame) |
| 645 |
} |
| 646 |
if s.err == nil { |
| 647 |
s.err = ErrEncoderClosed |
| 648 |
return nil |
| 649 |
} |
| 650 |
|
| 651 |
return s.err |
| 652 |
} |
| 653 |
|
| 654 |
func (e *Encoder) closeJobs() error { |
| 655 |
s := &e.state |
| 656 |
js := &s.jobs |
| 657 |
|
| 658 |
if errors.Is(s.err, ErrEncoderClosed) { |
| 659 |
return nil |
| 660 |
} |
| 661 |
|
| 662 |
if s.w == nil { |
| 663 |
if len(js.filling) == 0 && !s.headerWritten && !s.eofWritten && s.nInput == 0 { |
| 664 |
return nil |
| 665 |
} |
| 666 |
return errors.New("zstd: encoder has no writer") |
| 667 |
} |
| 668 |
|
| 669 |
if err := e.dispatchJob(true); err != nil { |
| 670 |
e.shutdownJobWorkers() |
| 671 |
if errors.Is(s.err, ErrEncoderClosed) { |
| 672 |
return nil |
| 673 |
} |
| 674 |
return err |
| 675 |
} |
| 676 |
|
| 677 |
if s.frameContentSize > 0 && s.nInput != s.frameContentSize { |
| 678 |
e.shutdownJobWorkers() |
| 679 |
return fmt.Errorf("frame content size %d given, but %d bytes was written", s.frameContentSize, s.nInput) |
| 680 |
} |
| 681 |
|
| 682 |
if s.fullFrameWritten { |
| 683 |
e.shutdownJobWorkers() |
| 684 |
s.err = ErrEncoderClosed |
| 685 |
return nil |
| 686 |
} |
| 687 |
|
| 688 |
e.shutdownJobWorkers() |
| 689 |
if js.flusherErr != nil { |
| 690 |
return js.flusherErr |
| 691 |
} |
| 692 |
|
| 693 |
// Write CRC |
| 694 |
if e.o.crc { |
| 695 |
var tmp [4]byte |
| 696 |
_, s.err = s.w.Write(s.encoder.AppendCRC(tmp[:0])) |
| 697 |
s.nWritten += 4 |
| 698 |
} |
| 699 |
|
| 700 |
// Add padding |
| 701 |
if s.err == nil && e.o.pad > 0 { |
| 702 |
add := calcSkippableFrame(s.nWritten, int64(e.o.pad)) |
| 703 |
frame, err := skippableFrame(js.filling[:0], add, rand.Reader) |
| 704 |
if err != nil { |
| 705 |
return err |
| 706 |
} |
| 707 |
_, s.err = s.w.Write(frame) |
| 708 |
} |
| 709 |
if s.err == nil { |
| 710 |
s.err = ErrEncoderClosed |
| 711 |
return nil |
| 712 |
} |
| 713 |
return s.err |
| 714 |
} |
| 715 |
|
| 716 |
// EncodeAll will encode all input in src and append it to dst. |
| 717 |
// This function can be called concurrently, but each call will only run on a single goroutine. |
| 718 |
// If empty input is given, nothing is returned, unless WithZeroFrames is specified. |
| 719 |
// Encoded blocks can be concatenated and the result will be the combined input stream. |
| 720 |
// Data compressed with EncodeAll can be decoded with the Decoder, |
| 721 |
// using either a stream or DecodeAll. |
| 722 |
func (e *Encoder) EncodeAll(src, dst []byte) []byte { |
| 723 |
e.init.Do(e.initialize) |
| 724 |
enc := <-e.encoders |
| 725 |
defer func() { |
| 726 |
e.encoders <- enc |
| 727 |
}() |
| 728 |
return e.encodeAll(enc, src, dst) |
| 729 |
} |
| 730 |
|
| 731 |
func (e *Encoder) encodeAll(enc encoder, src, dst []byte) []byte { |
| 732 |
if len(src) == 0 { |
| 733 |
if e.o.fullZero { |
| 734 |
// Add frame header. |
| 735 |
fh := frameHeader{ |
| 736 |
ContentSize: 0, |
| 737 |
WindowSize: MinWindowSize, |
| 738 |
SingleSegment: true, |
| 739 |
// Adding a checksum would be a waste of space. |
| 740 |
Checksum: false, |
| 741 |
DictID: 0, |
| 742 |
} |
| 743 |
dst = fh.appendTo(dst) |
| 744 |
|
| 745 |
// Write raw block as last one only. |
| 746 |
var blk blockHeader |
| 747 |
blk.setSize(0) |
| 748 |
blk.setType(blockTypeRaw) |
| 749 |
blk.setLast(true) |
| 750 |
dst = blk.appendTo(dst) |
| 751 |
} |
| 752 |
return dst |
| 753 |
} |
| 754 |
|
| 755 |
// Use single segments when above minimum window and below window size. |
| 756 |
single := len(src) <= e.o.windowSize && len(src) > MinWindowSize |
| 757 |
if e.o.single != nil { |
| 758 |
single = *e.o.single |
| 759 |
} |
| 760 |
fh := frameHeader{ |
| 761 |
ContentSize: uint64(len(src)), |
| 762 |
WindowSize: uint32(enc.WindowSize(int64(len(src)))), |
| 763 |
SingleSegment: single, |
| 764 |
Checksum: e.o.crc, |
| 765 |
DictID: e.o.dict.ID(), |
| 766 |
} |
| 767 |
|
| 768 |
// If less than 1MB, allocate a buffer up front. |
| 769 |
if len(dst) == 0 && cap(dst) == 0 && len(src) < 1<<20 && !e.o.lowMem { |
| 770 |
dst = make([]byte, 0, len(src)) |
| 771 |
} |
| 772 |
dst = fh.appendTo(dst) |
| 773 |
|
| 774 |
// If we can do everything in one block, prefer that. |
| 775 |
if len(src) <= e.o.blockSize { |
| 776 |
enc.Reset(e.o.dict, true) |
| 777 |
// Slightly faster with no history and everything in one block. |
| 778 |
if e.o.crc { |
| 779 |
_, _ = enc.CRC().Write(src) |
| 780 |
} |
| 781 |
blk := enc.Block() |
| 782 |
blk.last = true |
| 783 |
if e.o.dict == nil { |
| 784 |
enc.EncodeNoHist(blk, src) |
| 785 |
} else { |
| 786 |
enc.Encode(blk, src) |
| 787 |
} |
| 788 |
|
| 789 |
// If we got the exact same number of literals as input, |
| 790 |
// assume the literals cannot be compressed. |
| 791 |
oldout := blk.output |
| 792 |
// Output directly to dst |
| 793 |
blk.output = dst |
| 794 |
|
| 795 |
err := blk.encode(src, e.o.noEntropy, !e.o.allLitEntropy) |
| 796 |
if err != nil { |
| 797 |
panic(err) |
| 798 |
} |
| 799 |
dst = blk.output |
| 800 |
blk.output = oldout |
| 801 |
} else { |
| 802 |
enc.Reset(e.o.dict, false) |
| 803 |
blk := enc.Block() |
| 804 |
for len(src) > 0 { |
| 805 |
todo := src |
| 806 |
if len(todo) > e.o.blockSize { |
| 807 |
todo = todo[:e.o.blockSize] |
| 808 |
} |
| 809 |
src = src[len(todo):] |
| 810 |
if e.o.crc { |
| 811 |
_, _ = enc.CRC().Write(todo) |
| 812 |
} |
| 813 |
blk.pushOffsets() |
| 814 |
enc.Encode(blk, todo) |
| 815 |
if len(src) == 0 { |
| 816 |
blk.last = true |
| 817 |
} |
| 818 |
err := blk.encode(todo, e.o.noEntropy, !e.o.allLitEntropy) |
| 819 |
if err != nil { |
| 820 |
panic(err) |
| 821 |
} |
| 822 |
dst = append(dst, blk.output...) |
| 823 |
blk.reset(nil) |
| 824 |
} |
| 825 |
} |
| 826 |
if e.o.crc { |
| 827 |
dst = enc.AppendCRC(dst) |
| 828 |
} |
| 829 |
// Add padding with content from crypto/rand.Reader |
| 830 |
if e.o.pad > 0 { |
| 831 |
add := calcSkippableFrame(int64(len(dst)), int64(e.o.pad)) |
| 832 |
var err error |
| 833 |
dst, err = skippableFrame(dst, add, rand.Reader) |
| 834 |
if err != nil { |
| 835 |
panic(err) |
| 836 |
} |
| 837 |
} |
| 838 |
return dst |
| 839 |
} |
| 840 |
|
| 841 |
// MaxEncodedSize returns the expected maximum |
| 842 |
// size of an encoded block or stream. |
| 843 |
func (e *Encoder) MaxEncodedSize(size int) int { |
| 844 |
frameHeader := 4 + 2 // magic + frame header & window descriptor |
| 845 |
if e.o.dict != nil { |
| 846 |
frameHeader += 4 |
| 847 |
} |
| 848 |
// Frame content size: |
| 849 |
if size < 256 { |
| 850 |
frameHeader++ |
| 851 |
} else if size < 65536+256 { |
| 852 |
frameHeader += 2 |
| 853 |
} else if size < math.MaxInt32 { |
| 854 |
frameHeader += 4 |
| 855 |
} else { |
| 856 |
frameHeader += 8 |
| 857 |
} |
| 858 |
// Final crc |
| 859 |
if e.o.crc { |
| 860 |
frameHeader += 4 |
| 861 |
} |
| 862 |
|
| 863 |
// Max overhead is 3 bytes/block. |
| 864 |
// There cannot be 0 blocks. |
| 865 |
blocks := (size + e.o.blockSize) / e.o.blockSize |
| 866 |
|
| 867 |
// Combine, add padding. |
| 868 |
maxSz := frameHeader + 3*blocks + size |
| 869 |
if e.o.pad > 1 { |
| 870 |
maxSz += calcSkippableFrame(int64(maxSz), int64(e.o.pad)) |
| 871 |
} |
| 872 |
return maxSz |
| 873 |
} |