...

Source file src/github.com/klauspost/compress/zstd/example_test.go

Documentation: github.com/klauspost/compress/zstd

     1  package zstd_test
     2  
     3  import (
     4  	"bytes"
     5  	"fmt"
     6  
     7  	"github.com/klauspost/compress/zstd"
     8  )
     9  
    10  func ExampleWithEncoderDictRaw() {
    11  	// "Raw" dictionaries can be used for compressed delta encoding.
    12  
    13  	source := []byte(`
    14  		This is the source file. Compression of the target file with
    15  		the source file as the dictionary will produce a compressed
    16  		delta encoding of the target file.`)
    17  	target := []byte(`
    18  		This is the target file. Decompression of the delta encoding with
    19  		the source file as the dictionary will produce this file.`)
    20  
    21  	// The dictionary id is arbitrary. We use zero for compatibility
    22  	// with zstd --patch-from, but applications can use any id
    23  	// not in the range [32768, 1<<31).
    24  	const id = 0
    25  
    26  	bestLevel := zstd.WithEncoderLevel(zstd.SpeedBestCompression)
    27  
    28  	w, _ := zstd.NewWriter(nil, bestLevel,
    29  		zstd.WithEncoderDictRaw(id, source))
    30  	delta := w.EncodeAll(target, nil)
    31  
    32  	r, _ := zstd.NewReader(nil, zstd.WithDecoderDictRaw(id, source))
    33  	out, err := r.DecodeAll(delta, nil)
    34  	if err != nil || !bytes.Equal(out, target) {
    35  		panic("decoding error")
    36  	}
    37  
    38  	// Ordinary compression, for reference.
    39  	w, _ = zstd.NewWriter(nil, bestLevel)
    40  	compressed := w.EncodeAll(target, nil)
    41  
    42  	// Check that the delta is at most half as big as the compressed file.
    43  	fmt.Println(len(delta) < len(compressed)/2)
    44  	// Output:
    45  	// true
    46  }
    47  

View as plain text