-
Notifications
You must be signed in to change notification settings - Fork 0
/
obf.cc
1576 lines (1394 loc) · 47 KB
/
obf.cc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include <cstdio>
#include <cassert>
#include <cctype>
#include <cstdarg>
#include <cstddef>
#include <cstdlib>
#include <cstring>
#include <cstdint>
#include <cinttypes>
#include <climits>
#include <fcntl.h>
#include <unistd.h>
#include <unordered_map>
#include <set>
#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>
#include <string>
#include <functional>
#include <type_traits>
/* Some kind of enumeration of the fragments we deal with.
*/
class Token {
protected:
uint16_t value;
static const uint16_t nothingValue = UINT16_MAX;
bool inRange(uint16_t s, uint16_t n) const { return s <= value && value < (s + n); }
explicit constexpr Token(uint16_t i = nothingValue) : value(i) {}
public:
static constexpr Token nothing() { return Token(nothingValue); }
bool isNothing() const { return value == nothingValue; }
uint16_t toInt() const { return value; }
uint16_t hash() const { return value; }
bool operator<(Token t) { return value < t.value; }
bool operator<=(Token t) { return value <= t.value; }
bool operator==(Token t) { return value == t.value; }
bool operator!=(Token t) { return !(value == t.value); }
bool operator>(Token t) { return !(value <= t.value); }
bool operator>=(Token t) { return !(value < t.value); }
};
/* Slightly more specific enumerations of single-character (ASCII) fragments.
*/
template<char const* alphabet, bool endToken = true>
class LetterlikeToken : public Token {
explicit LetterlikeToken(uint16_t i) : Token(i) { assert(isNothing() || value < range()); }
public:
explicit LetterlikeToken(char const* c) {
if (c && *c && strchr(alphabet, *c) != NULL) {
uint16_t i = strchr(alphabet, *c) - alphabet;
value = i;
} else {
value = nothingValue;
}
}
static constexpr LetterlikeToken fromChar(char c) {
return LetterlikeToken(&c);
}
static constexpr LetterlikeToken fromInt(uint16_t i) {
return LetterlikeToken(i);
}
static constexpr LetterlikeToken nothing() { return LetterlikeToken(nothingValue); }
char toChar() const { if (isNothing()) return '\0'; return alphabet[value]; }
static constexpr uint16_t range() { return strlen(alphabet) + (endToken ? 1 : 0); }
static constexpr LetterlikeToken end() { return LetterlikeToken(range() - 1); }
constexpr bool isEnd() const { return value == end().value; }
constexpr bool isDigit() const { return isdigit(toChar()); }
constexpr bool isXDigit() const { return isxdigit(toChar()); }
constexpr bool isAlpha() const { return isalpha(toChar()); }
constexpr bool isAlnum() const { return isalnum(toChar()); }
constexpr bool isPunct() const { return ispunct(toChar()); }
};
/* These alphabets are ordered such that under specific conditions (defined by
* classes within WordParser) the alphabet can be truncated and the
* range-coding parameters can be easily adjusted to account for that.
*/
static char constexpr letterAlphabet[] = "abcdefghijklmnopqrstuvwxyz'";
static char constexpr separatorAlphabet[] = ".!?,;:()[]-/\"'*";
static char constexpr numberAlphabet[] = "abcdefghijklmnopqrstuvwxyz0123456789$.,:";
typedef LetterlikeToken<letterAlphabet> LetterToken;
typedef LetterlikeToken<separatorAlphabet, false> SeparatorToken;
typedef LetterlikeToken<numberAlphabet> NumberToken;
/* Only some of the tokens represented here are words (the dictionary words).
* Why are the others in here? I'm not sure, anymore. This is where life
* began so there's a lot of history.
*
* Should I call this MacroToken, maybe?
*
* We have in here a list of dictionary words, separators (all the
* SeparatorTokens, above), escapes to numbers and words we have to spell out
* letter-by-letter, and suffixes.
*
* The suffixes were going to be words to be spelled out letter-by-letter but
* with pre-defined endings. By enumerating these separately, we get a
* compromise token for many words we can't fit in the dictionary which might
* (maybe) be interchangeable options in a markov chain, as in:
* "At school Albert studies (psych|astr|fren|thdrbroeptp)ology"
* but that represents a lot of extra work, so I haven't done it yet.
*/
class WordToken : public Token {
static std::unordered_map<std::string, uint16_t> wordMap;
static std::unordered_map<std::string, uint16_t> suffixMap;
static std::vector<std::string const*> wordList;
static std::vector<std::string const*> suffixList;
static std::vector<std::string> separatorStrings;
static uint16_t firstWord,
firstSuffix,
firstSeparator,
firstNumber,
firstOther;
static uint16_t periodValue;
static const uint16_t otherMask = 0x3fff;
/* hashValue should be the same as value except for tokens that are escapes
* to unknown words and numbers, in which case we use a hash of the spelling.
* This allows the context hash to respond to the specific (assuming no
* collisions) word even if it's not in the dictionary.
*/
uint16_t hashValue;
protected:
WordToken(uint16_t i, uint16_t h) : Token(i), hashValue(h) {}
public:
WordToken() : WordToken(nothingValue, nothingValue) {}
operator std::string const& () { return toString(*this); }
static WordToken nothing() { return WordToken(nothingValue, nothingValue); }
static WordToken fromInt(uint16_t i) { return WordToken(i, i); }
static size_t numWords() { return wordList.size(); }
static size_t numSuffixes() { return suffixList.size(); }
static size_t numOtherWords() { return otherMask + 1; }
static size_t numNumbers() { return 1; }
static size_t numSeparators() { return SeparatorToken::range(); }
static WordToken dictionaryWord(unsigned i) { assert(i < numWords()); return fromInt(firstWord + i); }
static WordToken suffixWord(unsigned i) { assert(i < numSuffixes()); return fromInt(firstSuffix + i); }
static WordToken otherWord(uint32_t h) { return WordToken(firstOther, firstOther + (h & otherMask)); }
static WordToken separatorWord(unsigned i) { assert(i < numSeparators()); return fromInt(firstSeparator + i); }
static WordToken numberWord(unsigned i) { assert(i < numNumbers()); return fromInt(firstNumber + i); }
static WordToken period() { return WordToken(periodValue, periodValue); }
uint16_t hash() const { return hashValue; }
bool isDictionaryWord() const { return inRange(firstWord, numWords()); }
bool isSuffix() const { return inRange(firstSuffix, numSuffixes()); }
bool isSeparator() const { return inRange(firstSeparator, numSeparators()); }
bool isNumber() const { return inRange(firstNumber, numNumbers()); }
bool isOtherWord() const { return inRange(firstOther, numOtherWords()); }
bool needsLetters() const { return isSuffix() || isOtherWord(); }
bool needsDigits() const { return isNumber(); }
std::string const& toString(WordToken t) const {
if (isDictionaryWord()) return *wordList[value - firstWord];
if (isSuffix()) return *suffixList[value - firstSuffix];
if (isSeparator()) return separatorStrings[value - firstSeparator];
static const std::string number("<999>");
if (isNumber()) return number;
static const std::string nothing("<nothing>");
if (isNothing()) return nothing;
static const std::string other("<smurf>");
return other;
}
std::string const& toString() const {
return toString(*this);
}
char const* c_str() const {
return toString(*this).c_str();
}
static uint16_t range() { return firstOther + 1; }
static ssize_t init(char const* dict = "dictionary.txt",
bool verbose = false);
public:
/* TODO: eliminate this... */
static ssize_t lookupWord(std::string const& s) {
auto it = wordMap.find(s);
if (it != wordMap.end()) {
return it->second;
}
return -1;
}
};
/* A utility class to incrementally classify strings (words, if you will) and
* report what characters would be legal extensions on what's been read so far.
* This manages things like prohibiting the end-of-word token in an "other"
* word when the word parsed so far is already a dictionary word (because we
* can never allow two encodings for the same string).
*
* This is all very ad-hoc and needs to be replaced by something less so. Also
* I started messing around with C++ more than I really needed to, here, and it
* probably shows.
*
* TODO: Start again.
*/
class WordParser {
template<typename T>
class ParserBase {
public:
using TokenType = T;
ParserBase() : illegalTokens(T::nothing()) {}
bool needMore() const { return !illegalTokens.isNothing(); }
bool isFailed() { return fail; }
TokenType getIllegalTokens() const { return illegalTokens; }
protected:
TokenType illegalTokens = TokenType::nothing();
bool fail = true;
};
template<typename T>
struct ParserTop : public T {
using typename T::TokenType;
using T::fail;
using T::illegalTokens;
using T::needMore;
using T::reset;
using T::update;
using T::get;
//std::static_assert(std::is_base_of<ParserBase<T::TokenType>, T>::value, "bad T");
ParserTop() : T() { start(); }
ParserTop(bool b) : T(b) { start(); }
void start() {
illegalTokens = TokenType::end();
fail = false;
reset();
}
WordToken append(TokenType t, uint32_t hash, bool reserved) {
if (fail) return WordToken::nothing();
if (t.isNothing() || t >= illegalTokens) {
fail = true;
return WordToken::nothing();
}
illegalTokens = reserved ? TokenType::end() : TokenType::nothing();
update(t);
if (fail || needMore()) return WordToken::nothing();
return get(hash);
}
WordToken append(char c, uint32_t hash, bool reserved) {
TokenType t = TokenType::fromChar(c);
return append(t, hash, reserved);
}
TokenType getIllegalTokens() const { return illegalTokens; }
};
class OtherWordParser_Middle : public ParserBase<LetterToken> {
protected:
void reset() {
illegalTokens = LetterToken::fromChar('\'');
}
void update(TokenType t) {
if (t == TokenType::fromChar('\'')) {
illegalTokens = TokenType::fromChar('\'');
}
}
WordToken get(uint32_t hash) const {
return WordToken::otherWord(hash);
}
};
class DictWordParser_Middle : public OtherWordParser_Middle {
std::string word; // TODO: eliminate
const bool enabled;
protected:
void reset() {
if (enabled) OtherWordParser_Middle::reset();
else fail = true;
}
void update(TokenType t) {
word += t.toChar();
OtherWordParser_Middle::update(t);
}
WordToken get(uint32_t hash) const {
// TODO: this, incrementally, with a triedawg/whatever in update()
int wordIndex = WordToken::lookupWord(word);
return (wordIndex >= 0) ? WordToken::dictionaryWord(wordIndex)
: WordToken::nothing();
}
public:
DictWordParser_Middle(bool enable = true) : enabled(enable) {}
};
class NumberParser_Middle : public ParserBase<NumberToken> {
bool seenNonAlpha;
protected:
void reset() {
seenNonAlpha = false;
/* can't have a . or , before we see a digit. */
illegalTokens = NumberToken::fromChar('.');
}
bool isNotLetter(NumberToken t) {
bool r = !t.isAlpha();
assert( r == LetterToken::fromChar(t.toChar()).isNothing());
return r;
}
void update(NumberToken t) {
seenNonAlpha = seenNonAlpha || isNotLetter(t);
if (!seenNonAlpha) {
illegalTokens = NumberToken::fromChar('.');
} else if (!t.isAlnum()) {
illegalTokens = NumberToken::end();
}
}
WordToken get(uint32_t hash) const {
if (seenNonAlpha) return WordToken::numberWord(0);
else return WordToken::nothing();
}
};
class SeparatorParser_Middle : public ParserBase<SeparatorToken> {
TokenType value = TokenType::nothing();
protected:
void reset() { value = TokenType::nothing(); }
void update(SeparatorToken t) {
if (value.isNothing()) value = t;
else fail = true;
}
WordToken get(uint32_t) const {
return WordToken::separatorWord(value.toInt());
}
};
public:
using OtherWordParser = ParserTop<OtherWordParser_Middle>;
using DictWordParser = ParserTop<DictWordParser_Middle>;
using NumberParser = ParserTop<NumberParser_Middle>;
using SeparatorParser = ParserTop<SeparatorParser_Middle>;
DictWordParser dict;
OtherWordParser other;
NumberParser number;
SeparatorParser separator;
WordToken dictToken;
WordToken otherToken;
WordToken numberToken;
WordToken separatorToken;
uint32_t hash;
size_t position;
WordToken goodToken;
size_t goodPosition;
public:
WordParser(bool useDict = true) : dict(useDict) {}
void start() {
hash = 0xdeadbeef;
position = 0;
goodToken = WordToken::nothing();
goodPosition = 0;
dict.start();
other.start();
separator.start();
number.start();
}
bool nextChar(char c) {
struct WordTokenAcc {
WordToken v;
WordTokenAcc() : v(WordToken::nothing()) {}
WordTokenAcc(WordToken t) : v(t) {}
WordTokenAcc operator |=(WordToken t) {
if (isNothing()) v = t;
return *this;
}
operator WordToken() { return v; }
bool isNothing() { return v.isNothing(); }
bool toInt() { return v.toInt(); }
std::string const& toString() { return v.toString(); }
} r;
hash = ((hash ^ (hash >> 15)) + c * 0x12345) * 31;
position++;
uint32_t h = (hash ^ (hash >> 17));
r |= (dictToken = dict.append(c, h, !r.isNothing()));
r |= (otherToken = other.append(c, h, !r.isNothing()));
r |= (numberToken = number.append(c, h, !r.isNothing()));
r |= (separatorToken = separator.append(c, h, !r.isNothing()));
if (!r.isNothing()) {
goodToken = r;
goodPosition = position;
}
bool done = dict.isFailed()
&& other.isFailed()
&& number.isFailed()
&& separator.isFailed();
return !done;
}
WordToken getResult(size_t& length) {
length = goodPosition;
return goodToken;
}
template<typename T> inline T getIllegalTokens() const;
template<typename T> inline WordToken getToken() const;
template<typename T>
bool isOk() const {
return !getToken<T>().isNothing();
}
};
template<> inline
LetterToken WordParser::getIllegalTokens<LetterToken>() const { return other.getIllegalTokens(); }
template<> inline
NumberToken WordParser::getIllegalTokens<NumberToken>() const { return number.getIllegalTokens(); }
template<> inline
SeparatorToken WordParser::getIllegalTokens() const { return separator.getIllegalTokens(); }
template<> inline
WordToken WordParser::getToken<LetterToken>() const { return otherToken; }
template<> inline
WordToken WordParser::getToken<NumberToken>() const { return numberToken; }
template<> inline
WordToken WordParser::getToken<SeparatorToken>() const { return separatorToken; }
/* Converts a std::istream to a series of WordTokens through calls to next().
*/
class Tokenizer {
std::istream& in;
std::string buffer;
std::string ungets;
bool lineNums = true;
int line = 1;
bool useDictionary;
int get() {
if (ungets.size() > 0) {
int r = ungets.back();
ungets.pop_back();
return r;
}
return in.get();
}
void putback(int c) {
assert(c != EOF);
ungets.push_back(c);
}
public:
Tokenizer(std::istream& stream, bool useDict = true, bool verbose = false)
: in(stream), lineNums(verbose), useDictionary(useDict) {
buffer.reserve(1024);
ungets.reserve(1024);
}
WordToken next() {
buffer.clear();
WordParser wp(useDictionary);
int c;
for (;;) {
while ((c = get()) != EOF && (isspace(c) || iscntrl(c))) {
if (c == '\n' && lineNums && ++line % 10000 == 0) {
printf("line %d\r", line);
fflush(stdout);
}
}
if (c == EOF) {
if (lineNums) printf("%d lines.\n", line);
return WordToken::nothing();
}
buffer.clear();
wp.start();
while (c != EOF && wp.nextChar(tolower(c))) {
buffer += tolower(c);
c = get();
}
size_t len;
auto t = wp.getResult(len);
if (!t.isNothing()) {
assert(len > 0);
if (c != EOF) putback(c);
while (buffer.length() > len) {
putback(buffer.back());
buffer.pop_back();
}
assert(!t.isNothing());
return t;
} else {
assert(len == 0);
}
}
}
std::string const& spellThat() {
return buffer;
}
};
std::vector<std::string const*> WordToken::wordList;
std::vector<std::string const*> WordToken::suffixList;
std::unordered_map<std::string, uint16_t> WordToken::wordMap;
std::unordered_map<std::string, uint16_t> WordToken::suffixMap;
std::vector<std::string> WordToken::separatorStrings;
uint16_t WordToken::firstWord,
WordToken::firstSuffix,
WordToken::firstSeparator,
WordToken::firstNumber,
WordToken::firstOther;
uint16_t WordToken::periodValue = Token::nothingValue;
ssize_t WordToken::init(char const* dict, bool verbose) {
std::filebuf fb;
if (!fb.open(dict, std::ios::in)) return -1;
if (verbose) {
printf("reading %s...\n", dict);
fflush(stdout);
}
std::istream is(&fb);
Tokenizer tok(is, false, verbose);
int count = 0;
while (!tok.next().isNothing()) {
auto& s = tok.spellThat();
if (isalpha(s[0]) && wordMap.emplace(s, count).second) count++;
}
fb.close();
if (verbose) printf("dictionary is %zu words.\n", wordMap.size());
/* TODO: suffixMap */
for (auto c : separatorAlphabet) {
if (c != '\0') {
separatorStrings.emplace_back(std::string(1, c));
}
}
wordList.resize(wordMap.size());
for (auto& it : wordMap) wordList[it.second] = &it.first;
suffixList.resize(suffixMap.size());
for (auto& it : suffixMap) suffixList[it.second] = &it.first;
firstWord = 0;
firstSuffix = firstWord + numWords();
firstSeparator = firstSuffix + numSuffixes();
firstNumber = firstSeparator + numSeparators();
firstOther = firstNumber + numNumbers();
periodValue = firstSeparator;
if (verbose) printf("dictWords: %zu, suffWords: %zu, sepWords: %zu, numWords: %zu\n",
numWords(), numSuffixes(), numSeparators(), numNumbers());
return 0;
}
/* Class needed by RangeCoder to get ranges to code. */
struct RangeCoderProb {
uint64_t getTotal() const { return total; }
virtual uint64_t getSpan(int symbol, uint64_t& base, uint64_t& size) const = 0;
virtual int getSymbol(uint64_t off, uint64_t& base, uint64_t& size) const = 0;
protected:
uint64_t total;
};
/* As advertised.
*/
class RangeCoder {
static const bool debug = true;
uint64_t low = 0;
uint64_t range = 0x8000000000000000;
__extension__ typedef unsigned __int128 uint128_t;
/* TODO: keep a running EOF stream value to detect/emit at EOF. */
void encode(uint64_t base, uint64_t size, uint64_t total) {
assert(size > 0);
assert(base + size <= total);
/* TODO: handle small ranges with deferred carry or suchlike. */
assert(total <= range);
low += base * (uint128_t)range / total;
range = size * (uint128_t)range / total;
dbg("(%08x-%08x ", (unsigned)(low >> 32), (unsigned)((low + range) >> 32));
if (bitsAvailable() > 0) {
if (debug) for (int i = 0; i < bitsAvailable(); i++)
dbgchar(((low << i) >> 63) ? '1' : '0');
advance(bitsAvailable());
}
if (debug) {
dbgchar(' ');
for (int i = 0; i < 12; i++) dbgchar(((low << i) >> 63) ? '1' : '0');
dbgchar('-');
for (int i = 0; i < 12; i++) dbgchar((((low + range - 1) << i) >> 63) ? '1' : '0');
dbg(" %08x-%08x)", (unsigned)(low >> 32), (unsigned)((low + range) >> 32));
}
}
protected:
uint64_t bs = 0;
public:
RangeCoder() { consume(63); }
int decode(RangeCoderProb const& p) {
uint64_t total = p.getTotal();
assert(total <= range);
//TODO: should be: `uint64_t off = ((bs - low) * (uint128_t)total + range - 1) / range;`, right?
uint64_t off = (bs - low) * (uint128_t)total / range;
uint64_t base, size;
int r = p.getSymbol(off, base, size);
dbg("dec: s:%08x-%08x ", (unsigned)(base >> 0), (unsigned)((base + size) >> 0));
encode(base, size, total);
assert(low <= bs && bs < (low + range));
return r;
}
void encode(RangeCoderProb const& p, int symbol) {
uint64_t base, size, total;
total = p.getSpan(symbol, base, size);
dbg("enc: s:%08x-%08x ", (unsigned)(base >> 0), (unsigned)((base + size) >> 0));
encode(base, size, total);
}
protected:
int bitsAvailable() const {
uint64_t test = low ^ (low + range);
return __builtin_clzll(test);
}
virtual void advance(int bits) {
emit(bits);
consume(bits);
low <<= bits;
range <<= bits;
}
virtual void emit(int bits) {
uint64_t bs = low;
for (int i = 0; i < bits; i++) {
putbit(bs >> 63);
bs <<= 1;
}
}
virtual void consume(int bits) {
for (int i = 0; i < bits; i++) {
bs = (bs << 1) | getbit();
}
}
virtual void putbit(int b) {
putchar('0' | b);
}
virtual int getbit() {
return random() & 1;
}
public:
void setLog(std::string* s) {
debuglog = s;
}
std::string log() {
if (debuglog) {
std::string r = *debuglog;
debuglog->clear();
return r;
}
return "";
}
private:
std::string* debuglog = NULL;
void dbgchar(char c) const {
if (debug && debuglog) *debuglog += c;
}
void dbg(char const* fmt, ...) const {
if (debug && debuglog) {
char buf[4096];
va_list ap;
va_start(ap, fmt);
vsnprintf(buf, sizeof(buf), fmt, ap);
va_end(ap);
*debuglog += buf;
}
}
};
/* Keep a hash of the last n tokens seen. Also keep 'alpha' and 'beta', hashes
* of the last 1 and 2 tokens seen.
*
* TODO(think): Is a distance of 1 pointless? The dictionary words are
* probably the commonest words and so that should be pretty flat -- there are
* only a couple of tokens where we should expect meaningfully un-flat values.
* Maybe distances of 2 and 3 make more sense.
*
* TODO: Make it not a template, with static history size (power of two) and
* programmable history distance.
*/
template <unsigned D, const uint64_t m = 0x98b5892bb6fb97d9>
class HistoryHash {
uint16_t history[D];
unsigned histpos = 0;
uint64_t hash = 0, alpha = 0, beta = 0;
uint64_t FullHash(void) {
uint64_t h = 0;
for (unsigned i = 0; i < D; i++) {
h = (h + history[(histpos + i) % D]) * m;
}
return h;
}
static uint64_t lag(unsigned d = D) {
uint64_t e = 1;
for (unsigned i = 0; i < d; i++) e *= m;
return e;
}
public:
HistoryHash(void) { reset(); }
void reset(void) {
memset(history, 0, sizeof(history));
histpos = 0;
hash = 0;
}
void integrate(uint32_t t) {
hash = hash - history[histpos] * lag();
t *= 0xb16d5a03;
t ^= t >> 15;
history[histpos] = t;
hash = (hash + history[histpos]) * m;
beta = (alpha + t) * m;
alpha = t * m;
histpos = (histpos + 1) % D;
assert(hash == FullHash());
}
void reset(uint32_t s) {
reset();
if (s) integrate(s);
}
uint32_t get(unsigned bits) const {
return (uint32_t)(hash ^ (hash >> 32)) >> (32 - bits);
}
uint32_t getAlpha(unsigned bits) const {
return (uint32_t)(alpha ^ (alpha >> 32)) >> (32 - bits);
}
uint32_t getBeta(unsigned bits) const {
return (uint32_t)(beta ^ (beta >> 32)) >> (32 - bits);
}
};
/* Manage accumulation of statistics and return probabilities for given context.
*/
template<typename T, int hashDist = 4,
uint64_t fscale = 1024, uint64_t fscale_a = 128, uint64_t fscale_b = 32>
class Mumble {
public:
using TokenType = T; // TODO: Pretty sure this isn't necessary.
using ContextHash = HistoryHash<hashDist>; // TODO: Can probably squash this, too.
class RCProb : public RangeCoderProb {
Mumble const& source;
ContextHash const& hashes;
uint64_t getSpan_(int symbol, uint64_t& base, uint64_t& size) const {
base = 0;
for (int i = 0; i < symbol; i++) base += source.getScore(hashes, i);
size = source.getScore(hashes, symbol);
return total;
}
int getSymbol_(uint64_t off, uint64_t& base, uint64_t& size) const {
assert(off < total);
base = 0;
int symbol = 0;
for (base = 0; base < total; base += size, symbol++) {
size = source.getScore(hashes, symbol);
if (off < base + size) {
return symbol;
}
}
assert(!"findToken() failed");
return -1;
}
public:
RCProb(Mumble const& src, ContextHash const& h, TokenType illegal)
: source(src), hashes(h) {
total = source.getTotal(hashes, illegal);
}
virtual uint64_t getSpan(int symbol, uint64_t& base, uint64_t& size) const override;
virtual int getSymbol(uint64_t off, uint64_t& base, uint64_t& size) const override;
};
RCProb getStats(ContextHash const& history, TokenType illegal) const {
return RCProb(*this, history, illegal);
}
private:
uint16_t tableSize;
template<uint32_t (*getHash)(ContextHash const& ctx)>
class FreqData {
#if 0
/* good for sparse tables,
* high memory overhead in dense tables (but overall win),
* terrible CPU overhead
*/
struct FreqTab : public std::multiset<uint16_t> {
FreqTab(uint32_t, uint16_t) {}
};
#else
/* bad for sparse tables,
* low memory overhead for dense tables (overall lose),
* minimal CPU overhead
*/
class FreqTab {
uint32_t total = 0;
std::vector<uint32_t> counts;
public:
FreqTab(uint32_t h, uint16_t sz) : total(0), counts(sz, 0) { }
void insert(uint16_t i) {
counts[i]++;
total++;
}
size_t count(uint16_t i) const { return counts[i]; }
size_t size(void) const { return total; }
using iterator = std::vector<uint32_t>::iterator;
using const_iterator = std::vector<uint32_t>::const_iterator;
};
#endif
std::unordered_map<uint32_t, FreqTab> freqMap;
uint64_t total = 0;
uint16_t tableSize;
public:
FreqData(uint16_t sz) : tableSize(sz) {}
void insert(ContextHash const& ctx, uint16_t i) {
total++;
auto set = freqMap.emplace(getHash(ctx), FreqTab(getHash(ctx), tableSize)).first;
set->second.insert(i);
}
size_t count(ContextHash const& ctx, uint16_t i) const {
auto set = freqMap.find(getHash(ctx));
if (set == freqMap.end()) return 0;
return set->second.count(i);
}
size_t size(ContextHash const& ctx) const {
auto set = freqMap.find(getHash(ctx));
if (set == freqMap.end()) return 0;
return set->second.size();
}
size_t size() const {
return total;
}
};
/* TODO: hashBits should be 32 (assumed to be sufficient for no collisions),
* but we're just going to cut it short and endure the collisions as "part of
* the fun", because we don't have a great underlying data structure right
* now (something that scales between sparse and dense while keeping the
* memory footprint minimal).
*/
static const int hashBits = 18;
static uint32_t getHash(ContextHash const& ctx) { return ctx.get(hashBits); }
static uint32_t getHash_a(ContextHash const& ctx) { return ctx.getAlpha(hashBits); }
static uint32_t getHash_b(ContextHash const& ctx) { return ctx.getBeta(hashBits); }
FreqData<getHash> freq;
FreqData<getHash_a> freq_a;
FreqData<getHash_b> freq_b;
void inc(ContextHash const& ctx, int i) {
freq.insert(ctx, i);
freq_a.insert(ctx, i);
freq_b.insert(ctx, i);
}
/* Currently histogram data is synthesised from three frequency tables. The
* stats for the full hashDist-length hash (very sparse), and the alpha and
* beta hashes (much denser). These are weighted by fscale* to give priority
* to the full-length hash when it's available, and to use the shorter hashes
* as low-weight tiebreakers. All that plus one for each bucket to ensure
* that every outcome is attainable.
*
* This method is really awful, and there's quite a lot obviously wrong with
* it, but it kind of worked a little bit at some point while I was hacking.
*
* Really the tables represent only weightings, and the absolute magnitudes
* reflect only the coverage of the sampling. These should be mixed in a
* more insightful way and the combined result distilled into something
* compact and easy to parse.
*
* TODO(quick-and-dirty): Throw away tables with low populations, and retain
* only the longest-match table that has adequate coverage. Refer to that
* alone.
*
* What I think we really want is a selection of typical sorted distributions
* (maybe just the one curve, in fact) and for each hash a pointer to a list
* of tokens in the order they appear on that curve under that hash. That's
* a fuzzy match already, and the order can probably afford to be fairly
* fuzzy too (especially for small values), so many hashes should share the
* same order and/or the same curve.
*
* TODO: Make that happen.
*
* TODO(interim): Scan the tables more sensibly (particularly when using
* multisets or similar), retaining results of past look-ups, iterators,
* etc..
*/
/* Answer queries from RCProb, for the range coder to use.
*/
uint64_t getScore(ContextHash const& ctx, int i) const {
return 1 + fscale * freq.count(ctx, i)
+ fscale_a * freq_a.count(ctx, i)
+ fscale_b * freq_b.count(ctx, i);
}
uint64_t getTotal(ContextHash const& ctx, TokenType illegal = TokenType::nothing()) const {
uint64_t total = tableSize + fscale * freq.size(ctx)
+ fscale_a * freq_a.size(ctx)
+ fscale_b * freq_b.size(ctx);
if (!illegal.isNothing()) {
for (int i = illegal.toInt(); i < tableSize; i++)
total -= getScore(ctx, i);
}
return total;
}
/* TODO: Could probably accept fscale* values here, and hash distance too.
* Not sure there's any need to make this a template at all... have to check
* how StringContext turns out to be sure.
*/
public:
Mumble(int tmax) : tableSize(tmax), freq(tmax), freq_a(tmax), freq_b(tmax) {
}
void integrate(ContextHash const& ctx, Token t) {
if (t.isNothing()) return;
uint16_t i = t.toInt();
assert(i < tableSize);
inc(ctx, i);
}
};
typedef Mumble<WordToken> WordMumble;
typedef Mumble<LetterToken, 6, 16, 1, 1> LetterMumble;
typedef Mumble<NumberToken, 6, 16, 1, 1> NumberMumble;
/* TODO: Make a better effort to expose what I really want in WordParser and
* then making a WordParser out of that, rather than throwing it all inside
* WordParser and ignoring the redundancy.
*/
template<typename T>
struct TokenParser : public WordParser {
void reset() { WordParser::start(); }
bool nextChar(T t) { return WordParser::nextChar(t.toChar()); }
T getIllegalTokens() const { return WordParser::getIllegalTokens<T>(); }
T end() const { assert(WordParser::isOk<T>()); return T::end(); }
T end(bool dictWord) const { assert(dictWord != WordParser::isOk<T>()); return T::end(); }
WordToken getToken() const { return WordParser::getToken<T>(); }
};
template<>
struct TokenParser<WordToken> {
WordToken v;
static void reset() {}
void nextChar(WordToken t) { v = t; }
static WordToken getIllegalTokens() { return WordToken::nothing(); }
WordToken end() const { return WordToken::nothing(); }
WordToken getToken() const { return v; }
};