Debian Codegraph @

src/cxx/cffCompressor.cc

raw
1 /*
2 * Copyright 2015 Google Inc. All Rights Reserved.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 #include "cffCompressor.h"
18
19 // needed for Windows's "_setmode" to enable binary mode for stdin/stdout
20 #ifdef _WIN32
21 #include <fcntl.h>
22 #include <io.h>
23 #endif
24
25 const unsigned int_size = sizeof(int_type);
26 const float K = 0.1;
27 const float ALPHA = 0.1;
28 const unsigned hardware_threads = std::thread::hardware_concurrency();
29 const unsigned NUM_THREADS = hardware_threads ? hardware_threads : 1;
30 const unsigned DEFAULT_NUM_ROUNDS = 4;
31
32 // token_t ============
33 token_t::token_t(int_type value_) : value(value_) {}
34 token_t::token_t(const token_t &other) : value(other.value) {}
35
36 int_type token_t::getValue() const {
37 return value;
38 }
39
40 inline unsigned token_t::size() const {
41 return part(0);
42 }
43
44 inline unsigned token_t::part(unsigned idx) const {
45 assert(idx < 4);
46 char shift = (int_size - idx - 1) * 8;
47 return (value & (0xff << shift)) >> shift;
48 }
49
50 std::string token_t::toString() const {
51 std::ostringstream os;
52 os << "token_t(" << part(0) << ", " << part(1) <<
53 ", " << part(2) << ", " << part(3) << ")";
54 return os.str();
55 }
56
57 bool token_t::operator<(const token_t &other) const {
58 return value < other.value;
59 }
60
61 bool token_t::operator!=(const token_t &other) const {
62 return value != other.value;
63 }
64
65 bool token_t::operator==(const token_t &other) const {
66 return value == other.value;
67 }
68
69 std::ostream& operator<<(std::ostream &stream, const token_t &tok) {
70 return stream << tok.toString();
71 }
72 // end token_t ===============
73
74
75 // light_substring_t =========
76 bool light_substring_t::operator<(const light_substring_t &other) const {
77 /// compares actual tokens
78
79 // optimization if they are literally pointing to the same thing
80 if (begin == other.begin && end == other.end)
81 return false; // they are equal
82
83 unsigned thisLen = end - begin;
84 unsigned otherLen = other.end - other.begin;
85
86 if (thisLen < otherLen) {
87 auto p = std::mismatch(begin, end, other.begin);
88 if (p.first == end)
89 return true;
90 else
91 return *p.first < *p.second;
92 } else { // thisLen >= otherLen
93 auto p = std::mismatch(other.begin, other.end, begin);
94 if (p.first == other.end)
95 return false;
96 else
97 return *p.second < *p.first;
98 }
99 }
100
101 light_substring_t::light_substring_t(uint32_t start, uint32_t len,
102 charstring_pool_t* pool) {
103 begin = pool->get(start);
104 end = begin + len;
105 }
106 // end light_substring_t =====
107
108
109 // substring_t ===============
110 substring_t::substring_t(unsigned _len, unsigned _start, unsigned _freq)
111 : pos(0), flatten(true), start(_start), len(_len), freq(_freq), _cost(0) {}
112
113 substring_t::substring_t(const substring_t &other)
114 : pos(0), flatten(other.flatten), start(other.start), len(other.len),
115 freq(other.freq), _cost(0) {}
116
117 const_tokiter_t substring_t::begin(const charstring_pool_t &chPool) const {
118 return chPool.get(start);
119 }
120
121 const_tokiter_t substring_t::end(const charstring_pool_t &chPool) const {
122 return begin(chPool) + len;
123 }
124
125 std::string substring_t::toString(const charstring_pool_t &chPool) {
126 std::ostringstream os;
127 os << "[";
128 auto it = begin(chPool);
129 for (; it != end(chPool) - 1; ++it) {
130 os << *it << ", ";
131 }
132 ++it;
133 os << *it << "]";
134 return os.str();
135 }
136
137 uint16_t substring_t::cost(const charstring_pool_t &chPool) {
138 if (_cost != 0) {
139 return _cost;
140 } else {
141 // call other cost
142 int sum = doCost(chPool);
143 _cost = sum;
144 return _cost;
145 }
146 }
147
148 uint16_t substring_t::cost(const charstring_pool_t &chPool) const {
149 if (_cost != 0) {
150 return _cost;
151 } else {
152 return doCost(chPool);
153 }
154 }
155
156 uint16_t substring_t::doCost(const charstring_pool_t &chPool) const {
157 int sum = 0;
158 for (auto it = begin(chPool); it != end(chPool); ++it) {
159 sum += it->size();
160 }
161 return sum;
162 }
163
164 int substring_t::subrSaving(const charstring_pool_t &chPool) {
165 // XXX needs use_usages and true_cost, (and call_cost and subr_overhead params)
166 return doSubrSaving(cost(chPool));
167 }
168
169 int substring_t::subrSaving(const charstring_pool_t &chPool) const {
170 // XXX needs use_usages and true_cost, (and call_cost and subr_overhead params)
171 return doSubrSaving(cost(chPool));
172 }
173
174 int substring_t::doSubrSaving(int subCost) const {
175 int amt = freq;
176 int callCost = 5;
177 int subrOverhead = 3;
178
179 return subCost * amt
180 - subCost
181 - callCost * amt
182 - subrOverhead;
183 }
184
185 std::vector<unsigned char> substring_t::getTranslatedValue(
186 const charstring_pool_t& chPool) const {
187 std::vector<unsigned char> ans;
188
189 for (auto it = begin(chPool); it != end(chPool); ++it) {
190 std::vector<unsigned char> transTok = chPool.translateToken(*it);
191 ans.insert(ans.end(), transTok.begin(), transTok.end());
192 }
193
194 return ans;
195 }
196
197 substring_t& substring_t::operator=(const substring_t &other) {
198 if (*this != other) {
199 start = other.start;
200 len = other.len;
201 freq = other.freq;
202 _cost = other._cost;
203 }
204 return *this;
205 }
206
207 bool substring_t::operator<(const substring_t &other) const {
208 // ordering is by start pos, then len
209 if (start == other.start)
210 return len < other.len;
211 else
212 return start < other.start;
213 }
214
215 bool substring_t::operator==(const substring_t &other) const {
216 return start == other.start && len == other.len;
217 }
218
219 bool substring_t::operator!=(const substring_t &other) const {
220 return !(*this == other);
221 }
222
223 inline uint32_t substring_t::size() const {
224 return len;
225 }
226
227 inline uint32_t substring_t::getStart() const {
228 return start;
229 }
230
231 inline void substring_t::setAdjCost(float val) {
232 assert(val > 0);
233 adjCost = val;
234 }
235
236 inline void substring_t::syncPrice() {
237 price = adjCost;
238 }
239
240 void substring_t::updatePrice() {
241 float margCost = static_cast<float>(adjCost) / (freq + K);
242 price = margCost * ALPHA + price * (1 - ALPHA);
243 }
244
245 inline uint32_t substring_t::getFreq() const {
246 return freq;
247 }
248
249 inline void substring_t::resetFreq() {
250 freq = 0;
251 }
252
253 inline void substring_t::incrementFreq() {
254 ++freq;
255 }
256
257 inline void substring_t::increaseFreq(unsigned amt) {
258 freq += amt;
259 }
260
261 inline void substring_t::decrementFreq() {
262 assert(freq != 0);
263 --freq;
264 }
265
266 inline float substring_t::getPrice() const {
267 return price;
268 }
269
270 inline void substring_t::setPrice(float newPrice) {
271 price = newPrice;
272 }
273 // end substring_t ============
274
275
276 // charstring_pool_t ==========
277 charstring_pool_t::charstring_pool_t(unsigned nCharstrings)
278 : nextQuark(0), count(nCharstrings),
279 finalized(false), numRounds(DEFAULT_NUM_ROUNDS) {
280 pool.reserve(nCharstrings);
281 offset.reserve(nCharstrings + 1);
282 offset.push_back(0);
283 }
284
285 charstring_pool_t::charstring_pool_t(unsigned nCharstrings, int _nrounds)
286 : nextQuark(0), count(nCharstrings),
287 finalized(false), numRounds(_nrounds) {
288 pool.reserve(nCharstrings);
289 offset.reserve(nCharstrings + 1);
290 offset.push_back(0);
291 }
292
293 void charstring_pool_t::writeEncoding(
294 const encoding_list& enc,
295 const std::map<const substring_t*, uint32_t>& index,
296 std::ostream& outFile) {
297 // write the number of subrs called
298 assert(enc.size() < 128);
299 outFile.put(enc.size());
300 // write each call
301 for (const encoding_item& enc_item : enc) {
302 outFile.write(
303 reinterpret_cast<const char*>(&enc_item.pos),
304 sizeof(enc_item.pos)); // 4 bytes
305 auto it = index.find(enc_item.substr);
306 assert(it != index.end());
307 uint32_t subrIndex = it->second;
308 outFile.write(reinterpret_cast<const char*>(&subrIndex), 4);
309 }
310 }
311
312 void charstring_pool_t::writeSubrs(
313 std::list<substring_t>& subrs,
314 std::vector<encoding_list>& glyphEncodings,
315 std::ostream& outFile) {
316 /// write subrs
317 // write number of subrs
318 uint32_t numSubrs = (uint32_t) subrs.size();
319 outFile.write(reinterpret_cast<const char*>(&numSubrs), 4);
320
321 // number subrs
322 std::map<const substring_t*, uint32_t> index;
323
324 // write each subr's representative glyph and offset in that charstring
325 uint32_t curIndex = 0;
326 for (const substring_t& subr : subrs) {
327 index[&subr] = curIndex++;
328 uint32_t glyphIdx = rev[subr.getStart()];
329 uint32_t glyphOffset = subr.getStart() - offset[glyphIdx];
330 uint32_t subrLength = subr.size();
331 outFile.write(reinterpret_cast<const char*>(&glyphIdx), 4);
332 outFile.write(reinterpret_cast<const char*>(&glyphOffset), 4);
333 outFile.write(reinterpret_cast<const char*>(&subrLength), 4);
334 }
335
336 // after producing `index`, write subr encodings
337 for (const substring_t& subr : subrs) {
338 writeEncoding(subr.encoding, index, outFile);
339 }
340
341 /// write glyph encoding instructions
342 for (const encoding_list& glyphEnc : glyphEncodings) {
343 writeEncoding(glyphEnc, index, outFile);
344 }
345 }
346
347 unsigned charstring_pool_t::packEncoding(
348 const encoding_list& enc,
349 const std::map<const substring_t*, uint32_t>& index,
350 uint32_t* buffer) {
351 unsigned pos = 0;
352
353 // write the number of subrs called
354 buffer[pos++] = enc.size();
355 // write each call
356 for (const encoding_item& enc_item : enc) {
357 buffer[pos++] = enc_item.pos;
358 auto it = index.find(enc_item.substr);
359 assert(it != index.end());
360 uint32_t subrIndex = it->second;
361 buffer[pos++] = subrIndex;
362 }
363
364 return pos;
365 }
366
367 uint32_t* charstring_pool_t::getResponse(
368 std::list<substring_t>& subrs,
369 std::vector<encoding_list>& glyphEncodings,
370 unsigned& outputLength) {
371 unsigned length = 1 + subrs.size() * 3;
372 for (const substring_t& subr : subrs) {
373 length += 1 + subr.encoding.size() * 2;
374 }
375 for (const encoding_list& glyphEnc : glyphEncodings) {
376 length += 1 + glyphEnc.size() * 2;
377 }
378 outputLength = length;
379
380 uint32_t* buffer = new uint32_t[length];
381 unsigned pos = 0;
382
383 /// write subrs
384 // write number of subrs
385 uint32_t numSubrs = (uint32_t) subrs.size();
386 buffer[pos++] = numSubrs;
387
388 // number subrs
389 std::map<const substring_t*, uint32_t> index;
390
391 // write each subr's representative glyph and offset in that charstring
392 uint32_t curIndex = 0;
393 for (const substring_t& subr : subrs) {
394 index[&subr] = curIndex++;
395 uint32_t glyphIdx = rev[subr.getStart()];
396 uint32_t glyphOffset = subr.getStart() - offset[glyphIdx];
397 uint32_t subrLength = subr.size();
398 buffer[pos++] = glyphIdx;
399 buffer[pos++] = glyphOffset;
400 buffer[pos++] = subrLength;
401 }
402
403 // after producing `index`, write subr encodings
404 for (const substring_t& subr : subrs) {
405 pos += packEncoding(subr.encoding, index, buffer + pos);
406 }
407
408 /// write glyph encoding instructions
409 for (const encoding_list& glyphEnc : glyphEncodings) {
410 pos += packEncoding(glyphEnc, index, buffer + pos);
411 }
412
413 return buffer;
414 }
415
416 std::vector<unsigned char> charstring_pool_t::formatInt(int num) {
417 std::vector<unsigned char> ret;
418 if (num >= -107 && num <= 107) {
419 ret.push_back((unsigned char) num + 139);
420 } else if (num >= 108 && num <= 1131) {
421 unsigned char first = (num - 108) / 256;
422 unsigned char second = num - 108 - first * 256;
423 assert((static_cast<int>(first)) * 256 + static_cast<int>(second) + 108);
424 ret.push_back(first + 247);
425 ret.push_back(second);
426 } else if (num >= -1131 && num <= -108) {
427 unsigned char first = (num + 108) / 256;
428 unsigned char second = -num - 108 - first * 256;
429 assert(-(static_cast<int>(first)) * 256 - static_cast<int>(second) - 108);
430 ret.push_back(first + 251);
431 ret.push_back(second);
432 } else {
433 assert(num >= -32768 && num <= 32767);
434
435 ret.push_back((unsigned char) 28);
436 ret.push_back((unsigned char) ((num & 0xff00) >> 8));
437 ret.push_back((unsigned char) (num & 0xff));
438 }
439 return ret;
440 }
441
442 void charstring_pool_t::subroutinize(
443 std::list<substring_t>& substrings,
444 std::vector<encoding_list>& glyphEncodings) { // TODO: testMode
445 std::map<light_substring_t, substring_t*> substrMap;
446
447 /// set up map with initial values
448 for (substring_t &substr : substrings) {
449 substr.setAdjCost(substr.cost(*this));
450 substr.syncPrice();
451 light_substring_t key(substr.begin(*this), substr.end(*this));
452 substrMap[key] = &substr;
453 }
454
455 unsigned substringChunkSize = substrings.size() / NUM_THREADS + 1;
456 unsigned glyphChunkSize = count / NUM_THREADS + 1;
457 std::vector<std::thread> threads;
458 std::vector<std::vector<encoding_list> > results((count+glyphChunkSize-1)/glyphChunkSize);
459
460 for (int runCount = 0; runCount < numRounds; ++runCount) {
461 /// update market
462 for (substring_t& substr : substrings) {
463 substr.updatePrice();
464 }
465
466 /// minimize cost of substrings
467 // XXX consider redoing substringChunkSize
468 threads.clear();
469 auto curSubstr = substrings.begin();
470 for (unsigned i = 0; i < NUM_THREADS; ++i) {
471 if (i * substringChunkSize >= substrings.size())
472 break;
473
474 unsigned step = substringChunkSize;
475 if ((i + 1) * substringChunkSize > substrings.size())
476 step = substrings.size() - i * substringChunkSize;
477
478 auto start = curSubstr;
479 std::advance(curSubstr, step);
480
481 threads.push_back(std::thread(optimizeSubstrings,
482 std::ref(substrMap),
483 std::ref(*this),
484 start,
485 curSubstr));
486 }
487 for (auto threadIt = threads.begin(); threadIt != threads.end(); ++threadIt) {
488 threadIt->join();
489 }
490
491 // minimize cost of glyphstrings
492 threads.clear();
493 glyphEncodings.clear();
494 for (unsigned i = 0; i < NUM_THREADS; ++i) {
495 if (i * glyphChunkSize >= count)
496 break;
497
498 unsigned stop = (i + 1) * glyphChunkSize;
499 if (stop > count)
500 stop = count;
501
502 results[i].clear();
503 threads.push_back(std::thread(optimizeGlyphstrings,
504 std::ref(substrMap),
505 std::ref(*this),
506 i * glyphChunkSize,
507 stop,
508 std::ref(results[i])));
509 }
510 for (auto threadIt = threads.begin(); threadIt != threads.end(); ++threadIt) {
511 threadIt->join();
512 }
513
514 for (std::vector<encoding_list> &res : results) {
515 glyphEncodings.insert(glyphEncodings.end(), res.begin(), res.end());
516 }
517
518 // update usages
519 for (substring_t& substr : substrings) {
520 substr.resetFreq();
521 }
522
523 for (substring_t& substr : substrings) {
524 for (encoding_item& enc : substr.encoding) {
525 enc.substr->incrementFreq();
526 }
527 }
528 for (encoding_list& encList : glyphEncodings) {
529 for (encoding_item& enc : encList) {
530 enc.substr->incrementFreq();
531 }
532 }
533
534 /// cutdown
535 if (runCount <= numRounds - 2) { // NOTE: python checks for testMode
536 auto substrIt = substrings.begin();
537 for (; substrIt != substrings.end();) {
538 if (substrIt->subrSaving(*this) <= 0) {
539 light_substring_t key(substrIt->begin(*this), substrIt->end(*this));
540 size_t response = substrMap.erase(key);
541 // heuristic:
542 for (encoding_list::iterator encItem = substrIt->encoding.begin();
543 encItem != substrIt->encoding.end(); ++encItem) {
544 encItem->substr->increaseFreq(substrIt->getFreq() - 1);
545 }
546
547 substrIt = substrings.erase(substrIt);
548 } else {
549 ++substrIt;
550 }
551 }
552 }
553 }
554 }
555
556 void optimizeSubstrings(std::map<light_substring_t, substring_t*> &substrMap,
557 charstring_pool_t &csPool,
558 std::list<substring_t>::iterator begin,
559 std::list<substring_t>::iterator end) {
560 for (auto it = begin; it != end; ++it) {
561 auto ans = optimizeCharstring(
562 it->begin(csPool),
563 it->size(),
564 substrMap,
565 csPool,
566 true);
567 it->encoding = ans.first;
568 it->setAdjCost(ans.second);
569 }
570 }
571
572 void optimizeGlyphstrings(
573 std::map<light_substring_t, substring_t*> &substrMap,
574 charstring_pool_t &csPool,
575 unsigned start,
576 unsigned stop,
577 std::vector<encoding_list>& result) {
578 for (unsigned i = start; i < stop; ++i) {
579 charstring_t cs = csPool.getCharstring(i);
580 result.push_back(optimizeCharstring(
581 cs.begin,
582 cs.len,
583 substrMap,
584 csPool,
585 false)
586 .first);
587 }
588 }
589
590 std::pair<encoding_list, float> optimizeCharstring(
591 const_tokiter_t begin, uint32_t len,
592 std::map<light_substring_t, substring_t*> &substrMap,
593 charstring_pool_t& csPool, bool isSubstring) {
594 std::vector<float> results(len + 1);
595 std::vector<int> nextEncIdx(len, -1);
596 std::vector<substring_t*> nextEncSubstr(len, NULL);
597
598 for (int i = len - 1; i >= 0; --i) {
599 float minOption = -1;
600 int minEncIdx = len;
601 substring_t* minEncSubstr = NULL;
602 int curCost = 0;
603
604 const_tokiter_t curToken = begin + i;
605 for (unsigned j = i + 1; j <= len; ++j, ++curToken) {
606 curCost += curToken->size();
607
608 light_substring_t key(begin + i, begin + j);
609 auto entryIt = substrMap.find(key);
610 substring_t* substr;
611 float option;
612 if (!(i == 0 && j == len) && entryIt != substrMap.end()) {
613 // TODO: check to not subroutinize with yourself
614 substr = entryIt->second;
615 option = substr->getPrice() + results[j];
616 } else {
617 substr = NULL;
618 option = curCost + results[j];
619 }
620
621 if (option < minOption || minOption == -1) {
622 minOption = option;
623 minEncIdx = j;
624 minEncSubstr = substr;
625 }
626 }
627
628 results[i] = minOption;
629 nextEncIdx[i] = minEncIdx;
630 nextEncSubstr[i] = minEncSubstr;
631 }
632
633 encoding_list ans;
634 unsigned curEncIdx = 0;
635
636 while (curEncIdx < len) {
637 uint16_t lastIdx = curEncIdx;
638 substring_t* curEncSubstr = nextEncSubstr[curEncIdx];
639 curEncIdx = nextEncIdx[curEncIdx];
640
641 if (curEncSubstr != NULL) {
642 encoding_item item;
643 item.pos = lastIdx;
644 item.substr = curEncSubstr;
645 ans.push_back(item);
646 }
647 }
648
649 return std::pair<encoding_list, float>(ans, results[0]);
650 }
651
652 std::list<substring_t> charstring_pool_t::getSubstrings() {
653 if (!finalized)
654 finalize();
655
656 std::vector<unsigned> suffixes = generateSuffixes();
657 std::vector<unsigned> lcp = generateLCP(suffixes);
658 std::list<substring_t> substrings = generateSubstrings(suffixes, lcp);
659
660 return substrings;
661 }
662
663 charstring_t charstring_pool_t::getCharstring(unsigned idx) {
664 charstring_t cs;
665 cs.begin = pool.begin() + offset[idx];
666 cs.len = offset[idx + 1] - offset[idx];
667 return cs;
668 }
669
670 void charstring_pool_t::addRawCharstring(unsigned char* data, unsigned len) {
671 assert(!finalized);
672
673 uint32_t numHints = 0;
674 uint32_t stackSize = 0;
675
676 unsigned nToks = 0;
677 for (unsigned csPos = 0; csPos < len; ++csPos) {
678 unsigned char first = data[csPos];
679 unsigned tokSize;
680 if (first < 28 || (first >= 29 && first < 32)) {
681 if (first < 12) {
682 // operators 1-11
683 if (first == 1 || first == 3) {
684 // hstem/vstem
685 numHints += stackSize / 2;
686 }
687 tokSize = 1;
688 } else if (first == 12) {
689 // escape (12) + addl operator code
690 tokSize = 2;
691 } else if (first < 19) {
692 // operators 13-18
693 if (first == 18) {
694 // hstemhm
695 numHints += stackSize / 2;
696 }
697 tokSize = 1;
698 } else if (first < 21) {
699 // hintmask/cntrmask (19/20)
700 if (stackSize != 0) {
701 // account for additonal vhints on stack (assuming legal program)
702 numHints += stackSize / 2;
703 }
704 tokSize = 1 + numHints / 8 + ((numHints % 8 != 0) ? 1 : 0);
705 } else if (first < 28) {
706 // operators 21-27
707 if (first == 23) {
708 // vstemhm
709 numHints += stackSize / 2;
710 }
711 tokSize = 1;
712 } else {
713 // operators 29-31
714 tokSize = 1;
715 }
716
717 stackSize = 0;
718 } else {
719 stackSize += 1;
720
721 if (first == 28) {
722 // 16-bit signed
723 tokSize = 3;
724 } else if (first < 247) {
725 // -107 to 107
726 tokSize = 1;
727 } else if (first < 251) {
728 // +108 to +1131
729 tokSize = 2;
730 } else if (first < 255) {
731 // -108 to -1131
732 tokSize = 2;
733 } else {
734 // 4-byte floating point
735 tokSize = 5;
736 }
737 }
738
739 unsigned char* rawTok = new unsigned char[tokSize];
740 rawTok[0] = first;
741 memcpy(rawTok + 1, data + csPos + 1, tokSize - 1);
742 csPos += (tokSize - 1);
743
744 addRawToken(rawTok, tokSize);
745 delete[] rawTok;
746
747 ++nToks;
748 }
749
750 offset.push_back(offset.back() + nToks);
751 }
752
753 void charstring_pool_t::finalize() {
754 rev.reserve(pool.size());
755 int cur = 0;
756 for (unsigned i = 0; i < pool.size(); ++i) {
757 if (i >= offset[cur + 1])
758 ++cur;
759 rev.push_back(cur);
760 }
761
762 finalized = true;
763 }
764
765 const_tokiter_t charstring_pool_t::get(unsigned idx) const {
766 const_tokiter_t x = pool.begin() + idx;
767 return x;
768 }
769
770 inline uint16_t charstring_pool_t::quarkFor(unsigned char* data, unsigned len) {
771 // TODO: verify using a string key isn't a time problem
772 std::string key((const char*) data, (size_t) len);
773 auto it = quarkMap.find(key);
774 if (it == quarkMap.end()) {
775 assert(nextQuark < 65536);
776 assert(revQuark.size() == nextQuark);
777 unsigned q = nextQuark++;
778 quarkMap[key] = q;
779 revQuark.push_back(key);
780 return (uint16_t) q;
781 } else {
782 return (uint16_t) it->second;
783 }
784 }
785
786 void charstring_pool_t::addRawToken(unsigned char* data, unsigned len) {
787 assert(len > 0);
788 assert(len < 256);
789 int_type v = generateValue(data, len);
790 pool.push_back(token_t(v));
791 }
792
793 int_type charstring_pool_t::generateValue(unsigned char* data, unsigned len) {
794 int_type v;
795 if (len < int_size) {
796 v = len;
797 for (unsigned i = 0; i < len; ++i) {
798 v <<= 8;
799 v |= data[i];
800 }
801 v <<= 8 * (int_size - len - 1);
802 } else {
803 uint16_t q = quarkFor(data, len);
804 v = len;
805 v <<= 8;
806 v |= data[0];
807 v <<= 16;
808 v |= q;
809 // std::cout << "QUARK: " << q << std::endl;
810 }
811 return v;
812 }
813
814 struct charstring_pool_t::suffixSortFunctor {
815 const std::vector<token_t> &pool;
816 const std::vector<unsigned> &offset;
817 const std::vector<unsigned> &rev;
818 suffixSortFunctor(const std::vector<token_t> &_pool,
819 const std::vector<unsigned> &_offset,
820 const std::vector<unsigned> &_rev)
821 : pool(_pool), offset(_offset), rev(_rev) {}
822 bool operator()(unsigned a, unsigned b) {
823 int aLen = offset[rev[a] + 1] - a;
824 int bLen = offset[rev[b] + 1] - b;
825 auto aFirst = pool.begin() + a;
826 auto bFirst = pool.begin() + b;
827
828 if (aLen < bLen) {
829 auto aLast = pool.begin() + offset[rev[a] + 1];
830 auto p = std::mismatch(aFirst, aLast, bFirst);
831 if (p.first == aLast)
832 return true;
833 else
834 return *p.first < *p.second;
835 } else { // aLen >= bLen
836 auto bLast = pool.begin() + offset[rev[b] + 1];
837 auto p = std::mismatch(bFirst, bLast, aFirst);
838 if (p.first == bLast)
839 return false;
840 else
841 return *p.second < *p.first;
842 }
843 }
844 };
845
846 std::vector<unsigned> charstring_pool_t::generateSuffixes() {
847 assert(finalized);
848
849 std::vector<unsigned> suffixes;
850 suffixes.reserve(pool.size());
851
852 for (unsigned i = 0; i < pool.size(); ++i)
853 suffixes.push_back(i);
854
855 std::stable_sort(
856 suffixes.begin(),
857 suffixes.end(),
858 suffixSortFunctor(pool, offset, rev));
859
860 return suffixes;
861 }
862
863 std::vector<unsigned> charstring_pool_t::generateLCP(
864 const std::vector<unsigned> &suffixes) {
865 assert(finalized);
866 assert(suffixes.size() == pool.size());
867
868 std::vector<uint32_t> lcp(pool.size(), 0);
869 std::vector<uint32_t> rank(pool.size(), 0);
870
871 for (unsigned i = 0; i < pool.size(); ++i) {
872 unsigned idx = suffixes[i];
873 rank[idx] = i;
874 }
875
876 for (std::vector<unsigned>::iterator ch = offset.begin();
877 ch != offset.end() - 1; ++ch) {
878 unsigned start = *ch;
879 unsigned end = *(ch + 1);
880 unsigned curH = 0;
881 for (unsigned tokIdx = start; tokIdx < end; ++tokIdx) {
882 unsigned curRank = rank[tokIdx];
883 if (curRank > 0) {
884 unsigned befInSuffixes = suffixes[curRank - 1];
885 unsigned befEnd = offset[rev[befInSuffixes] + 1];
886 while (befInSuffixes + curH < befEnd
887 && tokIdx + curH < end
888 && pool[befInSuffixes + curH] == pool[tokIdx + curH])
889 ++curH;
890 lcp[curRank] = curH;
891
892 if (curH > 0)
893 --curH;
894 }
895 }
896 }
897
898 return lcp;
899 }
900
901 bool charstring_pool_t::verify_lcp(
902 std::vector<unsigned>& lcp,
903 std::vector<unsigned>& suffixes) {
904 for (unsigned i = 1; i < pool.size(); ++i) {
905 auto thisCur = pool.begin() + suffixes[i];
906 auto befCur = pool.begin() + suffixes[i - 1];
907 auto thisEnd = pool.begin() + offset[rev[suffixes[i]] + 1];
908 auto befEnd = pool.begin() + offset[rev[suffixes[i - 1]] + 1];
909 for (unsigned j = 0; j < lcp[i]; ++j) {
910 assert(*thisCur == *befCur);
911 ++thisCur;
912 ++befCur;
913 }
914 assert(*thisCur != *befCur || thisCur == thisEnd || befCur == befEnd);
915 }
916
917 return true;
918 }
919
920 std::list<substring_t> charstring_pool_t::generateSubstrings(
921 std::vector<unsigned> &suffixes,
922 std::vector<unsigned> &lcp) {
923 assert(finalized);
924 assert(suffixes.size() == lcp.size());
925 assert(lcp.size() == pool.size());
926
927 std::list<substring_t> substrings;
928 std::list<std::pair<unsigned, unsigned>> startIndices;
929
930 for (unsigned i = 0; i < suffixes.size(); ++i) {
931 while (!startIndices.empty() && startIndices.back().first > lcp[i]) {
932 unsigned len = startIndices.back().first;
933 unsigned startIdx = startIndices.back().second;
934 startIndices.pop_back();
935
936 unsigned freq = i - startIdx;
937 assert(freq >= 2); // NOTE: python allows different min_freq
938
939 substring_t subr(len, suffixes[startIdx], freq);
940 // NOTE: python allows turning this check off --
941 if (len > 1 && subr.subrSaving(*this) > 0) {
942 substrings.push_back(subr);
943 }
944 }
945
946 if (startIndices.empty() || lcp[i] > startIndices.back().first) {
947 startIndices.push_back(std::make_pair(lcp[i], i - 1));
948 }
949 }
950
951 // NOTE: python sorts by length or saving
952
953 return substrings;
954 }
955
956 std::vector<unsigned char> charstring_pool_t::translateToken(const token_t& tok) const {
957 size_t tokLen = tok.size();
958
959 if (tokLen < int_size) {
960 std::vector<unsigned char> ans;
961 for (unsigned i = 0; i < tokLen; ++i)
962 ans.push_back(tok.part(i + 1));
963 return ans;
964 } else {
965 uint16_t q = (tok.part(2) << 8) + tok.part(3);
966 std::string orig = revQuark.at(q);
967 std::vector<unsigned char> ans(orig.begin(), orig.end());
968 return ans;
969 }
970 }
971 // end charstring_pool_t =========
972
973
974
975 charstring_pool_t CharstringPoolFactory(
976 std::istream &instream,
977 int numRounds) {
978 uint16_t count;
979 unsigned char countBuffer[2];
980 instream.read(reinterpret_cast<char*>(countBuffer), 2);
981 count = (countBuffer[0] << 8) | (countBuffer[1]);
982
983 unsigned char offSize;
984 instream.read(reinterpret_cast<char*>(&offSize), 1);
985
986 uint32_t* offset = new uint32_t[count + 1];
987
988 unsigned char* offsetBuffer = new unsigned char[(count + 1) * offSize];
989 instream.read(reinterpret_cast<char*>(offsetBuffer), (count + 1) * offSize);
990 for (int i = 0; i < count + 1; ++i) {
991 offset[i] = 0;
992 for (int j = 0; j < offSize; ++j) {
993 offset[i] += offsetBuffer[i * offSize + j] << ((offSize - j - 1) * 8);
994 }
995 offset[i] -= 1; // CFF is 1-indexed(-ish)
996 }
997 delete[] offsetBuffer;
998 assert(offset[0] == 0);
999
1000 charstring_pool_t csPool(count, numRounds);
1001
1002 unsigned len;
1003 for (int i = 0; i < count; ++i) {
1004 unsigned len = offset[i + 1] - offset[i];
1005 char* data = new char[len];
1006 instream.read(data, len);
1007 csPool.addRawCharstring(reinterpret_cast<unsigned char*>(data), len);
1008 delete[] data;
1009 }
1010
1011 delete[] offset;
1012 csPool.finalize();
1013
1014 return csPool;
1015 }
1016
1017 void charstring_pool_t::printSuffix(unsigned idx, bool printVal) {
1018 std::cerr << "[";
1019 auto start = pool.begin() + idx;
1020 auto end = pool.begin() + offset[rev[idx] + 1];
1021 for (auto it = start; it != end; ++it) {
1022 if (printVal)
1023 std::cerr << it->getValue();
1024 else
1025 std::cerr << *it;
1026
1027 if (it + 1 != end)
1028 std::cerr << ", ";
1029 }
1030 std::cerr << "]" << std::endl;
1031 }
1032
1033 charstring_pool_t CharstringPoolFactoryFromString(
1034 unsigned char* buffer,
1035 int numRounds) {
1036 unsigned pos = 0;
1037
1038 uint16_t count;
1039 count = (buffer[pos] << 8) | (buffer[pos + 1]);
1040 pos += 2;
1041
1042 unsigned char offSize = buffer[pos++];
1043
1044 uint32_t* offset = new uint32_t[count + 1];
1045
1046 unsigned char* offsetBuffer = &buffer[pos];
1047 pos += (count + 1) * offSize;
1048 for (int i = 0; i < count + 1; ++i) {
1049 offset[i] = 0;
1050 for (int j = 0; j < offSize; ++j) {
1051 offset[i] += offsetBuffer[i * offSize + j] << ((offSize - j - 1) * 8);
1052 }
1053 offset[i] -= 1; // CFF is 1-indexed(-ish)
1054 }
1055 assert(offset[0] == 0);
1056
1057 charstring_pool_t csPool(count, numRounds);
1058
1059 unsigned len;
1060 for (int i = 0; i < count; ++i) {
1061 unsigned len = offset[i + 1] - offset[i];
1062 csPool.addRawCharstring(buffer + pos, len);
1063 pos += len;
1064 }
1065
1066 delete[] offset;
1067 csPool.finalize();
1068
1069 return csPool;
1070 }
1071
1072 extern "C" uint32_t* compreff(unsigned char* dataStream, int numRounds, unsigned& outputLength) {
1073 charstring_pool_t csPool = CharstringPoolFactoryFromString(dataStream,
1074 numRounds);
1075 std::list<substring_t> subrs = csPool.getSubstrings();
1076 std::vector<encoding_list> glyphEncodings;
1077 csPool.subroutinize(subrs, glyphEncodings);
1078 return csPool.getResponse(subrs, glyphEncodings, outputLength);
1079 }
1080
1081 extern "C" void unload(uint32_t* response) {
1082 free(response);
1083 }
1084
1085 int main(int argc, const char* argv[]) {
1086 int numRounds = DEFAULT_NUM_ROUNDS;
1087
1088 unsigned argIdx = 1;
1089 while (argIdx < static_cast<unsigned>(argc)) {
1090 if (strcmp(argv[argIdx], "--nrounds") == 0) {
1091 numRounds = atoi(argv[argIdx + 1]);
1092 argIdx += 2;
1093 } else {
1094 std::cerr << "Unrecognized argument: " << argv[argIdx] << std::endl;
1095 return 1;
1096 }
1097 }
1098
1099 #ifdef _WIN32
1100 if (_setmode(_fileno(stdin), _O_BINARY) == -1) {
1101 std::cerr << "Cannot set stdin to binary mode" << std::endl;
1102 return 1;
1103 }
1104 if (_setmode(_fileno(stdout), _O_BINARY) == -1) {
1105 std::cerr << "Cannot set stdout to binary mode" << std::endl;
1106 return 1;
1107 }
1108 #endif
1109
1110 charstring_pool_t csPool = CharstringPoolFactory(
1111 std::cin,
1112 numRounds);
1113
1114 std::list<substring_t> subrs = csPool.getSubstrings();
1115 std::vector<encoding_list> glyphEncodings;
1116 csPool.subroutinize(subrs, glyphEncodings);
1117
1118 csPool.writeSubrs(subrs, glyphEncodings, std::cout);
1119
1120 return 0;
1121 }