Debian Codegraph @

dict.go

raw symbols ◀ ▶ SCIP
1 Debian patch touch this file
1 package gozstd
2
3 /*
4 #cgo CFLAGS: -O3
5
6 #define ZSTD_STATIC_LINKING_ONLY
•7 #include <zstd.h>
8
9 #define ZDICT_STATIC_LINKING_ONLY
•10 #include <zdict.h>
11
12 #include <stdint.h> // for uintptr_t
13
14 // The following *_wrapper functions allow avoiding memory allocations
15 // durting calls from Go.
16 // See https://github.com/golang/go/issues/24450 .
17
18 static ZSTD_CDict* ZSTD_createCDict_wrapper(uintptr_t dictBuffer, size_t dictSize, int compressionLevel) {
19 return ZSTD_createCDict((const void *)dictBuffer, dictSize, compressionLevel);
20 }
21
22 static ZSTD_DDict* ZSTD_createDDict_wrapper(uintptr_t dictBuffer, size_t dictSize) {
23 return ZSTD_createDDict((const void *)dictBuffer, dictSize);
24 }
25
26 */
27 import "C"
28
29 import (
30 "fmt"
31 "runtime"
32 "sync"
33 "unsafe"
34 )
35
36 const minDictLen = C.ZDICT_DICTSIZE_MIN
37
38 // BuildDict returns dictionary built from the given samples.
39 //
40 // The resulting dictionary size will be close to desiredDictLen.
41 //
42 // The returned dictionary may be passed to NewCDict* and NewDDict.
43 func BuildDict(samples [][]byte, desiredDictLen int) []byte {
44 if desiredDictLen < minDictLen {
45 desiredDictLen = minDictLen
46 }
47 dict := make([]byte, desiredDictLen)
48
49 // Calculate the total samples size.
50 samplesBufLen := 0
51 for _, sample := range samples {
52 if len(sample) == 0 {
53 // Skip empty samples.
54 continue
55 }
56 samplesBufLen += len(sample)
57 }
58
59 // Construct flat samplesBuf and samplesSizes.
60 samplesBuf := make([]byte, 0, samplesBufLen)
61 samplesSizes := make([]C.size_t, 0, len(samples))
62 for _, sample := range samples {
63 samplesBuf = append(samplesBuf, sample...)
64 samplesSizes = append(samplesSizes, C.size_t(len(sample)))
65 }
66
67 // Add fake samples if the original samples are too small.
68 minSamplesBufLen := int(C.ZDICT_CONTENTSIZE_MIN)
69 if minSamplesBufLen < minDictLen {
70 minSamplesBufLen = minDictLen
71 }
72 for samplesBufLen < minSamplesBufLen {
73 fakeSample := []byte(fmt.Sprintf("this is a fake sample %d", samplesBufLen))
74 samplesBuf = append(samplesBuf, fakeSample...)
75 samplesSizes = append(samplesSizes, C.size_t(len(fakeSample)))
76 samplesBufLen += len(fakeSample)
77 }
78
79 // Run ZDICT_trainFromBuffer under lock, since it looks like it
80 // is unsafe for concurrent usage (it just randomly crashes).
81 // TODO: remove this restriction.
82
83 buildDictLock.Lock()
84 result := C.ZDICT_trainFromBuffer(
85 unsafe.Pointer(&dict[0]),
86 C.size_t(len(dict)),
87 unsafe.Pointer(&samplesBuf[0]),
88 &samplesSizes[0],
89 C.unsigned(len(samplesSizes)))
90 buildDictLock.Unlock()
91 if C.ZDICT_isError(result) != 0 {
92 // Return empty dictionary, since the original samples are too small.
93 return nil
94 }
95
96 dictLen := int(result)
97 return dict[:dictLen]
98 }
99
100 var buildDictLock sync.Mutex
101
102 // CDict is a dictionary used for compression.
103 //
104 // A single CDict may be re-used in concurrently running goroutines.
105 type CDict struct {
106 p *C.ZSTD_CDict
107 compressionLevel int
108 }
109
110 // NewCDict creates new CDict from the given dict.
111 //
112 // Call Release when the returned dict is no longer used.
113 func NewCDict(dict []byte) (*CDict, error) {
114 return NewCDictLevel(dict, DefaultCompressionLevel)
115 }
116
117 // NewCDictLevel creates new CDict from the given dict
118 // using the given compressionLevel.
119 //
120 // Call Release when the returned dict is no longer used.
121 func NewCDictLevel(dict []byte, compressionLevel int) (*CDict, error) {
122 if len(dict) == 0 {
123 return nil, fmt.Errorf("dict cannot be empty")
124 }
125
126 cd := &CDict{
127 p: C.ZSTD_createCDict_wrapper(
128 C.uintptr_t(uintptr(unsafe.Pointer(&dict[0]))),
129 C.size_t(len(dict)),
130 C.int(compressionLevel)),
131 compressionLevel: compressionLevel,
132 }
133 // Prevent from GC'ing of dict during CGO call above.
134 runtime.KeepAlive(dict)
135 runtime.SetFinalizer(cd, freeCDict)
136 return cd, nil
137 }
138
139 // Release releases resources occupied by cd.
140 //
141 // cd cannot be used after the release.
142 func (cd *CDict) Release() {
143 if cd.p == nil {
144 return
145 }
146 result := C.ZSTD_freeCDict(cd.p)
147 ensureNoError("ZSTD_freeCDict", result)
148 cd.p = nil
149 }
150
151 func freeCDict(v interface{}) {
152 v.(*CDict).Release()
153 }
154
155 // DDict is a dictionary used for decompression.
156 //
157 // A single DDict may be re-used in concurrently running goroutines.
158 type DDict struct {
159 p *C.ZSTD_DDict
160 }
161
162 // NewDDict creates new DDict from the given dict.
163 //
164 // Call Release when the returned dict is no longer needed.
165 func NewDDict(dict []byte) (*DDict, error) {
166 if len(dict) == 0 {
167 return nil, fmt.Errorf("dict cannot be empty")
168 }
169
170 dd := &DDict{
171 p: C.ZSTD_createDDict_wrapper(
172 C.uintptr_t(uintptr(unsafe.Pointer(&dict[0]))),
173 C.size_t(len(dict))),
174 }
175 // Prevent from GC'ing of dict during CGO call above.
176 runtime.KeepAlive(dict)
177 runtime.SetFinalizer(dd, freeDDict)
178 return dd, nil
179 }
180
181 // Release releases resources occupied by dd.
182 //
183 // dd cannot be used after the release.
184 func (dd *DDict) Release() {
185 if dd.p == nil {
186 return
187 }
188
189 result := C.ZSTD_freeDDict(dd.p)
190 ensureNoError("ZSTD_freeDDict", result)
191 dd.p = nil
192 }
193
194 func freeDDict(v interface{}) {
195 v.(*DDict).Release()
196 }