-
Notifications
You must be signed in to change notification settings - Fork 36
/
dict-generate.cpp
1789 lines (1674 loc) · 55.3 KB
/
dict-generate.cpp
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
/**********************************************************************************
* Program to generate the dictionary for the C implementation of the zxcvbn password estimator.
* Copyright (c) 2015-2017 Tony Evans
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
**********************************************************************************/
#include <algorithm>
#include <iostream>
#include <string>
#include <fstream>
#include <list>
#include <set>
#include <vector>
#include <map>
#include <memory>
#include <limits>
#include <stdlib.h>
#include <string.h>
#include <math.h>
using namespace std;
class Node;
typedef std::shared_ptr<Node> NodeSPtr;
typedef std::weak_ptr<Node> NodeWPtr;
typedef std::map<char, NodeSPtr> NodeMap_t;
typedef unsigned int Check_t;
/**********************************************************************************
* Class to perform CRC checksum calculation.
*/
class TrieCheck
{
public:
typedef uint64_t Check_t;
static const Check_t CHK_INIT = 0xffffffffffffffff;
TrieCheck() { Init(); }
void Init() { mCrc = CHK_INIT; }
operator Check_t() const { return Result(); }
Check_t Result() const { return mCrc; }
bool operator ! () const { return mCrc == CHK_INIT; }
void operator () (const void *, unsigned int);
protected:
Check_t mCrc;
};
/**********************************************************************************
* Class to hold a node within the trie
*/
class Node
{
public:
Node();
Node(const Node &);
~Node();
Node & operator = (const Node &);
//bool operator == (const Node & r) const { return !IsEqual(r); }
//bool operator != (const Node & r) const { return !IsEqual(r); }
void SetEnd() { mEnd = true; }
bool IsEnd() const { return mEnd; }
int Height() const { return mHeight; }
// Scan the trie and count nodes
int NodeCount() { ClearCounted() ; return CountNodes(); }
int CalcAddress() { int a=0; ClearCounted(); a=CalcAddr(a, true); return CalcAddr(a, false); }
Node *GetParent() { return mParent; }
unsigned int GetAddr() const { return mAddr; }
NodeMap_t::iterator ChildBegin() { return mChild.begin(); }
NodeMap_t::iterator ChildEnd() { return mChild.end(); }
unsigned int GetNumChild() { return mChild.size(); }
int GetNumEnds() const { return mEndings; }
NodeSPtr FindChild(char);
std::string GetChildChars();
TrieCheck::Check_t CalcCheck();
int CalcEndings();
int CalcHeight();
NodeSPtr AddChild(char);
void ChangeChild(NodeSPtr &, NodeSPtr &);
// bool IsEqual(const Node &) const;
void ClearCounted();
void SetCounted() { mCounted = true; }
bool IsCounted() const { return mCounted; }
protected:
int CountNodes();
int CalcAddr(int, bool);
NodeMap_t mChild;
Node *mParent;
int mEndings;
int mHeight;
unsigned int mAddr;
TrieCheck mCheck;
bool mEnd;
bool mCounted;
};
/**********************************************************************************
* Static table used for the crc implementation.
*/
static const TrieCheck::Check_t CrcTable[16] =
{
0x0000000000000000, 0x7d08ff3b88be6f81, 0xfa11fe77117cdf02, 0x8719014c99c2b083,
0xdf7adabd7a6e2d6f, 0xa2722586f2d042ee, 0x256b24ca6b12f26d, 0x5863dbf1e3ac9dec,
0x95ac9329ac4bc9b5, 0xe8a46c1224f5a634, 0x6fbd6d5ebd3716b7, 0x12b5926535897936,
0x4ad64994d625e4da, 0x37deb6af5e9b8b5b, 0xb0c7b7e3c7593bd8, 0xcdcf48d84fe75459
};
// Update the crc value with new data.
void TrieCheck::operator () (const void *v, unsigned int Len)
{
Check_t Crc = mCrc;
const unsigned char *Data = reinterpret_cast<const unsigned char *>(v);
while(Len--)
{
Crc = CrcTable[(Crc ^ (*Data >> 0)) & 0x0f] ^ (Crc >> 4);
Crc = CrcTable[(Crc ^ (*Data >> 4)) & 0x0f] ^ (Crc >> 4);
++Data;
}
mCrc = Crc;
}
Node::Node()
{
mEndings = -1;
mHeight = -1;
mEnd = false;
mParent = 0;
}
Node::Node(const Node &r)
{
*this = r;
}
Node::~Node()
{
}
Node &Node::operator = (const Node & r)
{
mChild = r.mChild;
mParent = r.mParent;
mEndings = r.mEndings;
mHeight = r.mHeight;
mCheck = r.mCheck;
mEnd = r.mEnd;
return *this;
}
/**********************************************************************************
* Generate a checksum for the current node. Value also depends of the
* checksum of any child nodes
*/
TrieCheck::Check_t Node::CalcCheck()
{
if (!mCheck)
{
// Not done this node before
char c;
NodeMap_t::iterator It;
mCheck.Init();
// Include number of children
c = mChild.size();
mCheck(&c, sizeof c);
// For each child include its character and node checksum
for(It = mChild.begin(); It != mChild.end(); ++It)
{
Check_t n = It->second->CalcCheck();
c = It->first;
mCheck(&c, sizeof c);
mCheck(&n, sizeof n);
}
// Finally include whether this node is an ending in the chaecksum
c = mEnd;
mCheck(&c, sizeof c);
}
return mCheck;
}
/**********************************************************************************
* Get number of nodes for this which end/finish a word
*/
int Node::CalcEndings()
{
if (mEndings < 0)
{
// Not already done this node,so calculate the ends
int n = 0;
NodeMap_t::iterator It;
// Number of endings is sum of the endings of the child nodes and plus this node if it ends a word
for(It = mChild.begin(); It != mChild.end(); ++It)
n += It->second->CalcEndings();
n += !!mEnd;
mEndings = n;
}
return mEndings;
}
/**********************************************************************************
* Calculate the height of the trie starting at current node
*/
int Node::CalcHeight()
{
if (mHeight < 0)
{
// Not already done this node,so calculate the height
int Hi = 0;
NodeMap_t::iterator It;
// Get height of all child nodes, remember the highest
for(It = mChild.begin(); It != mChild.end(); ++It)
{
int i = It->second->CalcHeight();
if (i >= Hi)
Hi = i+1;
}
mHeight = Hi;
}
return mHeight;
}
/**********************************************************************************
* Clear indication that node has been counted
*/
void Node::ClearCounted()
{
NodeMap_t::iterator It;
mCounted = false;
for(It = mChild.begin(); It != mChild.end(); ++It)
It->second->ClearCounted();
}
/**********************************************************************************
* Count this plus the number of child nodes. As part of the tree node count
* scan, make sure not to double count nodes
*/
int Node::CountNodes()
{
// Count is 0 if already done
if (mCounted)
return 0;
mCounted = true;
NodeMap_t::iterator It;
int i = 1; // 1 for this node
// Add the child nodes
for(It = mChild.begin(); It != mChild.end(); ++It)
i += It->second->CountNodes();
return i;
}
/**********************************************************************************
* Calculate the final node address
*/
int Node::CalcAddr(int Start, bool ManyEnds)
{
NodeMap_t::iterator It;
if (!(mCounted || (ManyEnds && (mEndings < 256))))
{
mCounted = true;
mAddr = Start++;
}
for(It = mChild.begin(); It != mChild.end(); ++It)
Start = It->second->CalcAddr(Start, ManyEnds);
return Start;
}
/**********************************************************************************
* Add the given character to the current node, return the next lower node
*/
NodeSPtr Node::AddChild(char c)
{
NodeMap_t::iterator It;
// Find character in map of child nodes
It = mChild.find(c);
if (It == mChild.end())
{
// New character, create new child node
NodeSPtr a(new Node);
a->mParent = this;
std::pair<char, NodeSPtr> x(c, a);
std::pair<NodeMap_t::iterator, bool> y = mChild.insert(x);
It = y.first;
}
return It->second;
}
/**********************************************************************************
* Find the child node which corresponds to the given character.
*/
NodeSPtr Node::FindChild(char Ch)
{
NodeMap_t::iterator It;
It = mChild.find(Ch);
if (It == mChild.end())
return NodeSPtr();
return It->second;
}
/**********************************************************************************
* Replace the current child node (old param) with a new child (Replace param),
* and update the new child parent.
*/
void Node::ChangeChild(NodeSPtr & Replace, NodeSPtr & Old)
{
NodeMap_t::iterator It;
for(It = mChild.begin(); It != mChild.end(); ++It)
{
NodeSPtr p = It->second;
if (p == Old)
{
It->second = Replace;
Replace->mParent = this;
break;
}
}
}
/**********************************************************************************
* Find all the characters corresponding to the children of this node.
*/
std::string Node::GetChildChars()
{
NodeMap_t::iterator It;
std::string Result;
for(It = mChild.begin(); It != mChild.end(); ++It)
{
char c = It->first;
Result += c;
}
return Result;
}
/**********************************************************************************
* struct to hold data read from input file (except for the word string)
*/
struct Entry
{
Entry() : mRank(0), mDict(0), mOrder(0), mOccurs(0) {}
int mRank;
int mDict;
int mOrder;
int mOccurs;
};
/**********************************************************************************
* Struct to hold a string and an int. Also provide the compare operators for std::set class
*/
struct StringInt
{
string s;
unsigned int i;
StringInt() { i=0; }
StringInt(const StringInt & r) : s(r.s), i(r.i) {}
StringInt & operator = (const StringInt & r) { i = r.i; s = r.s; return *this; }
bool operator < (const StringInt & r) const { return s < r.s; }
bool operator > (const StringInt & r) const { return s > r.s; }
bool operator == (const StringInt & r) const { return s == r.s; }
StringInt * Self() const { return const_cast<StringInt *>(this); }
};
typedef map<string, Entry> EntryMap_t;
typedef list<string> StringList_t;
typedef list<NodeSPtr> NodeList_t;
typedef set<StringInt> StringIntSet_t;
typedef vector<int> StringOfInts;
typedef vector<unsigned int> UintVect;
typedef vector<uint64_t> Uint64Vect;
typedef vector<StringInt *> StrIntPtrVect_t;
typedef vector<StringInt> StringIntVect_t;
// Variables holding 'interesting' information on the data
unsigned int MaxLength, MinLength, NumChars, NumInWords, NumDuplicate;
static string PassWithMaxChilds, MaxChildChars;
static unsigned int MaxNumChilds, MaxChildsPosn;
struct FileInfo
{
FileInfo() : Words(0), BruteIgnore(0), Accented(0), Dups(0), Used(0), Rank(0) { }
string Name;
StringList_t Pwds;
int Words;
int BruteIgnore;
int Accented;
int Dups;
int Used;
int Rank;
};
/**********************************************************************************
* Read the file of words and add them to the file information.
*/
static bool ReadInputFile(const string & FileName, FileInfo &Info, int MaxRank)
{
ifstream f(FileName.c_str());
if (!f.is_open())
{
cerr << "Error opening " << FileName << endl;
return false;
}
Info.Name = FileName;
// Rank is the position of the work in the dictionary file. Rank==1 is lowest for a word (and
// indicates a very popular or bad password).
int Rank = 0;
string Line;
while(getline(f, Line) && (Rank < MaxRank))
{
// Truncate at first space or tab to leave just the word in case additional info on line
string::size_type y = Line.find_first_of("\t ");
if (y != string::npos)
Line.erase(y);
y = Line.length();
if (!y)
continue;
++Info.Words;
// Only use words where all chars are ascii (no accents etc.)
string::size_type x;
double BruteForce = 1.0;
for(x = 0; x < y; ++x)
{
unsigned char c = Line[x];
if (c >= 128)
break;
c = tolower(c);
Line[x] = c;
BruteForce *= 26.0;
}
if (x < y)
{
++Info.Accented;
continue;
}
// Don't use words where the brute force strength is less than the word's rank
if (BruteForce < (Rank+1))
{
++Info.BruteIgnore;
continue;
}
// Remember some interesting info
if (y > MaxLength)
MaxLength = y;
if (y < MinLength)
MinLength = y;
NumChars += y;
Info.Pwds.push_back(Line);
++Rank;
}
f.close();
return true;
}
static void CombineWordLists(EntryMap_t & Entries, FileInfo *Infos, int NumInfo)
{
bool Done = false;
int Rank = 0;
while(!Done)
{
int i;
++Rank;
Done = true;
for(i = 0; i < NumInfo; ++i)
{
FileInfo *p = Infos + i;
while(!p->Pwds.empty())
{
Done = false;
string Word = p->Pwds.front();
p->Pwds.pop_front();
EntryMap_t::iterator It = Entries.find(Word);
if (It != Entries.end())
{
// Word is repeat of one from another file
p->Dups += 1;
++NumDuplicate;
}
else
{
// New word, add it
Entry e;
e.mDict = i;
e.mRank = Rank;
Entries.insert(std::pair<std::string, Entry>(Word, e));
p->Used += 1;
break;
}
}
}
}
}
/**********************************************************************************
* Use all words previously read from file(s) and add them to a Trie, which starts
* at Root. Also update a bool array indicating the chars used in the words.
*/
static void ProcessEntries(NodeSPtr Root, EntryMap_t & Entries, bool *InputCharSet)
{
EntryMap_t::iterator It;
std::string Text;
for(It = Entries.begin(); It != Entries.end(); ++It)
{
Text = It->first;
// Add latest word to tree
string::size_type x;
NodeSPtr pNode = Root;
for(x = 0; x < Text.length(); ++x)
{
char c = Text[x];
pNode = pNode->AddChild(c);
// Add char to set of used character codes
InputCharSet[c & 0xFF] = true;
}
pNode->SetEnd();
}
}
/**********************************************************************************
* Add the passed node to the list if it has same height as value in Hi (= number
* of steps to get to a terminal node). If current node has height greater than Hi,
* recursivly call with each child node as one of these may be at the required height.
*/
static void AddToListAtHeight(NodeList_t & Lst, NodeSPtr Node, int Hi)
{
if (Hi == Node->Height())
{
Lst.push_back(Node);
return;
}
if (Hi < Node->Height())
{
NodeMap_t::iterator It;
for(It = Node->ChildBegin(); It != Node->ChildEnd(); ++It)
{
AddToListAtHeight(Lst, It->second, Hi);
}
}
}
/**********************************************************************************
* Scan the trie and update the original word list with the alphabetical order
* (or 'index location') of the words
*/
static void ScanTrieForOrder(EntryMap_t & Entries, int & Ord, NodeSPtr Root, const string & Str)
{
if (Root->IsEnd())
{
// Root is a word ending node, so store its index in the input word store
EntryMap_t::iterator Ite;
Ite = Entries.find(Str);
if (Ite == Entries.end())
throw "Trie string not in entries";
Ite->second.mOrder = ++Ord;
}
NodeMap_t::iterator It;
string Tmp;
// For each child, append its character to the current word string and do a recursive
// call to update their word indexes.
for(It = Root->ChildBegin(); It != Root->ChildEnd(); ++It)
{
Tmp = Str + It->first;
ScanTrieForOrder(Entries, Ord, It->second, Tmp);
}
}
/**********************************************************************************
* Reduce the trie by merging tails where possible. Starting at greatest height,
* get a list of all nodes with given height, then test for identical nodes. If
* found, change the parent of the second identical node to use the first node,
* and delete second node and its children. Reduce height by one and repeat
* until height is zero.
*/
static void ReduceTrie(NodeSPtr Root)
{
int Height;
Root->CalcCheck();
NodeSPtr pNode = Root;
for(Height = Root->CalcHeight(); Height >= 0; --Height)
{
// Get a list of all nodes at given height
NodeList_t Lst;
AddToListAtHeight(Lst, Root, Height);
NodeList_t::iterator Ita, Itb;
for(Ita = Lst.begin(); Ita != Lst.end(); ++Ita)
{
// Going to use a CRC to decide if two nodes are identical
TrieCheck::Check_t Chka = (*Ita)->CalcCheck();
Itb = Ita;
for(++Itb; Itb != Lst.end(); )
{
if (Chka == (*Itb)->CalcCheck())
{
// Found two identical nodes (with identical children)
Node * Parentb = (*Itb)->GetParent();
if (Parentb)
{
// Change the 2nd parent to use the current node as child
// Remove the 2nd node from the scanning list to as it will
// get deleted by the sharing (as using std::shared_ptr)
Parentb->ChangeChild(*Ita, *Itb);
Itb = Lst.erase(Itb);
}
else
{
cout << " orphan ";
++Itb;
}
}
else
{
++Itb;
}
}
}
}
}
/**********************************************************************************
* Scan the trie to match with the supplied word. Return the order of the
* word, or -1 if it is not in the trie.
*/
static int CheckWord(NodeSPtr Root, const string & Str)
{
int i = 1;
bool e = false;
string::size_type x;
NodeSPtr p = Root;
for(x = 0; x < Str.length(); ++x)
{
int j;
NodeMap_t::iterator It;
// Scan children to find one that matches current character
char c = Str[x];
for(It = p->ChildBegin(); It != p->ChildEnd(); ++It)
{
if (It->first == c)
break;
// Add the number of endings at or below child to track the alphabetical index
j = It->second->CalcEndings();
i += j;
}
// Fail if no child matches the character
if (It == p->ChildEnd())
return -1;
// Allow for this node being a word ending
e = p->IsEnd();
if (e)
++i;
if (p->GetNumChild() > MaxNumChilds)
{
NodeMap_t::iterator Itc;
MaxNumChilds = p->GetNumChild();
MaxChildsPosn = x;
PassWithMaxChilds = Str;
MaxChildChars.clear();
for(Itc = p->ChildBegin(); Itc != p->ChildEnd(); ++Itc)
MaxChildChars += Itc->first;
}
p = It->second;
}
if (p && p->IsEnd())
{
if (x == Str.length())
return i;
}
return -1;
}
/**********************************************************************************
* Try to find every input word in the reduced trie. The order should also
* match, otherwise the reduction has corrupted the trie.
*/
static int CheckReduction(StringIntVect_t & Ranks, NodeSPtr Root, EntryMap_t & Entries)
{
int i = 0;
int n = 0;
EntryMap_t::iterator It;
std::string Text;
int b;
Ranks.resize(Entries.size()+1);
for(It = Entries.begin(); (It != Entries.end()) && (i <= 200000); ++It)
{
Text = It->first;
b = CheckWord(Root, Text);
if (b < 0)
{
++i;
cout << It->second.mOrder << ": Missing " << Text.c_str() << endl;
}
else if (It->second.mOrder != b)
{
++i;
cout << It->second.mOrder << ": Bad order " << b << " for " << Text.c_str() << endl;
}
else
{
//if (Text == "fred")
// cout << Text.c_str() << "-> " << It->second.mOrder << ", " << It->second.mRank << endl;
++n;
}
if (b >= int(Ranks.size()))
throw " Using Ranks beyond end";
if (b >= 0)
{
char Tmp[20];
Ranks[b].i = It->second.mRank;
snprintf(Tmp, sizeof(Tmp), "%d: ", n);
Ranks[b].s = string(Tmp) + Text;
}
// Try to find a non-existant word
Text.insert(0, "a");
Text += '#';
b = CheckWord(Root, Text);
if (b > 0)
throw string("Found non-existant word ") + Text;
}
if (i > 0)
throw "Missing words in reduction check = " + to_string(i);
return n;
}
struct ChkNum
{
int Match;
int Err;
ChkNum() : Match(0), Err(0) {}
ChkNum(const ChkNum &r) : Match(r.Match), Err(r.Err) {}
ChkNum & operator = (const ChkNum & r) { Match = r.Match; Err = r.Err; return *this; }
ChkNum & operator += (const ChkNum & r) { Match += r.Match; Err += r.Err; return *this; }
};
/**********************************************************************************
* Find all possible words in the trie and make sure they are input words.
* Return number of words found. Done as a second trie check.
*/
static ChkNum CheckEntries(NodeSPtr Root, string Str, const EntryMap_t & Entries)
{
ChkNum Ret;
if (Root->IsEnd())
{
// This is an end node, find the word in the input words
EntryMap_t::const_iterator It = Entries.find(Str);
if (It != Entries.end())
++Ret.Match;
else
++Ret.Err;
}
// Add each child character to the passed string and recursively check
NodeMap_t::iterator It;
for(It = Root->ChildBegin(); It != Root->ChildEnd(); ++It)
{
string Tmp = Str;
Tmp += It->first;
Ret += CheckEntries(It->second, Tmp, Entries);
}
return Ret;
}
/**********************************************************************************
* Convert the passed bool array of used chars into a character string
*/
string MakeCharSet(bool *InputCharSet)
{
int i;
string s;
for(i = 1; i < 256; ++i)
{
if (InputCharSet[i])
s += char(i);
}
return s;
}
/**********************************************************************************
* Create a set of strings which contain the possible characters matched at
* a node when checking a word.
*/
void MakeChildBitMap(StringIntSet_t & StrSet, NodeSPtr Root, int & Loc)
{
// Skip if already done
if (Root->IsCounted())
return;
string::size_type x;
StringInt In;
NodeSPtr p = Root;
In.s = Root->GetChildChars();
if (StrSet.find(In) == StrSet.end())
{
// Not already in set of possible child chars for a node, so add it
In.i = Loc++; // Address in the final output array
StrSet.insert(In);
}
// Recursively do the child nodes
for(x = 0; x < In.s.length(); ++x)
{
char c = In.s[x];
NodeSPtr q = p->FindChild(c);
if (q)
MakeChildBitMap(StrSet, q, Loc);
}
Root->SetCounted();
}
// Constants defining bit positions of node data
// Number of bits to represent the index of the child char pattern in the final child bitmap array,
const int BITS_CHILD_PATT_INDEX = 14;
// Number of bits to represent index of where the child pointers start for this node in
// the Child map array and its bit position
const int BITS_CHILD_MAP_INDEX = 18;
const int SHIFT_CHILD_MAP_INDEX = BITS_CHILD_PATT_INDEX;
// Bit positions of word ending indicator and indicator for number of word endings for this + child nodes is >= 256
const int SHIFT_WORD_ENDING_BIT = SHIFT_CHILD_MAP_INDEX + BITS_CHILD_MAP_INDEX;
const int SHIFT_LARGE_ENDING_BIT = SHIFT_WORD_ENDING_BIT + 1;
/**********************************************************************************
* Create the arrays of data that will be output
*/
void CreateArrays(NodeSPtr Root, StringIntSet_t & StrSet, StringOfInts & ChildAddrs, Uint64Vect & NodeData, UintVect & NodeEnds)
{
NodeMap_t::iterator Itc;
StringInt Tmp;
StringOfInts Chld;
// Find children in the child pattern array
Tmp.s= Root->GetChildChars();
StringIntSet_t::iterator Its = StrSet.find(Tmp);
// Make a 'string' of pointers to the children
for(Itc = Root->ChildBegin(); Itc != Root->ChildEnd(); ++Itc)
{
int i = Itc->second->GetAddr();
Chld.push_back(i);
}
// Find where in pointer array the child pointer string is
StringOfInts::size_type x = search(ChildAddrs.begin(), ChildAddrs.end(), Chld.begin(), Chld.end()) - ChildAddrs.begin();
if (x == ChildAddrs.size())
{
// Not found, add it
ChildAddrs.insert(ChildAddrs.end(), Chld.begin(), Chld.end());
}
// Val will contain the final node data
uint64_t Val = Its->i;
if (Val >= (1 << BITS_CHILD_PATT_INDEX))
{
char Tmp[20];
snprintf(Tmp, sizeof Tmp, "%u", Its->i);
throw string("Not enough bits for child pattern index value of ") + Tmp + " for " +
Its->s + " (BITS_CHILD_PATT_INDEX too small)";
}
if (x >= (1 << BITS_CHILD_MAP_INDEX))
{
char Tmp[24];
snprintf(Tmp, sizeof Tmp, "%lu", x);
throw string("Not enough bits for child map index value of ") + Tmp + " for " +
Its->s + " (BITS_CHILD_MAP_INDEX too small)";
}
Val |= x << SHIFT_CHILD_MAP_INDEX;
if (Root->IsEnd())
Val |= uint64_t(1) << SHIFT_WORD_ENDING_BIT;
if (Root->GetNumEnds() >= 256)
Val |= uint64_t(1) << SHIFT_LARGE_ENDING_BIT;
// Make sure output arrays are big enough
if (Root->GetAddr() > NodeData.size())
{
NodeData.resize(Root->GetAddr()+1, 4000000000);
NodeEnds.resize(Root->GetAddr()+1, 4000000000);
}
// Save the node data and number of word endings for the node
NodeData[Root->GetAddr()] = Val;
NodeEnds[Root->GetAddr()] = Root->GetNumEnds();
// Now do the children
for(Itc = Root->ChildBegin(); Itc != Root->ChildEnd(); ++Itc)
{
CreateArrays(Itc->second, StrSet, ChildAddrs, NodeData, NodeEnds);
}
}
/**********************************************************************************
* Output the data as a binary file.
*/
static int OutputBinary(ostream *Out, const string & ChkFile, const string & CharSet, StringIntSet_t & StrSet, //NodeSPtr & Root,
StringOfInts & ChildAddrs, Uint64Vect & NodeData, UintVect & NodeEnds, StringIntVect_t & Ranks)
{
int OutputSize;
unsigned int FewEndStart = 2000000000;
unsigned int i;
unsigned int Index;
unsigned short u;
TrieCheck h;
for(Index = 0; Index < NodeData.size(); ++Index)
{
uint64_t v = NodeData[Index];
if ((FewEndStart >= 2000000000) && !(v & (uint64_t(1) << SHIFT_LARGE_ENDING_BIT)))
{
FewEndStart = Index;
break;
}
}
// Header words
unsigned int NumWordEnd;
const unsigned int MAGIC = 'z' + ('x'<< 8) + ('c' << 16) + ('v' << 24);
Out->write((char *)&MAGIC, sizeof MAGIC); // Write magic
h(&MAGIC, sizeof MAGIC);
OutputSize = sizeof MAGIC;
i = NodeData.size();
Out->write((char *)&i, sizeof i); // Write number of nodes
h(&i, sizeof i);
OutputSize += sizeof i;
i = ChildAddrs.size();
if (NodeData.size() > numeric_limits<unsigned int>::max())
i |= 1<<31;
Out->write((char *)&i, sizeof i); // Write number of child location entries & size of each entry
h(&i, sizeof i);
OutputSize += sizeof i;
i = Ranks.size();
Out->write((char *)&i, sizeof i); // Write number of ranks
h(&i, sizeof i);
OutputSize += sizeof i;
NumWordEnd = (NodeData.size() + 7) / 8;
Out->write((char *)&NumWordEnd, sizeof NumWordEnd); // Write number of word endings
h(&NumWordEnd, sizeof NumWordEnd);
OutputSize += sizeof NumWordEnd;
i = StrSet.size();
Out->write((char *)&i, sizeof i); // Write size of of child bitmap data
h(&i, sizeof i);
OutputSize += sizeof i;
unsigned int BytePerEntry = (CharSet.length() + 7) / 8;
Out->write((char *)&BytePerEntry, sizeof BytePerEntry); // Write size of each child bitmap
h(&BytePerEntry, sizeof BytePerEntry);
OutputSize += sizeof BytePerEntry;
Out->write((char *)&FewEndStart, sizeof FewEndStart); // Write number of large end counts
h(&FewEndStart, sizeof FewEndStart);
OutputSize += sizeof FewEndStart;
i = NodeData.size();
Out->write((char *)&i, sizeof i); // Write number of end counts
h(&i, sizeof i);
OutputSize += sizeof i;
i = CharSet.length();
Out->write((char *)&i, sizeof i); // Write size of character set
h(&i, sizeof i);
OutputSize += sizeof i;
// Output array of node data
unsigned char *WordEnds = new unsigned char[NumWordEnd];
unsigned char v = 0;
unsigned int z = 0;
int y = 0;
for(Index = 0; Index < NodeData.size(); ++Index)
{
i = NodeData[Index];
Out->write((char *)&i, sizeof i);
h(&i, sizeof i);