Debian Codegraph @

dict/cmd/builddict/main.go

raw
1 // Copyright 2023+ Klaus Post. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
4
5 package main
6
7 import (
8 "flag"
9 "fmt"
10 "io"
11 "log"
12 "os"
13 "path/filepath"
14 "runtime/debug"
15
16 "github.com/klauspost/compress/dict"
17 "github.com/klauspost/compress/zstd"
18 )
19
20 var (
21 wantLenFlag = flag.Int("len", 112<<10, "Specify custom output size")
22 wantHashBytes = flag.Int("hash", 6, "Hash bytes match length. Minimum match length.")
23 wantMaxBytes = flag.Int("max", 32<<10, "Max input length to index per input file")
24 wantOutput = flag.String("o", "dictionary.bin", "Output name")
25 wantFormat = flag.String("format", "zstd", `Output type. "zstd" "s2" or "raw"`)
26 wantZstdID = flag.Uint("dictID", 0, "Zstd dictionary ID. Default (0) will be random")
27 wantZstdCompat = flag.Bool("zcompat", true, "Generate dictionary compatible with zstd 1.5.5 and older")
28 wantZstdLevel = flag.Int("zlevel", 0, "Zstd compression level. 0-4")
29 quiet = flag.Bool("q", false, "Do not print progress")
30 )
31
32 func main() {
33 flag.Parse()
34 debug.SetGCPercent(25)
35 o := dict.Options{
36 MaxDictSize: *wantLenFlag,
37 HashBytes: *wantHashBytes,
38 Output: os.Stdout,
39 ZstdDictID: uint32(*wantZstdID),
40 ZstdDictCompat: *wantZstdCompat,
41 ZstdLevel: zstd.EncoderLevel(*wantZstdLevel),
42 }
43 if *wantOutput == "" || *quiet {
44 o.Output = nil
45 }
46 var input [][]byte
47 base := flag.Arg(0)
48 if base == "" {
49 flag.Usage()
50 log.Fatal("no path with files specified")
51 }
52
53 // Index ALL hashes in all files.
54 err := filepath.Walk(base, func(path string, info os.FileInfo, err error) error {
55 if err != nil {
56 return err
57 }
58 if info.IsDir() {
59 return nil
60 }
61
62 f, err := os.Open(path)
63 if err != nil {
64 log.Print(err)
65 return nil
66 }
67 defer f.Close()
68 b, err := io.ReadAll(io.LimitReader(f, int64(*wantMaxBytes)))
69 if len(b) < 8 {
70 return nil
71 }
72 if len(b) == 0 {
73 return nil
74 }
75 input = append(input, b)
76 if !*quiet {
77 fmt.Print("\r"+info.Name(), " read...")
78 }
79 return nil
80 })
81 if err != nil {
82 log.Fatal(err)
83 }
84 if len(input) == 0 {
85 log.Fatal("no files read")
86 }
87 var out []byte
88 switch *wantFormat {
89 case "zstd":
90 out, err = dict.BuildZstdDict(input, o)
91 case "s2":
92 out, err = dict.BuildS2Dict(input, o)
93 case "raw":
94 out, err = dict.BuildRawDict(input, o)
95 default:
96 err = fmt.Errorf("unknown format %q", *wantFormat)
97 }
98 if err != nil {
99 log.Fatal(err)
100 }
101 if *wantOutput != "" {
102 err = os.WriteFile(*wantOutput, out, 0666)
103 if err != nil {
104 log.Fatal(err)
105 }
106 } else {
107 _, err = os.Stdout.Write(out)
108 if err != nil {
109 log.Fatal(err)
110 }
111 }
112 }