...
1 package zstd_test
2
3 import (
4 "archive/zip"
5 "bytes"
6 "fmt"
7 "io"
8
9 "github.com/klauspost/compress/zstd"
10 )
11
12 func ExampleZipCompressor() {
13
14
15 compr := zstd.ZipCompressor(zstd.WithWindowSize(1<<20), zstd.WithEncoderCRC(false))
16 decomp := zstd.ZipDecompressor()
17
18
19 var buf bytes.Buffer
20 zw := zip.NewWriter(&buf)
21 zw.RegisterCompressor(zstd.ZipMethodWinZip, compr)
22 zw.RegisterCompressor(zstd.ZipMethodPKWare, compr)
23
24
25 tmp := make([]byte, 1<<20)
26 for i := range tmp {
27 tmp[i] = byte(i)
28 }
29 w, err := zw.CreateHeader(&zip.FileHeader{
30 Name: "file1.txt",
31 Method: zstd.ZipMethodWinZip,
32 })
33 if err != nil {
34 panic(err)
35 }
36 w.Write(tmp)
37
38
39 w, err = zw.CreateHeader(&zip.FileHeader{
40 Name: "file2.txt",
41 Method: zstd.ZipMethodPKWare,
42 })
43 w.Write(tmp)
44 zw.Close()
45
46 zr, err := zip.NewReader(bytes.NewReader(buf.Bytes()), int64(buf.Len()))
47 if err != nil {
48 panic(err)
49 }
50 zr.RegisterDecompressor(zstd.ZipMethodWinZip, decomp)
51 zr.RegisterDecompressor(zstd.ZipMethodPKWare, decomp)
52 for _, file := range zr.File {
53 rc, err := file.Open()
54 if err != nil {
55 panic(err)
56 }
57 b, err := io.ReadAll(rc)
58 rc.Close()
59 if bytes.Equal(b, tmp) {
60 fmt.Println(file.Name, "ok")
61 } else {
62 fmt.Println(file.Name, "mismatch")
63 }
64 }
65
66
67
68 }
69
View as plain text