| 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 |
// Get zstandard de/compressors for zip. |
| 14 |
// These can be used by multiple readers and writers. |
| 15 |
compr := zstd.ZipCompressor(zstd.WithWindowSize(1<<20), zstd.WithEncoderCRC(false)) |
| 16 |
decomp := zstd.ZipDecompressor() |
| 17 |
|
| 18 |
// Try it out... |
| 19 |
var buf bytes.Buffer |
| 20 |
zw := zip.NewWriter(&buf) |
| 21 |
zw.RegisterCompressor(zstd.ZipMethodWinZip, compr) |
| 22 |
zw.RegisterCompressor(zstd.ZipMethodPKWare, compr) |
| 23 |
|
| 24 |
// Create 1MB data |
| 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 |
// Another... |
| 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 |
// Output: |
| 66 |
// file1.txt ok |
| 67 |
// file2.txt ok |
| 68 |
} |