File: example_test.go

package info (click to toggle)
golang-github-klauspost-compress 1.17.2%2Bds1-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 46,376 kB
  • sloc: asm: 23,058; sh: 73; makefile: 11
file content (46 lines) | stat: -rw-r--r-- 1,320 bytes parent folder | download | duplicates (4)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
package zstd_test

import (
	"bytes"
	"fmt"

	"github.com/klauspost/compress/zstd"
)

func ExampleWithEncoderDictRaw() {
	// "Raw" dictionaries can be used for compressed delta encoding.

	source := []byte(`
		This is the source file. Compression of the target file with
		the source file as the dictionary will produce a compressed
		delta encoding of the target file.`)
	target := []byte(`
		This is the target file. Decompression of the delta encoding with
		the source file as the dictionary will produce this file.`)

	// The dictionary id is arbitrary. We use zero for compatibility
	// with zstd --patch-from, but applications can use any id
	// not in the range [32768, 1<<31).
	const id = 0

	bestLevel := zstd.WithEncoderLevel(zstd.SpeedBestCompression)

	w, _ := zstd.NewWriter(nil, bestLevel,
		zstd.WithEncoderDictRaw(id, source))
	delta := w.EncodeAll(target, nil)

	r, _ := zstd.NewReader(nil, zstd.WithDecoderDictRaw(id, source))
	out, err := r.DecodeAll(delta, nil)
	if err != nil || !bytes.Equal(out, target) {
		panic("decoding error")
	}

	// Ordinary compression, for reference.
	w, _ = zstd.NewWriter(nil, bestLevel)
	compressed := w.EncodeAll(target, nil)

	// Check that the delta is at most half as big as the compressed file.
	fmt.Println(len(delta) < len(compressed)/2)
	// Output:
	// true
}