/src/duckdb/third_party/fsst/libfsst.cpp
Line | Count | Source |
1 | | // this software is distributed under the MIT License (http://www.opensource.org/licenses/MIT): |
2 | | // |
3 | | // Copyright 2018-2020, CWI, TU Munich, FSU Jena |
4 | | // |
5 | | // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files |
6 | | // (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, |
7 | | // merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is |
8 | | // furnished to do so, subject to the following conditions: |
9 | | // |
10 | | // - The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. |
11 | | // |
12 | | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES |
13 | | // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE |
14 | | // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR |
15 | | // IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. |
16 | | // |
17 | | // You can contact the authors via the FSST source repository : https://github.com/cwida/fsst |
18 | | #include "libfsst.hpp" |
19 | | #include "duckdb/common/unique_ptr.hpp" |
20 | | |
21 | | namespace libfsst { |
22 | 0 | Symbol concat(Symbol a, Symbol b) { |
23 | 0 | Symbol s; |
24 | 0 | u32 length = a.length()+b.length(); |
25 | 0 | if (length > Symbol::maxLength) length = Symbol::maxLength; |
26 | 0 | s.set_code_len(FSST_CODE_MASK, length); |
27 | 0 | s.store_num((b.load_num() << (8*a.length())) | a.load_num()); |
28 | 0 | return s; |
29 | 0 | } |
30 | | } // namespace libfsst |
31 | | |
32 | | namespace std { |
33 | | template <> |
34 | | class hash<libfsst::QSymbol> { |
35 | | public: |
36 | 0 | size_t operator()(const libfsst::QSymbol& q) const { |
37 | 0 | uint64_t k = q.symbol.load_num(); |
38 | 0 | const uint64_t m = 0xc6a4a7935bd1e995; |
39 | 0 | const int r = 47; |
40 | 0 | uint64_t h = 0x8445d61a4e774912 ^ (8*m); |
41 | 0 | k *= m; |
42 | 0 | k ^= k >> r; |
43 | 0 | k *= m; |
44 | 0 | h ^= k; |
45 | 0 | h *= m; |
46 | 0 | h ^= h >> r; |
47 | 0 | h *= m; |
48 | 0 | h ^= h >> r; |
49 | 0 | return h; |
50 | 0 | } |
51 | | }; |
52 | | } |
53 | | |
54 | | namespace libfsst { |
55 | 0 | bool isEscapeCode(u16 pos) { return pos < FSST_CODE_BASE; } |
56 | | |
57 | 0 | std::ostream& operator<<(std::ostream& out, const Symbol& s) { |
58 | 0 | for (u32 i=0; i<s.length(); i++) |
59 | 0 | out << s.val.str[i]; |
60 | 0 | return out; |
61 | 0 | } |
62 | | |
63 | 0 | SymbolTable *buildSymbolTable(Counters& counters, std::vector<const u8*> line, const size_t len[], bool zeroTerminated=false) { |
64 | 0 | SymbolTable *st = new SymbolTable(), *bestTable = new SymbolTable(); |
65 | 0 | int bestGain = (int) -FSST_SAMPLEMAXSZ; // worst case (everything exception) |
66 | 0 | size_t sampleFrac = 128; |
67 | | |
68 | | // start by determining the terminator. We use the (lowest) most infrequent byte as terminator |
69 | 0 | st->zeroTerminated = zeroTerminated; |
70 | 0 | if (zeroTerminated) { |
71 | 0 | st->terminator = 0; // except in case of zeroTerminated mode, then byte 0 is terminator regardless frequency |
72 | 0 | } else { |
73 | 0 | u16 byteHisto[256]; |
74 | 0 | memset(byteHisto, 0, sizeof(byteHisto)); |
75 | 0 | for(size_t i=0; i<line.size(); i++) { |
76 | 0 | const u8* cur = line[i]; |
77 | 0 | const u8* end = cur + len[i]; |
78 | 0 | while(cur < end) byteHisto[*cur++]++; |
79 | 0 | } |
80 | 0 | u32 minSize = FSST_SAMPLEMAXSZ, i = st->terminator = 256; |
81 | 0 | while(i-- > 0) { |
82 | 0 | if (byteHisto[i] > minSize) continue; |
83 | 0 | st->terminator = i; |
84 | 0 | minSize = byteHisto[i]; |
85 | 0 | } |
86 | 0 | } |
87 | 0 | assert(st->terminator != 256); |
88 | | |
89 | | // a random number between 0 and 128 |
90 | 0 | auto rnd128 = [&](size_t i) { return 1 + (FSST_HASH((i+1UL)*sampleFrac)&127); }; |
91 | | |
92 | | // compress sample, and compute (pair-)frequencies |
93 | 0 | auto compressCount = [&](SymbolTable *st, Counters &counters) { // returns gain |
94 | 0 | int gain = 0; |
95 | |
|
96 | 0 | for(size_t i=0; i<line.size(); i++) { |
97 | 0 | const u8* cur = line[i], *start = cur; |
98 | 0 | const u8* end = cur + len[i]; |
99 | |
|
100 | 0 | if (sampleFrac < 128) { |
101 | | // in earlier rounds (sampleFrac < 128) we skip data in the sample (reduces overall work ~2x) |
102 | 0 | if (rnd128(i) > sampleFrac) continue; |
103 | 0 | } |
104 | 0 | if (cur < end) { |
105 | 0 | u16 code2 = 255, code1 = st->findLongestSymbol(cur, end); |
106 | 0 | cur += st->symbols[code1].length(); |
107 | 0 | gain += (int) (st->symbols[code1].length()-(1+isEscapeCode(code1))); |
108 | 0 | while (true) { |
109 | | // count single symbol (i.e. an option is not extending it) |
110 | 0 | counters.count1Inc(code1); |
111 | | |
112 | | // as an alternative, consider just using the next byte.. |
113 | 0 | if (st->symbols[code1].length() != 1) // .. but do not count single byte symbols doubly |
114 | 0 | counters.count1Inc(*start); |
115 | |
|
116 | 0 | if (cur==end) { |
117 | 0 | break; |
118 | 0 | } |
119 | | |
120 | | // now match a new symbol |
121 | 0 | start = cur; |
122 | 0 | if (cur<end-7) { |
123 | 0 | u64 word = fsst_unaligned_load(cur); |
124 | 0 | size_t code = word & 0xFFFFFF; |
125 | 0 | size_t idx = FSST_HASH(code)&(st->hashTabSize-1); |
126 | 0 | Symbol s = st->hashTab[idx]; |
127 | 0 | code2 = st->shortCodes[word & 0xFFFF] & FSST_CODE_MASK; |
128 | 0 | word &= (0xFFFFFFFFFFFFFFFF >> (u8) s.icl); |
129 | 0 | if ((s.icl < FSST_ICL_FREE) & (s.load_num() == word)) { |
130 | 0 | code2 = s.code(); |
131 | 0 | cur += s.length(); |
132 | 0 | } else if (code2 >= FSST_CODE_BASE) { |
133 | 0 | cur += 2; |
134 | 0 | } else { |
135 | 0 | code2 = st->byteCodes[word & 0xFF] & FSST_CODE_MASK; |
136 | 0 | cur += 1; |
137 | 0 | } |
138 | 0 | } else { |
139 | 0 | code2 = st->findLongestSymbol(cur, end); |
140 | 0 | cur += st->symbols[code2].length(); |
141 | 0 | } |
142 | | |
143 | | // compute compressed output size |
144 | 0 | gain += ((int) (cur-start))-(1+isEscapeCode(code2)); |
145 | | |
146 | | // now count the subsequent two symbols we encode as an extension codesibility |
147 | 0 | if (sampleFrac < 128) { // no need to count pairs in final round |
148 | | // consider the symbol that is the concatenation of the two last symbols |
149 | 0 | counters.count2Inc(code1, code2); |
150 | | |
151 | | // as an alternative, consider just extending with the next byte.. |
152 | 0 | if ((cur-start) > 1) // ..but do not count single byte extensions doubly |
153 | 0 | counters.count2Inc(code1, *start); |
154 | 0 | } |
155 | 0 | code1 = code2; |
156 | 0 | } |
157 | 0 | } |
158 | 0 | } |
159 | 0 | return gain; |
160 | 0 | }; |
161 | |
|
162 | 0 | auto makeTable = [&](SymbolTable *st, Counters &counters) { |
163 | | // hashmap of c (needed because we can generate duplicate candidates) |
164 | 0 | std::unordered_set<QSymbol> cands; |
165 | | |
166 | | // artificially make terminater the most frequent symbol so it gets included |
167 | 0 | u16 terminator = st->nSymbols?FSST_CODE_BASE:st->terminator; |
168 | 0 | counters.count1Set(terminator,65535); |
169 | |
|
170 | 0 | auto addOrInc = [&](std::unordered_set<QSymbol> &cands, Symbol s, u64 count) { |
171 | 0 | if (count < (5*sampleFrac)/128) return; // improves both compression speed (less candidates), but also quality!! |
172 | 0 | QSymbol q; |
173 | 0 | q.symbol = s; |
174 | 0 | q.gain = count * s.length(); |
175 | 0 | auto it = cands.find(q); |
176 | 0 | if (it != cands.end()) { |
177 | 0 | q.gain += (*it).gain; |
178 | 0 | cands.erase(*it); |
179 | 0 | } |
180 | 0 | cands.insert(q); |
181 | 0 | }; |
182 | | |
183 | | // add candidate symbols based on counted frequency |
184 | 0 | for (u32 pos1=0; pos1<FSST_CODE_BASE+(size_t) st->nSymbols; pos1++) { |
185 | 0 | u32 cnt1 = counters.count1GetNext(pos1); // may advance pos1!! |
186 | 0 | if (!cnt1) continue; |
187 | | |
188 | | // heuristic: promoting single-byte symbols (*8) helps reduce exception rates and increases [de]compression speed |
189 | 0 | Symbol s1 = st->symbols[pos1]; |
190 | 0 | addOrInc(cands, s1, ((s1.length()==1)?8LL:1LL)*cnt1); |
191 | |
|
192 | 0 | if (sampleFrac >= 128 || // last round we do not create new (combined) symbols |
193 | 0 | s1.length() == Symbol::maxLength || // symbol cannot be extended |
194 | 0 | s1.val.str[0] == st->terminator) { // multi-byte symbols cannot contain the terminator byte |
195 | 0 | continue; |
196 | 0 | } |
197 | | |
198 | 0 | for (u32 pos2=0; pos2<FSST_CODE_BASE+(size_t)st->nSymbols; pos2++) { |
199 | 0 | u32 cnt2 = counters.count2GetNext(pos1, pos2); // may advance pos2!! |
200 | 0 | if (!cnt2) continue; |
201 | | |
202 | | // create a new symbol |
203 | 0 | Symbol s2 = st->symbols[pos2]; |
204 | 0 | Symbol s3 = concat(s1, s2); |
205 | 0 | if (s2.val.str[0] != st->terminator) // multi-byte symbols cannot contain the terminator byte |
206 | 0 | addOrInc(cands, s3, cnt2); |
207 | 0 | } |
208 | 0 | } |
209 | | |
210 | | // insert candidates into priority queue (by gain) |
211 | 0 | auto cmpGn = [](const QSymbol& q1, const QSymbol& q2) { return (q1.gain < q2.gain) || (q1.gain == q2.gain && q1.symbol.load_num() > q2.symbol.load_num()); }; |
212 | 0 | std::priority_queue<QSymbol,std::vector<QSymbol>,decltype(cmpGn)> pq(cmpGn); |
213 | 0 | for (auto& q : cands) |
214 | 0 | pq.push(q); |
215 | | |
216 | | // Create new symbol map using best candidates |
217 | 0 | st->clear(); |
218 | 0 | while (st->nSymbols < 255 && !pq.empty()) { |
219 | 0 | QSymbol q = pq.top(); |
220 | 0 | pq.pop(); |
221 | 0 | st->add(q.symbol); |
222 | 0 | } |
223 | 0 | }; |
224 | |
|
225 | 0 | u8 bestCounters[512*sizeof(u16)]; |
226 | | #ifdef NONOPT_FSST |
227 | | for(size_t frac : {127, 127, 127, 127, 127, 127, 127, 127, 127, 128}) { |
228 | | sampleFrac = frac; |
229 | | #else |
230 | 0 | for(sampleFrac=8; true; sampleFrac += 30) { |
231 | 0 | #endif |
232 | 0 | memset(&counters, 0, sizeof(Counters)); |
233 | 0 | long gain = compressCount(st, counters); |
234 | 0 | if (gain >= bestGain) { // a new best solution! |
235 | 0 | counters.backup1(bestCounters); |
236 | 0 | *bestTable = *st; bestGain = gain; |
237 | 0 | } |
238 | 0 | if (sampleFrac >= 128) break; // we do 5 rounds (sampleFrac=8,38,68,98,128) |
239 | 0 | makeTable(st, counters); |
240 | 0 | } |
241 | 0 | delete st; |
242 | 0 | counters.restore1(bestCounters); |
243 | 0 | makeTable(bestTable, counters); |
244 | 0 | bestTable->finalize(zeroTerminated); // renumber codes for more efficient compression |
245 | 0 | return bestTable; |
246 | 0 | } |
247 | | |
248 | | // optimized adaptive *scalar* compression method |
249 | 0 | static inline size_t compressBulk(SymbolTable &symbolTable, size_t nlines, size_t lenIn[], u8* strIn[], size_t size, u8* out, size_t lenOut[], u8* strOut[], bool noSuffixOpt, bool avoidBranch) { |
250 | 0 | const u8 *cur = NULL, *end = NULL, *lim = out + size; |
251 | 0 | size_t curLine, suffixLim = symbolTable.suffixLim; |
252 | 0 | u8 byteLim = symbolTable.nSymbols + symbolTable.zeroTerminated - symbolTable.lenHisto[0]; |
253 | |
|
254 | 0 | u8 buf[512+8] = {}; /* +8 sentinel is to avoid 8-byte unaligned-loads going beyond 511 out-of-bounds */ |
255 | | |
256 | | // three variants are possible. dead code falls away since the bool arguments are constants |
257 | 0 | auto compressVariant = [&](bool noSuffixOpt, bool avoidBranch) { |
258 | 0 | while (cur < end) { |
259 | 0 | u64 word = fsst_unaligned_load(cur); |
260 | 0 | size_t code = symbolTable.shortCodes[word & 0xFFFF]; |
261 | 0 | if (noSuffixOpt && ((u8) code) < suffixLim) { |
262 | | // 2 byte code without having to worry about longer matches |
263 | 0 | *out++ = (u8) code; cur += 2; |
264 | 0 | } else { |
265 | 0 | size_t pos = word & 0xFFFFFF; |
266 | 0 | size_t idx = FSST_HASH(pos)&(symbolTable.hashTabSize-1); |
267 | 0 | Symbol s = symbolTable.hashTab[idx]; |
268 | 0 | out[1] = (u8) word; // speculatively write out escaped byte |
269 | 0 | word &= (0xFFFFFFFFFFFFFFFF >> (u8) s.icl); |
270 | 0 | if ((s.icl < FSST_ICL_FREE) && s.load_num() == word) { |
271 | 0 | *out++ = (u8) s.code(); cur += s.length(); |
272 | 0 | } else if (avoidBranch) { |
273 | | // could be a 2-byte or 1-byte code, or miss |
274 | | // handle everything with predication |
275 | 0 | *out = (u8) code; |
276 | 0 | out += 1+((code&FSST_CODE_BASE)>>8); |
277 | 0 | cur += (code>>FSST_LEN_BITS); |
278 | 0 | } else if ((u8) code < byteLim) { |
279 | | // 2 byte code after checking there is no longer pattern |
280 | 0 | *out++ = (u8) code; cur += 2; |
281 | 0 | } else { |
282 | | // 1 byte code or miss. |
283 | 0 | *out = (u8) code; |
284 | 0 | out += 1+((code&FSST_CODE_BASE)>>8); // predicated - tested with a branch, that was always worse |
285 | 0 | cur++; |
286 | 0 | } |
287 | 0 | } |
288 | 0 | } |
289 | 0 | }; |
290 | |
|
291 | 0 | for(curLine=0; curLine<nlines; curLine++) { |
292 | 0 | size_t chunk, curOff = 0; |
293 | 0 | strOut[curLine] = out; |
294 | 0 | do { |
295 | 0 | cur = strIn[curLine] + curOff; |
296 | 0 | chunk = lenIn[curLine] - curOff; |
297 | 0 | if (chunk > 511) { |
298 | 0 | chunk = 511; // we need to compress in chunks of 511 in order to be byte-compatible with simd-compressed FSST |
299 | 0 | } |
300 | 0 | if ((2*chunk+7) > (size_t) (lim-out)) { |
301 | 0 | return curLine; // out of memory |
302 | 0 | } |
303 | | // copy the string to the 511-byte buffer |
304 | 0 | memcpy(buf, cur, chunk); |
305 | 0 | buf[chunk] = (u8) symbolTable.terminator; |
306 | 0 | cur = buf; |
307 | 0 | end = cur + chunk; |
308 | | |
309 | | // based on symboltable stats, choose a variant that is nice to the branch predictor |
310 | 0 | if (noSuffixOpt) { |
311 | 0 | compressVariant(true,false); |
312 | 0 | } else if (avoidBranch) { |
313 | 0 | compressVariant(false,true); |
314 | 0 | } else { |
315 | 0 | compressVariant(false, false); |
316 | 0 | } |
317 | 0 | } while((curOff += chunk) < lenIn[curLine]); |
318 | 0 | lenOut[curLine] = (size_t) (out - strOut[curLine]); |
319 | 0 | } |
320 | 0 | return curLine; |
321 | 0 | } |
322 | | |
323 | 0 | #define FSST_SAMPLELINE ((size_t) 512) |
324 | | |
325 | | // quickly select a uniformly random set of lines such that we have between [FSST_SAMPLETARGET,FSST_SAMPLEMAXSZ) string bytes |
326 | | std::vector<const u8*> makeSample(u8* sampleBuf, u8* strIn[], size_t *lenIn, size_t nlines, |
327 | 0 | duckdb::unique_ptr<std::vector<size_t>>& sample_len_out) { |
328 | 0 | size_t totSize = 0; |
329 | 0 | std::vector<const u8*> sample; |
330 | |
|
331 | 0 | for(size_t i=0; i<nlines; i++) |
332 | 0 | totSize += lenIn[i]; |
333 | |
|
334 | 0 | if (totSize < FSST_SAMPLETARGET) { |
335 | 0 | for(size_t i=0; i<nlines; i++) |
336 | 0 | sample.push_back(strIn[i]); |
337 | 0 | } else { |
338 | 0 | size_t sampleRnd = FSST_HASH(4637947); |
339 | 0 | const u8* sampleLim = sampleBuf + FSST_SAMPLETARGET; |
340 | |
|
341 | 0 | sample_len_out = duckdb::unique_ptr<std::vector<size_t>>(new std::vector<size_t>()); |
342 | 0 | sample_len_out->reserve(nlines + FSST_SAMPLEMAXSZ/FSST_SAMPLELINE); |
343 | | |
344 | | // This fails if we have a lot of small strings and a few big ones? |
345 | 0 | while(sampleBuf < sampleLim) { |
346 | | // choose a non-empty line |
347 | 0 | sampleRnd = FSST_HASH(sampleRnd); |
348 | 0 | size_t linenr = sampleRnd % nlines; |
349 | 0 | while (lenIn[linenr] == 0) |
350 | 0 | if (++linenr == nlines) linenr = 0; |
351 | | |
352 | | // choose a chunk |
353 | 0 | size_t chunks = 1 + ((lenIn[linenr]-1) / FSST_SAMPLELINE); |
354 | 0 | sampleRnd = FSST_HASH(sampleRnd); |
355 | 0 | size_t chunk = FSST_SAMPLELINE*(sampleRnd % chunks); |
356 | | |
357 | | // add the chunk to the sample |
358 | 0 | size_t len = std::min(lenIn[linenr]-chunk,FSST_SAMPLELINE); |
359 | 0 | memcpy(sampleBuf, strIn[linenr]+chunk, len); |
360 | 0 | sample.push_back(sampleBuf); |
361 | |
|
362 | 0 | sample_len_out->push_back(len); |
363 | 0 | sampleBuf += len; |
364 | 0 | } |
365 | 0 | } |
366 | 0 | return sample; |
367 | 0 | } |
368 | | |
369 | 0 | extern "C" duckdb_fsst_encoder_t* duckdb_fsst_create(size_t n, size_t lenIn[], u8 *strIn[], int zeroTerminated) { |
370 | 0 | u8* sampleBuf = new u8[FSST_SAMPLEMAXSZ]; |
371 | 0 | duckdb::unique_ptr<std::vector<size_t>> sample_sizes; |
372 | 0 | std::vector<const u8*> sample = makeSample(sampleBuf, strIn, lenIn, n?n:1, sample_sizes); // careful handling of input to get a right-size and representative sample |
373 | 0 | Encoder *encoder = new Encoder(); |
374 | 0 | const size_t* sampleLen = sample_sizes ? sample_sizes->data() : &lenIn[0]; |
375 | 0 | encoder->symbolTable = std::shared_ptr<SymbolTable>(buildSymbolTable(encoder->counters, sample, sampleLen, zeroTerminated)); |
376 | 0 | delete[] sampleBuf; |
377 | 0 | return (duckdb_fsst_encoder_t*) encoder; |
378 | 0 | } |
379 | | |
380 | | /* create another encoder instance, necessary to do multi-threaded encoding using the same symbol table */ |
381 | 0 | extern "C" duckdb_fsst_encoder_t* duckdb_fsst_duplicate(duckdb_fsst_encoder_t *encoder) { |
382 | 0 | Encoder *e = new Encoder(); |
383 | 0 | e->symbolTable = ((Encoder*)encoder)->symbolTable; // it is a shared_ptr |
384 | 0 | return (duckdb_fsst_encoder_t*) e; |
385 | 0 | } |
386 | | |
387 | | // export a symbol table in compact format. |
388 | 0 | extern "C" u32 duckdb_fsst_export(duckdb_fsst_encoder_t *encoder, u8 *buf) { |
389 | 0 | Encoder *e = (Encoder*) encoder; |
390 | | // In ->version there is a versionnr, but we hide also suffixLim/terminator/nSymbols there. |
391 | | // This is sufficient in principle to *reconstruct* a duckdb_fsst_encoder_t from a duckdb_fsst_decoder_t |
392 | | // (such functionality could be useful to append compressed data to an existing block). |
393 | | // |
394 | | // However, the hash function in the encoder hash table is endian-sensitive, and given its |
395 | | // 'lossy perfect' hashing scheme is *unable* to contain other-endian-produced symbol tables. |
396 | | // Doing a endian-conversion during hashing will be slow and self-defeating. |
397 | | // |
398 | | // Overall, we could support reconstructing an encoder for incremental compression, but |
399 | | // should enforce equal-endianness. Bit of a bummer. Not going there now. |
400 | | // |
401 | | // The version field is now there just for future-proofness, but not used yet |
402 | | |
403 | | // version allows keeping track of fsst versions, track endianness, and encoder reconstruction |
404 | 0 | u64 version = (FSST_VERSION << 32) | // version is 24 bits, most significant byte is 0 |
405 | 0 | (((u64) e->symbolTable->suffixLim) << 24) | |
406 | 0 | (((u64) e->symbolTable->terminator) << 16) | |
407 | 0 | (((u64) e->symbolTable->nSymbols) << 8) | |
408 | 0 | FSST_ENDIAN_MARKER; // least significant byte is nonzero |
409 | |
|
410 | 0 | version = swap64_if_be(version); // ensure version is little-endian encoded |
411 | | |
412 | | /* do not assume unaligned reads here */ |
413 | 0 | memcpy(buf, &version, 8); |
414 | 0 | buf[8] = e->symbolTable->zeroTerminated; |
415 | 0 | for(u32 i=0; i<8; i++) |
416 | 0 | buf[9+i] = (u8) e->symbolTable->lenHisto[i]; |
417 | 0 | u32 pos = 17; |
418 | | |
419 | | // emit only the used bytes of the symbols |
420 | 0 | for(u32 i = e->symbolTable->zeroTerminated; i < e->symbolTable->nSymbols; i++) |
421 | 0 | for(u32 j = 0; j < e->symbolTable->symbols[i].length(); j++) |
422 | 0 | buf[pos++] = e->symbolTable->symbols[i].val.str[j]; // serialize used symbol bytes |
423 | |
|
424 | 0 | return pos; // length of what was serialized |
425 | 0 | } |
426 | | |
427 | 0 | #define FSST_CORRUPT 32774747032022883 /* 7-byte number in little endian containing "corrupt" */ |
428 | | |
429 | 0 | extern "C" u32 duckdb_fsst_import(duckdb_fsst_decoder_t *decoder, u8 *buf) { |
430 | 0 | u64 version = 0; |
431 | 0 | u32 code, pos = 17; |
432 | 0 | u8 lenHisto[8]; |
433 | | |
434 | | // version field (first 8 bytes) is now there just for future-proofness, unused still (skipped) |
435 | 0 | memcpy(&version, buf, 8); |
436 | 0 | version = swap64_if_be(version); // version is always little-endian encoded |
437 | |
|
438 | 0 | if ((version>>32) != FSST_VERSION) return 0; |
439 | 0 | decoder->zeroTerminated = buf[8]&1; |
440 | 0 | memcpy(lenHisto, buf+9, 8); |
441 | | |
442 | | // in case of zero-terminated, first symbol is "" (zero always, may be overwritten) |
443 | 0 | decoder->len[0] = 1; |
444 | 0 | decoder->symbol[0] = 0; |
445 | | |
446 | | // we use lenHisto[0] as 1-byte symbol run length (at the end) |
447 | 0 | code = decoder->zeroTerminated; |
448 | 0 | if (decoder->zeroTerminated) lenHisto[0]--; // if zeroTerminated, then symbol "" aka 1-byte code=0, is not stored at the end |
449 | | |
450 | | // now get all symbols from the buffer |
451 | 0 | for(u32 l=1; l<=8; l++) { /* l = 1,2,3,4,5,6,7,8 */ |
452 | 0 | for(u32 i=0; i < lenHisto[(l&7) /* 1,2,3,4,5,6,7,0 */]; i++, code++) { |
453 | 0 | decoder->len[code] = (l&7)+1; /* len = 2,3,4,5,6,7,8,1 */ |
454 | 0 | decoder->symbol[code] = 0; |
455 | 0 | for(u32 j=0; j<decoder->len[code]; j++) |
456 | 0 | ((u8*) &decoder->symbol[code])[j] = buf[pos++]; // note this enforces 'little endian' symbols |
457 | 0 | } |
458 | 0 | } |
459 | 0 | if (decoder->zeroTerminated) lenHisto[0]++; |
460 | | |
461 | | // fill unused symbols with text "corrupt". Gives a chance to detect corrupted code sequences (if there are unused symbols). |
462 | 0 | while(code<255) { |
463 | 0 | decoder->symbol[code] = FSST_CORRUPT; |
464 | 0 | decoder->len[code++] = 8; |
465 | 0 | } |
466 | 0 | return pos; |
467 | 0 | } |
468 | | |
469 | | // runtime check for simd |
470 | 0 | inline size_t _compressImpl(Encoder *e, size_t nlines, size_t lenIn[], u8 *strIn[], size_t size, u8 *output, size_t *lenOut, u8 *strOut[], bool noSuffixOpt, bool avoidBranch, int) { |
471 | 0 | return compressBulk(*e->symbolTable, nlines, lenIn, strIn, size, output, lenOut, strOut, noSuffixOpt, avoidBranch); |
472 | 0 | } |
473 | 0 | size_t compressImpl(Encoder *e, size_t nlines, size_t lenIn[], u8 *strIn[], size_t size, u8 *output, size_t *lenOut, u8 *strOut[], bool noSuffixOpt, bool avoidBranch, int simd) { |
474 | 0 | return _compressImpl(e, nlines, lenIn, strIn, size, output, lenOut, strOut, noSuffixOpt, avoidBranch, simd); |
475 | 0 | } |
476 | | |
477 | | // adaptive choosing of scalar compression method based on symbol length histogram |
478 | 0 | inline size_t _compressAuto(Encoder *e, size_t nlines, size_t lenIn[], u8 *strIn[], size_t size, u8 *output, size_t *lenOut, u8 *strOut[], int simd) { |
479 | 0 | bool avoidBranch = false, noSuffixOpt = false; |
480 | 0 | if (100*e->symbolTable->lenHisto[1] > 65*e->symbolTable->nSymbols && 100*e->symbolTable->suffixLim > 95*e->symbolTable->lenHisto[1]) { |
481 | 0 | noSuffixOpt = true; |
482 | 0 | } else if ((e->symbolTable->lenHisto[0] > 24 && e->symbolTable->lenHisto[0] < 92) && |
483 | 0 | (e->symbolTable->lenHisto[0] < 43 || e->symbolTable->lenHisto[6] + e->symbolTable->lenHisto[7] < 29) && |
484 | 0 | (e->symbolTable->lenHisto[0] < 72 || e->symbolTable->lenHisto[2] < 72)) { |
485 | 0 | avoidBranch = true; |
486 | 0 | } |
487 | 0 | return _compressImpl(e, nlines, lenIn, strIn, size, output, lenOut, strOut, noSuffixOpt, avoidBranch, simd); |
488 | 0 | } |
489 | 0 | size_t compressAuto(Encoder *e, size_t nlines, size_t lenIn[], u8 *strIn[], size_t size, u8 *output, size_t *lenOut, u8 *strOut[], int simd) { |
490 | 0 | return _compressAuto(e, nlines, lenIn, strIn, size, output, lenOut, strOut, simd); |
491 | 0 | } |
492 | | } // namespace libfsst |
493 | | |
494 | | using namespace libfsst; |
495 | | // the main compression function (everything automatic) |
496 | 0 | extern "C" size_t duckdb_fsst_compress(duckdb_fsst_encoder_t *encoder, size_t nlines, size_t lenIn[], u8 *strIn[], size_t size, u8 *output, size_t *lenOut, u8 *strOut[]) { |
497 | | // to be faster than scalar, simd needs 64 lines or more of length >=12; or fewer lines, but big ones (totLen > 32KB) |
498 | 0 | size_t totLen = std::accumulate(lenIn, lenIn+nlines, 0); |
499 | 0 | int simd = totLen > nlines*12 && (nlines > 64 || totLen > (size_t) 1<<15); |
500 | 0 | return _compressAuto((Encoder*) encoder, nlines, lenIn, strIn, size, output, lenOut, strOut, 3*simd); |
501 | 0 | } |
502 | | |
503 | | /* deallocate encoder */ |
504 | 0 | extern "C" void duckdb_fsst_destroy(duckdb_fsst_encoder_t* encoder) { |
505 | 0 | Encoder *e = (Encoder*) encoder; |
506 | 0 | delete e; |
507 | 0 | } |
508 | | |
509 | | /* very lazy implementation relying on export and import */ |
510 | 0 | extern "C" duckdb_fsst_decoder_t duckdb_fsst_decoder(duckdb_fsst_encoder_t *encoder) { |
511 | 0 | u8 buf[sizeof(duckdb_fsst_decoder_t)]; |
512 | 0 | u32 cnt1 = duckdb_fsst_export(encoder, buf); |
513 | 0 | duckdb_fsst_decoder_t decoder; |
514 | 0 | u32 cnt2 = duckdb_fsst_import(&decoder, buf); |
515 | | assert(cnt1 == cnt2); (void) cnt1; (void) cnt2; |
516 | 0 | return decoder; |
517 | 0 | } |