Debian Codegraph @

s2/writer.go

raw
1 // Copyright 2011 The Snappy-Go Authors. All rights reserved.
2 // Copyright (c) 2019+ Klaus Post. All rights reserved.
3 // Use of this source code is governed by a BSD-style
4 // license that can be found in the LICENSE file.
5
6 package s2
7
8 import (
9 "crypto/rand"
10 "encoding/binary"
11 "errors"
12 "fmt"
13 "io"
14 "runtime"
15 "sync"
16
17 "github.com/klauspost/compress/internal/race"
18 )
19
20 const (
21 levelUncompressed = iota + 1
22 levelFast
23 levelBetter
24 levelBest
25 )
26
27 // NewWriter returns a new Writer that compresses to w, using the
28 // framing format described at
29 // https://github.com/google/snappy/blob/master/framing_format.txt
30 //
31 // Users must call Close to guarantee all data has been forwarded to
32 // the underlying io.Writer and that resources are released.
33 // They may also call Flush zero or more times before calling Close.
34 func NewWriter(w io.Writer, opts ...WriterOption) *Writer {
35 w2 := Writer{
36 blockSize: defaultBlockSize,
37 concurrency: runtime.GOMAXPROCS(0),
38 randSrc: rand.Reader,
39 level: levelFast,
40 }
41 for _, opt := range opts {
42 if err := opt(&w2); err != nil {
43 w2.errState = err
44 return &w2
45 }
46 }
47 w2.obufLen = obufHeaderLen + MaxEncodedLen(w2.blockSize)
48 w2.paramsOK = true
49 w2.ibuf = make([]byte, 0, w2.blockSize)
50 w2.buffers.New = func() any {
51 return make([]byte, w2.obufLen)
52 }
53 w2.Reset(w)
54 return &w2
55 }
56
57 // Writer is an io.Writer that can write Snappy-compressed bytes.
58 type Writer struct {
59 errMu sync.Mutex
60 errState error
61
62 // ibuf is a buffer for the incoming (uncompressed) bytes.
63 ibuf []byte
64
65 blockSize int
66 obufLen int
67 concurrency int
68 written int64
69 uncompWritten int64 // Bytes sent to compression
70 output chan chan result
71 buffers sync.Pool
72 pad int
73
74 writer io.Writer
75 randSrc io.Reader
76 writerWg sync.WaitGroup
77 index Index
78 customEnc func(dst, src []byte) int
79
80 // wroteStreamHeader is whether we have written the stream header.
81 wroteStreamHeader bool
82 paramsOK bool
83 snappy bool
84 flushOnWrite bool
85 appendIndex bool
86 bufferCB func([]byte)
87 level uint8
88 }
89
90 type result struct {
91 b []byte
92 // return when writing
93 ret []byte
94 // Uncompressed start offset
95 startOffset int64
96 }
97
98 // err returns the previously set error.
99 // If no error has been set it is set to err if not nil.
100 func (w *Writer) err(err error) error {
101 w.errMu.Lock()
102 errSet := w.errState
103 if errSet == nil && err != nil {
104 w.errState = err
105 errSet = err
106 }
107 w.errMu.Unlock()
108 return errSet
109 }
110
111 // Reset discards the writer's state and switches the Snappy writer to write to w.
112 // This permits reusing a Writer rather than allocating a new one.
113 func (w *Writer) Reset(writer io.Writer) {
114 if !w.paramsOK {
115 return
116 }
117 // Close previous writer, if any.
118 if w.output != nil {
119 close(w.output)
120 w.writerWg.Wait()
121 w.output = nil
122 }
123 w.errState = nil
124 w.ibuf = w.ibuf[:0]
125 w.wroteStreamHeader = false
126 w.written = 0
127 w.writer = writer
128 w.uncompWritten = 0
129 w.index.reset(w.blockSize)
130
131 // If we didn't get a writer, stop here.
132 if writer == nil {
133 return
134 }
135 // If no concurrency requested, don't spin up writer goroutine.
136 if w.concurrency == 1 {
137 return
138 }
139
140 toWrite := make(chan chan result, w.concurrency)
141 w.output = toWrite
142
143 // Start a writer goroutine that will write all output in order.
144 w.writerWg.Go(func() {
145
146 // Get a queued write.
147 for write := range toWrite {
148 // Wait for the data to be available.
149 input := <-write
150 if input.ret != nil && w.bufferCB != nil {
151 w.bufferCB(input.ret)
152 input.ret = nil
153 }
154 in := input.b
155 if len(in) > 0 {
156 if w.err(nil) == nil {
157 // Don't expose data from previous buffers.
158 toWrite := in[:len(in):len(in)]
159 // Write to output.
160 n, err := writer.Write(toWrite)
161 if err == nil && n != len(toWrite) {
162 err = io.ErrShortBuffer
163 }
164 _ = w.err(err)
165 w.err(w.index.add(w.written, input.startOffset))
166 w.written += int64(n)
167 }
168 }
169 if cap(in) >= w.obufLen {
170 w.buffers.Put(in)
171 }
172 // close the incoming write request.
173 // This can be used for synchronizing flushes.
174 close(write)
175 }
176 })
177 }
178
179 // Write satisfies the io.Writer interface.
180 func (w *Writer) Write(p []byte) (nRet int, errRet error) {
181 if err := w.err(nil); err != nil {
182 return 0, err
183 }
184 if w.flushOnWrite {
185 return w.write(p)
186 }
187 // If we exceed the input buffer size, start writing
188 for len(p) > (cap(w.ibuf)-len(w.ibuf)) && w.err(nil) == nil {
189 var n int
190 if len(w.ibuf) == 0 {
191 // Large write, empty buffer.
192 // Write directly from p to avoid copy.
193 n, _ = w.write(p)
194 } else {
195 n = copy(w.ibuf[len(w.ibuf):cap(w.ibuf)], p)
196 w.ibuf = w.ibuf[:len(w.ibuf)+n]
197 w.write(w.ibuf)
198 w.ibuf = w.ibuf[:0]
199 }
200 nRet += n
201 p = p[n:]
202 }
203 if err := w.err(nil); err != nil {
204 return nRet, err
205 }
206 // p should always be able to fit into w.ibuf now.
207 n := copy(w.ibuf[len(w.ibuf):cap(w.ibuf)], p)
208 w.ibuf = w.ibuf[:len(w.ibuf)+n]
209 nRet += n
210 return nRet, nil
211 }
212
213 // ReadFrom implements the io.ReaderFrom interface.
214 // Using this is typically more efficient since it avoids a memory copy.
215 // ReadFrom reads data from r until EOF or error.
216 // The return value n is the number of bytes read.
217 // Any error except io.EOF encountered during the read is also returned.
218 func (w *Writer) ReadFrom(r io.Reader) (n int64, err error) {
219 if err := w.err(nil); err != nil {
220 return 0, err
221 }
222 if len(w.ibuf) > 0 {
223 err := w.AsyncFlush()
224 if err != nil {
225 return 0, err
226 }
227 }
228 if br, ok := r.(byter); ok {
229 buf := br.Bytes()
230 if err := w.EncodeBuffer(buf); err != nil {
231 return 0, err
232 }
233 return int64(len(buf)), w.AsyncFlush()
234 }
235 for {
236 inbuf := w.buffers.Get().([]byte)[:w.blockSize+obufHeaderLen]
237 n2, err := io.ReadFull(r, inbuf[obufHeaderLen:])
238 if err != nil {
239 if err == io.ErrUnexpectedEOF {
240 err = io.EOF
241 }
242 if err != io.EOF {
243 return n, w.err(err)
244 }
245 }
246 if n2 == 0 {
247 if cap(inbuf) >= w.obufLen {
248 w.buffers.Put(inbuf)
249 }
250 break
251 }
252 n += int64(n2)
253 err2 := w.writeFull(inbuf[:n2+obufHeaderLen])
254 if w.err(err2) != nil {
255 break
256 }
257
258 if err != nil {
259 // We got EOF and wrote everything
260 break
261 }
262 }
263
264 return n, w.err(nil)
265 }
266
267 // AddSkippableBlock will add a skippable block to the stream.
268 // The ID must be 0x80-0xfe (inclusive).
269 // Length of the skippable block must be <= 16777215 bytes.
270 func (w *Writer) AddSkippableBlock(id uint8, data []byte) (err error) {
271 if err := w.err(nil); err != nil {
272 return err
273 }
274 if len(data) == 0 {
275 return nil
276 }
277 if id < 0x80 || id > chunkTypePadding {
278 return fmt.Errorf("invalid skippable block id %x", id)
279 }
280 if len(data) > maxChunkSize {
281 return fmt.Errorf("skippable block excessed maximum size")
282 }
283 var header [4]byte
284 chunkLen := len(data)
285 header[0] = id
286 header[1] = uint8(chunkLen >> 0)
287 header[2] = uint8(chunkLen >> 8)
288 header[3] = uint8(chunkLen >> 16)
289 if w.concurrency == 1 {
290 write := func(b []byte) error {
291 n, err := w.writer.Write(b)
292 if err = w.err(err); err != nil {
293 return err
294 }
295 if n != len(b) {
296 return w.err(io.ErrShortWrite)
297 }
298 w.written += int64(n)
299 return w.err(nil)
300 }
301 if !w.wroteStreamHeader {
302 w.wroteStreamHeader = true
303 if w.snappy {
304 if err := write([]byte(magicChunkSnappy)); err != nil {
305 return err
306 }
307 } else {
308 if err := write([]byte(magicChunk)); err != nil {
309 return err
310 }
311 }
312 }
313 if err := write(header[:]); err != nil {
314 return err
315 }
316 return write(data)
317 }
318
319 // Create output...
320 if !w.wroteStreamHeader {
321 w.wroteStreamHeader = true
322 hWriter := make(chan result)
323 w.output <- hWriter
324 if w.snappy {
325 hWriter <- result{startOffset: w.uncompWritten, b: magicChunkSnappyBytes}
326 } else {
327 hWriter <- result{startOffset: w.uncompWritten, b: magicChunkBytes}
328 }
329 }
330
331 // Copy input.
332 inbuf := w.buffers.Get().([]byte)[:4]
333 copy(inbuf, header[:])
334 inbuf = append(inbuf, data...)
335
336 output := make(chan result, 1)
337 // Queue output.
338 w.output <- output
339 output <- result{startOffset: w.uncompWritten, b: inbuf}
340
341 return nil
342 }
343
344 // EncodeBuffer will add a buffer to the stream.
345 // This is the fastest way to encode a stream,
346 // but the input buffer cannot be written to by the caller
347 // until Flush or Close has been called when concurrency != 1.
348 //
349 // Use the WriterBufferDone to receive a callback when the buffer is done
350 // Processing.
351 //
352 // Note that input is not buffered.
353 // This means that each write will result in discrete blocks being created.
354 // For buffered writes, use the regular Write function.
355 func (w *Writer) EncodeBuffer(buf []byte) (err error) {
356 if err := w.err(nil); err != nil {
357 return err
358 }
359
360 if w.flushOnWrite {
361 _, err := w.write(buf)
362 return err
363 }
364 // Flush queued data first.
365 if len(w.ibuf) > 0 {
366 err := w.AsyncFlush()
367 if err != nil {
368 return err
369 }
370 }
371 if w.concurrency == 1 {
372 _, err := w.writeSync(buf)
373 if w.bufferCB != nil {
374 w.bufferCB(buf)
375 }
376 return err
377 }
378
379 // Spawn goroutine and write block to output channel.
380 if !w.wroteStreamHeader {
381 w.wroteStreamHeader = true
382 hWriter := make(chan result)
383 w.output <- hWriter
384 if w.snappy {
385 hWriter <- result{startOffset: w.uncompWritten, b: magicChunkSnappyBytes}
386 } else {
387 hWriter <- result{startOffset: w.uncompWritten, b: magicChunkBytes}
388 }
389 }
390 orgBuf := buf
391 for len(buf) > 0 {
392 // Cut input.
393 uncompressed := buf
394 if len(uncompressed) > w.blockSize {
395 uncompressed = uncompressed[:w.blockSize]
396 }
397 buf = buf[len(uncompressed):]
398 // Get an output buffer.
399 obuf := w.buffers.Get().([]byte)[:len(uncompressed)+obufHeaderLen]
400 race.WriteSlice(obuf)
401
402 output := make(chan result)
403 // Queue output now, so we keep order.
404 w.output <- output
405 res := result{
406 startOffset: w.uncompWritten,
407 }
408 w.uncompWritten += int64(len(uncompressed))
409 if len(buf) == 0 && w.bufferCB != nil {
410 res.ret = orgBuf
411 }
412 go func() {
413 race.ReadSlice(uncompressed)
414
415 checksum := crc(uncompressed)
416
417 // Set to uncompressed.
418 chunkType := uint8(chunkTypeUncompressedData)
419 chunkLen := 4 + len(uncompressed)
420
421 // Attempt compressing.
422 n := binary.PutUvarint(obuf[obufHeaderLen:], uint64(len(uncompressed)))
423 n2 := w.encodeBlock(obuf[obufHeaderLen+n:], uncompressed)
424
425 // Check if we should use this, or store as uncompressed instead.
426 if n2 > 0 {
427 chunkType = uint8(chunkTypeCompressedData)
428 chunkLen = 4 + n + n2
429 obuf = obuf[:obufHeaderLen+n+n2]
430 } else {
431 // copy uncompressed
432 copy(obuf[obufHeaderLen:], uncompressed)
433 }
434
435 // Fill in the per-chunk header that comes before the body.
436 obuf[0] = chunkType
437 obuf[1] = uint8(chunkLen >> 0)
438 obuf[2] = uint8(chunkLen >> 8)
439 obuf[3] = uint8(chunkLen >> 16)
440 obuf[4] = uint8(checksum >> 0)
441 obuf[5] = uint8(checksum >> 8)
442 obuf[6] = uint8(checksum >> 16)
443 obuf[7] = uint8(checksum >> 24)
444
445 // Queue final output.
446 res.b = obuf
447 output <- res
448 }()
449 }
450 return nil
451 }
452
453 func (w *Writer) encodeBlock(obuf, uncompressed []byte) int {
454 if w.customEnc != nil {
455 if ret := w.customEnc(obuf, uncompressed); ret >= 0 {
456 return ret
457 }
458 }
459 if w.snappy {
460 switch w.level {
461 case levelFast:
462 return encodeBlockSnappy(obuf, uncompressed)
463 case levelBetter:
464 return encodeBlockBetterSnappy(obuf, uncompressed)
465 case levelBest:
466 return encodeBlockBestSnappy(obuf, uncompressed)
467 }
468 return 0
469 }
470 switch w.level {
471 case levelFast:
472 return encodeBlock(obuf, uncompressed)
473 case levelBetter:
474 return encodeBlockBetter(obuf, uncompressed)
475 case levelBest:
476 return encodeBlockBest(obuf, uncompressed, nil)
477 }
478 return 0
479 }
480
481 func (w *Writer) write(p []byte) (nRet int, errRet error) {
482 if err := w.err(nil); err != nil {
483 return 0, err
484 }
485 if w.concurrency == 1 {
486 return w.writeSync(p)
487 }
488
489 // Spawn goroutine and write block to output channel.
490 for len(p) > 0 {
491 if !w.wroteStreamHeader {
492 w.wroteStreamHeader = true
493 hWriter := make(chan result)
494 w.output <- hWriter
495 if w.snappy {
496 hWriter <- result{startOffset: w.uncompWritten, b: magicChunkSnappyBytes}
497 } else {
498 hWriter <- result{startOffset: w.uncompWritten, b: magicChunkBytes}
499 }
500 }
501
502 var uncompressed []byte
503 if len(p) > w.blockSize {
504 uncompressed, p = p[:w.blockSize], p[w.blockSize:]
505 } else {
506 uncompressed, p = p, nil
507 }
508
509 // Copy input.
510 // If the block is incompressible, this is used for the result.
511 inbuf := w.buffers.Get().([]byte)[:len(uncompressed)+obufHeaderLen]
512 obuf := w.buffers.Get().([]byte)[:w.obufLen]
513 copy(inbuf[obufHeaderLen:], uncompressed)
514 uncompressed = inbuf[obufHeaderLen:]
515
516 output := make(chan result)
517 // Queue output now, so we keep order.
518 w.output <- output
519 res := result{
520 startOffset: w.uncompWritten,
521 }
522 w.uncompWritten += int64(len(uncompressed))
523
524 go func() {
525 checksum := crc(uncompressed)
526
527 // Set to uncompressed.
528 chunkType := uint8(chunkTypeUncompressedData)
529 chunkLen := 4 + len(uncompressed)
530
531 // Attempt compressing.
532 n := binary.PutUvarint(obuf[obufHeaderLen:], uint64(len(uncompressed)))
533 n2 := w.encodeBlock(obuf[obufHeaderLen+n:], uncompressed)
534
535 // Check if we should use this, or store as uncompressed instead.
536 if n2 > 0 {
537 chunkType = uint8(chunkTypeCompressedData)
538 chunkLen = 4 + n + n2
539 obuf = obuf[:obufHeaderLen+n+n2]
540 } else {
541 // Use input as output.
542 obuf, inbuf = inbuf, obuf
543 }
544
545 // Fill in the per-chunk header that comes before the body.
546 obuf[0] = chunkType
547 obuf[1] = uint8(chunkLen >> 0)
548 obuf[2] = uint8(chunkLen >> 8)
549 obuf[3] = uint8(chunkLen >> 16)
550 obuf[4] = uint8(checksum >> 0)
551 obuf[5] = uint8(checksum >> 8)
552 obuf[6] = uint8(checksum >> 16)
553 obuf[7] = uint8(checksum >> 24)
554
555 // Queue final output.
556 res.b = obuf
557 output <- res
558
559 // Put unused buffer back in pool.
560 w.buffers.Put(inbuf)
561 }()
562 nRet += len(uncompressed)
563 }
564 return nRet, nil
565 }
566
567 // writeFull is a special version of write that will always write the full buffer.
568 // Data to be compressed should start at offset obufHeaderLen and fill the remainder of the buffer.
569 // The data will be written as a single block.
570 // The caller is not allowed to use inbuf after this function has been called.
571 func (w *Writer) writeFull(inbuf []byte) (errRet error) {
572 if err := w.err(nil); err != nil {
573 return err
574 }
575
576 if w.concurrency == 1 {
577 _, err := w.writeSync(inbuf[obufHeaderLen:])
578 if cap(inbuf) >= w.obufLen {
579 w.buffers.Put(inbuf)
580 }
581 return err
582 }
583
584 // Spawn goroutine and write block to output channel.
585 if !w.wroteStreamHeader {
586 w.wroteStreamHeader = true
587 hWriter := make(chan result)
588 w.output <- hWriter
589 if w.snappy {
590 hWriter <- result{startOffset: w.uncompWritten, b: magicChunkSnappyBytes}
591 } else {
592 hWriter <- result{startOffset: w.uncompWritten, b: magicChunkBytes}
593 }
594 }
595
596 // Get an output buffer.
597 obuf := w.buffers.Get().([]byte)[:w.obufLen]
598 uncompressed := inbuf[obufHeaderLen:]
599
600 output := make(chan result)
601 // Queue output now, so we keep order.
602 w.output <- output
603 res := result{
604 startOffset: w.uncompWritten,
605 }
606 w.uncompWritten += int64(len(uncompressed))
607
608 go func() {
609 checksum := crc(uncompressed)
610
611 // Set to uncompressed.
612 chunkType := uint8(chunkTypeUncompressedData)
613 chunkLen := 4 + len(uncompressed)
614
615 // Attempt compressing.
616 n := binary.PutUvarint(obuf[obufHeaderLen:], uint64(len(uncompressed)))
617 n2 := w.encodeBlock(obuf[obufHeaderLen+n:], uncompressed)
618
619 // Check if we should use this, or store as uncompressed instead.
620 if n2 > 0 {
621 chunkType = uint8(chunkTypeCompressedData)
622 chunkLen = 4 + n + n2
623 obuf = obuf[:obufHeaderLen+n+n2]
624 } else {
625 // Use input as output.
626 obuf, inbuf = inbuf, obuf
627 }
628
629 // Fill in the per-chunk header that comes before the body.
630 obuf[0] = chunkType
631 obuf[1] = uint8(chunkLen >> 0)
632 obuf[2] = uint8(chunkLen >> 8)
633 obuf[3] = uint8(chunkLen >> 16)
634 obuf[4] = uint8(checksum >> 0)
635 obuf[5] = uint8(checksum >> 8)
636 obuf[6] = uint8(checksum >> 16)
637 obuf[7] = uint8(checksum >> 24)
638
639 // Queue final output.
640 res.b = obuf
641 output <- res
642
643 // Put unused buffer back in pool.
644 w.buffers.Put(inbuf)
645 }()
646 return nil
647 }
648
649 func (w *Writer) writeSync(p []byte) (nRet int, errRet error) {
650 if err := w.err(nil); err != nil {
651 return 0, err
652 }
653 if !w.wroteStreamHeader {
654 w.wroteStreamHeader = true
655 var n int
656 var err error
657 if w.snappy {
658 n, err = w.writer.Write(magicChunkSnappyBytes)
659 } else {
660 n, err = w.writer.Write(magicChunkBytes)
661 }
662 if err != nil {
663 return 0, w.err(err)
664 }
665 if n != len(magicChunk) {
666 return 0, w.err(io.ErrShortWrite)
667 }
668 w.written += int64(n)
669 }
670
671 for len(p) > 0 {
672 var uncompressed []byte
673 if len(p) > w.blockSize {
674 uncompressed, p = p[:w.blockSize], p[w.blockSize:]
675 } else {
676 uncompressed, p = p, nil
677 }
678
679 obuf := w.buffers.Get().([]byte)[:w.obufLen]
680 checksum := crc(uncompressed)
681
682 // Set to uncompressed.
683 chunkType := uint8(chunkTypeUncompressedData)
684 chunkLen := 4 + len(uncompressed)
685
686 // Attempt compressing.
687 n := binary.PutUvarint(obuf[obufHeaderLen:], uint64(len(uncompressed)))
688 n2 := w.encodeBlock(obuf[obufHeaderLen+n:], uncompressed)
689
690 if n2 > 0 {
691 chunkType = uint8(chunkTypeCompressedData)
692 chunkLen = 4 + n + n2
693 obuf = obuf[:obufHeaderLen+n+n2]
694 } else {
695 obuf = obuf[:8]
696 }
697
698 // Fill in the per-chunk header that comes before the body.
699 obuf[0] = chunkType
700 obuf[1] = uint8(chunkLen >> 0)
701 obuf[2] = uint8(chunkLen >> 8)
702 obuf[3] = uint8(chunkLen >> 16)
703 obuf[4] = uint8(checksum >> 0)
704 obuf[5] = uint8(checksum >> 8)
705 obuf[6] = uint8(checksum >> 16)
706 obuf[7] = uint8(checksum >> 24)
707
708 n, err := w.writer.Write(obuf)
709 if err != nil {
710 return 0, w.err(err)
711 }
712 if n != len(obuf) {
713 return 0, w.err(io.ErrShortWrite)
714 }
715 w.err(w.index.add(w.written, w.uncompWritten))
716 w.written += int64(n)
717 w.uncompWritten += int64(len(uncompressed))
718
719 if chunkType == chunkTypeUncompressedData {
720 // Write uncompressed data.
721 n, err := w.writer.Write(uncompressed)
722 if err != nil {
723 return 0, w.err(err)
724 }
725 if n != len(uncompressed) {
726 return 0, w.err(io.ErrShortWrite)
727 }
728 w.written += int64(n)
729 }
730 w.buffers.Put(obuf)
731 // Queue final output.
732 nRet += len(uncompressed)
733 }
734 return nRet, nil
735 }
736
737 // AsyncFlush writes any buffered bytes to a block and starts compressing it.
738 // It does not wait for the output has been written as Flush() does.
739 func (w *Writer) AsyncFlush() error {
740 if err := w.err(nil); err != nil {
741 return err
742 }
743
744 // Queue any data still in input buffer.
745 if len(w.ibuf) != 0 {
746 if !w.wroteStreamHeader {
747 _, err := w.writeSync(w.ibuf)
748 w.ibuf = w.ibuf[:0]
749 return w.err(err)
750 } else {
751 _, err := w.write(w.ibuf)
752 w.ibuf = w.ibuf[:0]
753 err = w.err(err)
754 if err != nil {
755 return err
756 }
757 }
758 }
759 return w.err(nil)
760 }
761
762 // Flush flushes the Writer to its underlying io.Writer.
763 // This does not apply padding.
764 func (w *Writer) Flush() error {
765 if err := w.AsyncFlush(); err != nil {
766 return err
767 }
768 if w.output == nil {
769 return w.err(nil)
770 }
771
772 // Send empty buffer
773 res := make(chan result)
774 w.output <- res
775 // Block until this has been picked up.
776 res <- result{b: nil, startOffset: w.uncompWritten}
777 // When it is closed, we have flushed.
778 <-res
779 return w.err(nil)
780 }
781
782 // Close calls Flush and then closes the Writer.
783 // Calling Close multiple times is ok,
784 // but calling CloseIndex after this will make it not return the index.
785 func (w *Writer) Close() error {
786 _, err := w.closeIndex(w.appendIndex)
787 return err
788 }
789
790 // CloseIndex calls Close and returns an index on first call.
791 // This is not required if you are only adding index to a stream.
792 func (w *Writer) CloseIndex() ([]byte, error) {
793 return w.closeIndex(true)
794 }
795
796 func (w *Writer) closeIndex(idx bool) ([]byte, error) {
797 err := w.Flush()
798 if w.output != nil {
799 close(w.output)
800 w.writerWg.Wait()
801 w.output = nil
802 }
803
804 var index []byte
805 if w.err(err) == nil && w.writer != nil {
806 // Create index.
807 if idx {
808 compSize := int64(-1)
809 if w.pad <= 1 {
810 compSize = w.written
811 }
812 index = w.index.appendTo(w.ibuf[:0], w.uncompWritten, compSize)
813 // Count as written for padding.
814 if w.appendIndex {
815 w.written += int64(len(index))
816 }
817 }
818
819 if w.pad > 1 {
820 tmp := w.ibuf[:0]
821 if len(index) > 0 {
822 // Allocate another buffer.
823 tmp = w.buffers.Get().([]byte)[:0]
824 defer w.buffers.Put(tmp)
825 }
826 add := calcSkippableFrame(w.written, int64(w.pad))
827 frame, err := skippableFrame(tmp, add, w.randSrc)
828 if err = w.err(err); err != nil {
829 return nil, err
830 }
831 n, err2 := w.writer.Write(frame)
832 if err2 == nil && n != len(frame) {
833 err2 = io.ErrShortWrite
834 }
835 _ = w.err(err2)
836 }
837 if len(index) > 0 && w.appendIndex {
838 n, err2 := w.writer.Write(index)
839 if err2 == nil && n != len(index) {
840 err2 = io.ErrShortWrite
841 }
842 _ = w.err(err2)
843 }
844 }
845 err = w.err(errClosed)
846 if err == errClosed {
847 return index, nil
848 }
849 return nil, err
850 }
851
852 // calcSkippableFrame will return a total size to be added for written
853 // to be divisible by multiple.
854 // The value will always be > skippableFrameHeader.
855 // The function will panic if written < 0 or wantMultiple <= 0.
856 func calcSkippableFrame(written, wantMultiple int64) int {
857 if wantMultiple <= 0 {
858 panic("wantMultiple <= 0")
859 }
860 if written < 0 {
861 panic("written < 0")
862 }
863 leftOver := written % wantMultiple
864 if leftOver == 0 {
865 return 0
866 }
867 toAdd := wantMultiple - leftOver
868 for toAdd < skippableFrameHeader {
869 toAdd += wantMultiple
870 }
871 return int(toAdd)
872 }
873
874 // skippableFrame will add a skippable frame with a total size of bytes.
875 // total should be >= skippableFrameHeader and < maxBlockSize + skippableFrameHeader
876 func skippableFrame(dst []byte, total int, r io.Reader) ([]byte, error) {
877 if total == 0 {
878 return dst, nil
879 }
880 if total < skippableFrameHeader {
881 return dst, fmt.Errorf("s2: requested skippable frame (%d) < 4", total)
882 }
883 if int64(total) >= maxBlockSize+skippableFrameHeader {
884 return dst, fmt.Errorf("s2: requested skippable frame (%d) >= max 1<<24", total)
885 }
886 // Chunk type 0xfe "Section 4.4 Padding (chunk type 0xfe)"
887 dst = append(dst, chunkTypePadding)
888 f := uint32(total - skippableFrameHeader)
889 // Add chunk length.
890 dst = append(dst, uint8(f), uint8(f>>8), uint8(f>>16))
891 // Add data
892 start := len(dst)
893 dst = append(dst, make([]byte, f)...)
894 _, err := io.ReadFull(r, dst[start:])
895 return dst, err
896 }
897
898 var errClosed = errors.New("s2: Writer is closed")
899
900 // WriterOption is an option for creating a encoder.
901 type WriterOption func(*Writer) error
902
903 // WriterConcurrency will set the concurrency,
904 // meaning the maximum number of decoders to run concurrently.
905 // The value supplied must be at least 1.
906 // By default this will be set to GOMAXPROCS.
907 func WriterConcurrency(n int) WriterOption {
908 return func(w *Writer) error {
909 if n <= 0 {
910 return errors.New("concurrency must be at least 1")
911 }
912 w.concurrency = n
913 return nil
914 }
915 }
916
917 // WriterAddIndex will append an index to the end of a stream
918 // when it is closed.
919 func WriterAddIndex() WriterOption {
920 return func(w *Writer) error {
921 w.appendIndex = true
922 return nil
923 }
924 }
925
926 // WriterBetterCompression will enable better compression.
927 // EncodeBetter compresses better than Encode but typically with a
928 // 10-40% speed decrease on both compression and decompression.
929 func WriterBetterCompression() WriterOption {
930 return func(w *Writer) error {
931 w.level = levelBetter
932 return nil
933 }
934 }
935
936 // WriterBestCompression will enable better compression.
937 // EncodeBest compresses better than Encode but typically with a
938 // big speed decrease on compression.
939 func WriterBestCompression() WriterOption {
940 return func(w *Writer) error {
941 w.level = levelBest
942 return nil
943 }
944 }
945
946 // WriterUncompressed will bypass compression.
947 // The stream will be written as uncompressed blocks only.
948 // If concurrency is > 1 CRC and output will still be done async.
949 func WriterUncompressed() WriterOption {
950 return func(w *Writer) error {
951 w.level = levelUncompressed
952 return nil
953 }
954 }
955
956 // WriterBufferDone will perform a callback when EncodeBuffer has finished
957 // writing a buffer to the output and the buffer can safely be reused.
958 // If the buffer was split into several blocks, it will be sent after the last block.
959 // Callbacks will not be done concurrently.
960 func WriterBufferDone(fn func(b []byte)) WriterOption {
961 return func(w *Writer) error {
962 w.bufferCB = fn
963 return nil
964 }
965 }
966
967 // WriterBlockSize allows to override the default block size.
968 // Blocks will be this size or smaller.
969 // Minimum size is 4KB and maximum size is 4MB.
970 //
971 // Bigger blocks may give bigger throughput on systems with many cores,
972 // and will increase compression slightly, but it will limit the possible
973 // concurrency for smaller payloads for both encoding and decoding.
974 // Default block size is 1MB.
975 //
976 // When writing Snappy compatible output using WriterSnappyCompat,
977 // the maximum block size is 64KB.
978 func WriterBlockSize(n int) WriterOption {
979 return func(w *Writer) error {
980 if w.snappy && n > maxSnappyBlockSize || n < minBlockSize {
981 return errors.New("s2: block size too large. Must be <= 64K and >=4KB on for snappy compatible output")
982 }
983 if n > maxBlockSize || n < minBlockSize {
984 return errors.New("s2: block size too large. Must be <= 4MB and >=4KB")
985 }
986 w.blockSize = n
987 return nil
988 }
989 }
990
991 // WriterPadding will add padding to all output so the size will be a multiple of n.
992 // This can be used to obfuscate the exact output size or make blocks of a certain size.
993 // The contents will be a skippable frame, so it will be invisible by the decoder.
994 // n must be > 0 and <= 4MB.
995 // The padded area will be filled with data from crypto/rand.Reader.
996 // The padding will be applied whenever Close is called on the writer.
997 func WriterPadding(n int) WriterOption {
998 return func(w *Writer) error {
999 if n <= 0 {
1000 return fmt.Errorf("s2: padding must be at least 1")
1001 }
1002 // No need to waste our time.
1003 if n == 1 {
1004 w.pad = 0
1005 }
1006 if n > maxBlockSize {
1007 return fmt.Errorf("s2: padding must less than 4MB")
1008 }
1009 w.pad = n
1010 return nil
1011 }
1012 }
1013
1014 // WriterPaddingSrc will get random data for padding from the supplied source.
1015 // By default crypto/rand is used.
1016 func WriterPaddingSrc(reader io.Reader) WriterOption {
1017 return func(w *Writer) error {
1018 w.randSrc = reader
1019 return nil
1020 }
1021 }
1022
1023 // WriterSnappyCompat will write snappy compatible output.
1024 // The output can be decompressed using either snappy or s2.
1025 // If block size is more than 64KB it is set to that.
1026 func WriterSnappyCompat() WriterOption {
1027 return func(w *Writer) error {
1028 w.snappy = true
1029 if w.blockSize > 64<<10 {
1030 // We choose 8 bytes less than 64K, since that will make literal emits slightly more effective.
1031 // And allows us to skip some size checks.
1032 w.blockSize = (64 << 10) - 8
1033 }
1034 return nil
1035 }
1036 }
1037
1038 // WriterFlushOnWrite will compress blocks on each call to the Write function.
1039 //
1040 // This is quite inefficient as blocks size will depend on the write size.
1041 //
1042 // Use WriterConcurrency(1) to also make sure that output is flushed.
1043 // When Write calls return, otherwise they will be written when compression is done.
1044 func WriterFlushOnWrite() WriterOption {
1045 return func(w *Writer) error {
1046 w.flushOnWrite = true
1047 return nil
1048 }
1049 }
1050
1051 // WriterCustomEncoder allows to override the encoder for blocks on the stream.
1052 // The function must compress 'src' into 'dst' and return the bytes used in dst as an integer.
1053 // Block size (initial varint) should not be added by the encoder.
1054 // Returning value 0 indicates the block could not be compressed.
1055 // Returning a negative value indicates that compression should be attempted.
1056 // The function should expect to be called concurrently.
1057 func WriterCustomEncoder(fn func(dst, src []byte) int) WriterOption {
1058 return func(w *Writer) error {
1059 w.customEnc = fn
1060 return nil
1061 }
1062 }