forked from zelenski/stanford-cpp-library
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathspl.cpp
9329 lines (8115 loc) · 265 KB
/
spl.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
// Stanford C++ library (extracted)
// @author Marty Stepp
// @version Sat Oct 12 18:21:52 PDT 2019
//
// This library has been merged into a single .h and .cpp file by an automatic script
// to make it easier to include and use with the CodeStepByStep tool.
// DO NOT EDIT THIS FILE DIRECTLY!
// If you want to make changes or additions to the Stanford C++ library,
// make them to the library's original source as separate .cpp / .h files,
// then re-run the script to extract the library into these single large merged files.
#include "spl.h"
/////////////////////// BEGIN code extracted from StanfordCPPLib/private/init.cpp ///////////////////////
/*
* File: init.cpp
* --------------
*
* TODO
*
* @author Marty Stepp
* @version 2018/11/22
* - added headless mode support
* @version 2018/08/28
* - refactor to use stanfordcpplib namespace
* @version 2018/08/27
* - initial version
*/
#define INTERNAL_INCLUDE 1
#define INTERNAL_INCLUDE 1
#define INTERNAL_INCLUDE 1
#define INTERNAL_INCLUDE 1
#define INTERNAL_INCLUDE 1
#define INTERNAL_INCLUDE 1
#undef INTERNAL_INCLUDE
#ifdef _WIN32
# include <direct.h> // for chdir
#else // _WIN32
# include <unistd.h> // for chdir
#endif // _WIN32
namespace stanfordcpplib {
namespace qtgui {
extern void initializeQtGraphicalConsole();
extern void shutdownConsole();
}
static void parseArgsQt(int argc, char** argv);
STATIC_VARIABLE_DECLARE(bool, isExitEnabled, true)
bool exitEnabled() {
return STATIC_VARIABLE(isExitEnabled);
}
// called automatically by real main() function;
// call to this is inserted by library init.h
// to be run in Qt GUI main thread
void initializeLibrary(int argc, char** argv) {
// ensure that library is initialized only once
static bool _initialized = false;
if (_initialized) {
return;
}
_initialized = true;
#ifndef SPL_HEADLESS_MODE
GThread::setMainThread();
#endif // SPL_HEADLESS_MODE
parseArgsQt(argc, argv);
#ifndef SPL_HEADLESS_MODE
// initialize the main Qt graphics subsystem
QtGui::instance()->setArgs(argc, argv);
QtGui::instance()->initializeQt();
// initialize Qt graphical console (if student #included it)
initializeQtGraphicalConsole();
#endif // SPL_HEADLESS_MODE
}
void initializeLibraryStudentThread() {
#if defined(SPL_CONSOLE_PRINT_EXCEPTIONS)
setConsolePrintExceptions(true, /* force */ true);
#endif
}
// this should be roughly the same code as platform.cpp's parseArgs function
static void parseArgsQt(int argc, char** argv) {
if (argc <= 0) {
return;
}
std::string arg0 = argv[0];
exceptions::setProgramNameForStackTrace(argv[0]);
// programName() = getRoot(getTail(arg0));
#ifndef _WIN32
// on Mac only, may need to change folder because of app's nested dir structure
size_t ax = arg0.find(".app/Contents/");
if (ax != std::string::npos) {
while (ax > 0 && arg0[ax] != '/') {
ax--;
}
if (ax > 0) {
std::string cwd = arg0.substr(0, ax);
chdir(cwd.c_str());
}
}
#endif // _WIN32
char* noConsoleFlag = getenv("NOCONSOLE");
if (noConsoleFlag && startsWith(std::string(noConsoleFlag), "t")) {
return;
}
}
// called automatically by real main() function;
// call to this is inserted by library init.h
// to be run in Qt main thread
#ifdef SPL_HEADLESS_MODE
void runMainInThread(int (* mainFunc)(void)) {
mainFunc();
}
void runMainInThread(std::function<int()> mainFunc) {
mainFunc();
}
void runMainInThreadVoid(void (* mainFuncVoid)(void)) {
mainFuncVoid();
}
void runMainInThreadVoid(std::function<void()> mainFuncVoid) {
mainFuncVoid();
}
#else // SPL_HEADLESS_MODE
void runMainInThread(int (* mainFunc)(void)) {
QtGui::instance()->startBackgroundEventLoop(mainFunc);
}
void runMainInThread(std::function<int()> mainFunc) {
QtGui::instance()->startBackgroundEventLoop(mainFunc);
}
void runMainInThreadVoid(void (* mainFuncVoid)(void)) {
QtGui::instance()->startBackgroundEventLoopVoid(mainFuncVoid);
}
void runMainInThreadVoid(std::function<void()> mainFuncVoid) {
QtGui::instance()->startBackgroundEventLoopVoid(mainFuncVoid);
}
#endif // SPL_HEADLESS_MODE
void setExitEnabled(bool enabled) {
STATIC_VARIABLE(isExitEnabled) = enabled;
// TODO: notify GConsoleWindow?
}
// shut down the Qt graphical console window;
// to be run in Qt main thread
void shutdownLibrary() {
#ifdef SPL_HEADLESS_MODE
// empty
#else
shutdownConsole();
#endif // SPL_HEADLESS_MODE
}
void staticInitializeLibrary() {
// empty
}
} // namespace stanfordcpplib
namespace std {
void __stanfordcpplib__exitLibrary(int status) {
if (stanfordcpplib::exitEnabled()) {
// call std::exit (has been renamed)
#ifdef exit
#undef exit
std::exit(status);
#define exit __stanfordcpplib__exitLibrary
#endif // exit
} else {
// not allowed to call exit(); produce error message
std::ostringstream out;
out << "Program tried to call exit(" << status << ") to quit. " << std::endl;
out << "*** This function has been disabled; main should end through " << std::endl;
out << "*** normal program control flow." << std::endl;
error(out.str());
}
}
} // namespace std
/////////////////////// END code extracted from StanfordCPPLib/private/init.cpp ///////////////////////
/////////////////////// BEGIN code extracted from StanfordCPPLib/collections/collections.cpp ///////////////////////
/*
* File: collections.cpp
* ---------------------
* This file implements the collections.h interface.
*
* @version 2019/04/11
* - added functions to read/write quoted char values
* @version 2018/10/20
* - initial version
*/
#define INTERNAL_INCLUDE 1
#define INTERNAL_INCLUDE 1
#undef INTERNAL_INCLUDE
#include <iomanip>
#include <iostream>
/*
* Implementation notes: readQuotedString and writeQuotedString
* ------------------------------------------------------------
* Most of the work in these functions has to do with escape sequences.
*/
STATIC_CONST_VARIABLE_DECLARE(std::string, STRING_DELIMITERS, ",:)}]\n")
bool stringNeedsQuoting(const std::string& str) {
int n = str.length();
for (int i = 0; i < n; i++) {
char ch = str[i];
if (isspace(ch)) return false;
if (STATIC_VARIABLE(STRING_DELIMITERS).find(ch) != std::string::npos) return true;
}
return false;
}
bool readQuotedChar(std::istream& is, char& ch, bool throwOnError) {
// skip whitespace
char temp;
while (is.get(temp) && isspace(temp)) {
// empty
}
if (is.fail()) {
return true;
}
// now we are either at a character, like X, or at the start of a quoted
// character such as 'X' or '\n'
if (temp == '\'' || temp == '"') {
// quoted character; defer to string-reading code
is.unget();
std::string s;
bool result = readQuotedString(is, s, throwOnError);
if (result && !s.empty()) {
ch = s[0];
}
return result;
} else {
// unquoted character; read it ourselves
// special case: \ (e.g. \n, \t)
if (temp == '\\') {
// TODO
char temp2;
if (is.get(temp2)) {
switch (temp2) {
case 'a': ch = '\a'; break;
case 'b': ch = '\b'; break;
case 'f': ch = '\f'; break;
case 'n': ch = '\n'; break;
case 'r': ch = '\r'; break;
case 't': ch = '\t'; break;
case 'v': ch = '\v'; break;
case '0': ch = '\0'; break;
case '\\': ch = '\\'; break;
case '\'': ch = '\''; break;
case '"': ch = '"'; break;
default: ch = '\0'; break;
}
}
} else {
ch = temp;
}
return true;
}
}
bool readQuotedString(std::istream& is, std::string& str, bool throwOnError) {
str = "";
char ch;
while (is.get(ch) && isspace(ch)) {
/* Empty */
}
if (is.fail()) {
return true; // empty string?
}
if (ch == '\'' || ch == '"') {
char delim = ch;
while (is.get(ch) && ch != delim) {
if (is.fail()) {
if (throwOnError) {
error("Unterminated string");
}
return false;
}
if (ch == '\\') {
if (!is.get(ch)) {
if (throwOnError) {
error("Unterminated string");
}
is.setstate(std::ios_base::failbit);
return false;
}
if (isdigit(ch) || ch == 'x') {
int maxDigits = 3;
int base = 8;
if (ch == 'x') {
base = 16;
maxDigits = 2;
}
int result = 0;
int digit = 0;
for (int i = 0; i < maxDigits && ch != delim; i++) {
if (isdigit(ch)) {
digit = ch - '0';
} else if (base == 16 && isxdigit(ch)) {
digit = toupper(ch) - 'A' + 10;
} else {
break;
}
result = base * result + digit;
if (!is.get(ch)) {
if (throwOnError) {
error("Unterminated string");
}
is.setstate(std::ios_base::failbit);
return false;
}
}
ch = char(result);
is.unget();
} else {
switch (ch) {
case 'a': ch = '\a'; break;
case 'b': ch = '\b'; break;
case 'f': ch = '\f'; break;
case 'n': ch = '\n'; break;
case 'r': ch = '\r'; break;
case 't': ch = '\t'; break;
case 'v': ch = '\v'; break;
case '"': ch = '"'; break;
case '\'': ch = '\''; break;
case '\\': ch = '\\'; break;
}
}
}
str += ch;
}
} else {
str += ch;
int endTrim = 0;
while (is.get(ch) && STATIC_VARIABLE(STRING_DELIMITERS).find(ch) == std::string::npos) {
str += ch;
if (!isspace(ch)) {
endTrim = str.length();
}
}
if (is) is.unget();
str = str.substr(0, endTrim);
}
return true; // read successfully
}
std::ostream& writeQuotedChar(std::ostream& os, char ch, bool forceQuotes) {
if (forceQuotes) {
os << '\'';
}
switch (ch) {
case '\a': os << "\\a"; break;
case '\b': os << "\\b"; break;
case '\f': os << "\\f"; break;
case '\n': os << "\\n"; break;
case '\r': os << "\\r"; break;
case '\t': os << "\\t"; break;
case '\v': os << "\\v"; break;
case '\\': os << "\\\\"; break;
default:
if (isprint(ch) && ch != '\'') {
os << ch;
} else {
std::ostringstream oss;
oss << std::oct << std::setw(3) << std::setfill('0') << (int(ch) & 0xFF);
os << "\\" << oss.str();
}
}
if (forceQuotes) {
os << '\'';
}
return os;
}
std::ostream& writeQuotedString(std::ostream& os, const std::string& str, bool forceQuotes) {
if (!forceQuotes && stringNeedsQuoting(str)) {
forceQuotes = true;
}
if (forceQuotes) {
os << '"';
}
int len = str.length();
for (int i = 0; i < len; i++) {
char ch = str.at(i);
switch (ch) {
case '\a': os << "\\a"; break;
case '\b': os << "\\b"; break;
case '\f': os << "\\f"; break;
case '\n': os << "\\n"; break;
case '\r': os << "\\r"; break;
case '\t': os << "\\t"; break;
case '\v': os << "\\v"; break;
case '\\': os << "\\\\"; break;
default:
if (isprint(ch) && ch != '"') {
os << ch;
} else {
std::ostringstream oss;
oss << std::oct << std::setw(3) << std::setfill('0') << (int(ch) & 0xFF);
os << "\\" << oss.str();
}
}
}
if (forceQuotes) {
os << '"';
}
return os;
}
/////////////////////// END code extracted from StanfordCPPLib/collections/collections.cpp ///////////////////////
/////////////////////// BEGIN code extracted from StanfordCPPLib/collections/basicgraph.cpp ///////////////////////
/*
* File: basicgraph.cpp
* --------------------
* This file implements any non-template functionality used by
* the BasicGraph class.
*
* @version 2016/12/01
*/
#define INTERNAL_INCLUDE 1
#undef INTERNAL_INCLUDE
int hashCode(const BasicGraph& graph) {
int code = hashSeed();
for (Vertex* v : graph) {
code = hashMultiplier() * code + hashCode(v->name);
}
for (Edge* e : graph.getEdgeSet()) {
code = hashMultiplier() * code + hashCode(e->start->name);
code = hashMultiplier() * code + hashCode(e->finish->name);
}
return (code & hashMask());
}
/////////////////////// END code extracted from StanfordCPPLib/collections/basicgraph.cpp ///////////////////////
/////////////////////// BEGIN code extracted from StanfordCPPLib/collections/dawglexicon.cpp ///////////////////////
/*
* File: dawglexicon.cpp
* ---------------------
* A lexicon is a word list. This lexicon is backed by two separate data
* structures for storing the words in the list:
*
* 1) a DAWG (directed acyclic word graph)
* 2) a Set<string> of other words.
*
* Typically the DAWG is used for a large list read from a file in binary
* format. The STL set is for words added piecemeal at runtime.
*
* The DAWG idea comes from an article by Appel & Jacobson, CACM May 1988.
* This lexicon implementation only has the code to load/search the DAWG.
* The DAWG builder code is quite a bit more intricate, see Julie Zelenski
* if you need it.
*
* @version 2018/03/10
* - added method front
* @version 2017/11/14
* - added iterator version checking support
* @version 2016/08/10
* - added constructor support for std initializer_list usage, such as {"a", "b", "c"}
* @version 2016/08/04
* - added operator >>
* @version 2015/07/05
* - using global hashing functions rather than global variables
* @version 2014/11/13
* - added comparison operators <, >=, etc.
* - added hashCode function
* @version 2014/10/10
* - removed 'using namespace' statement
* - added equals method, ==, != operators
* - fixed inclusion of foreach macro to avoid errors
* - BUGFIX: operator << now shows "" marks around words to match Lexicon
*/
#define INTERNAL_INCLUDE 1
#include <algorithm>
#include <cstdlib>
#include <cstring>
#include <fstream>
#include <iostream>
#include <sstream>
#include <stdint.h>
#include <string>
#define INTERNAL_INCLUDE 1
#define INTERNAL_INCLUDE 1
#define INTERNAL_INCLUDE 1
#define INTERNAL_INCLUDE 1
#undef INTERNAL_INCLUDE
static uint32_t my_ntohl(uint32_t arg);
/*
* The DAWG is stored as an array of edges. Each edge is represented by
* one 32-bit struct. The 5 "letter" bits indicate the character on this
* transition (expressed as integer from 1 to 26), the "accept" bit indicates
* if you accept after appending that char (current path forms word), and the
* "lastEdge" bit marks this as the last edge in a sequence of childeren.
* The bulk of the bits (24) are used for the index within the edge array for
* the children of this node. The children are laid out contiguously in
* alphabetical order. Since we read edges as binary bits from a file in
* a big-endian format, we have to swap the struct order for little-endian
* machines.
*/
DawgLexicon::DawgLexicon() :
_edges(nullptr),
_start(nullptr),
_edgeCount(0),
_dawgWordsCount(0) {
// empty
}
DawgLexicon::DawgLexicon(std::istream& input) :
_edges(nullptr),
_start(nullptr),
_edgeCount(0),
_dawgWordsCount(0) {
addWordsFromFile(input);
}
DawgLexicon::DawgLexicon(const std::string& filename) :
_edges(nullptr),
_start(nullptr),
_edgeCount(0),
_dawgWordsCount(0) {
addWordsFromFile(filename);
}
DawgLexicon::DawgLexicon(const DawgLexicon& src) :
_edges(nullptr),
_start(nullptr),
_edgeCount(0),
_dawgWordsCount(0) {
deepCopy(src);
}
DawgLexicon::DawgLexicon(std::initializer_list<std::string> list) :
_edges(nullptr),
_start(nullptr),
_edgeCount(0),
_dawgWordsCount(0) {
addAll(list);
}
DawgLexicon::~DawgLexicon() {
if (_edges) {
delete[] _edges;
}
}
void DawgLexicon::add(const std::string& word) {
std::string copy = word;
toLowerCaseInPlace(copy);
if (!contains(copy)) {
_otherWords.add(copy);
}
}
DawgLexicon& DawgLexicon::addAll(const DawgLexicon& lex) {
for (const std::string& word : lex) {
add(word);
}
return *this;
}
DawgLexicon& DawgLexicon::addAll(std::initializer_list<std::string> list) {
for (const std::string& word : list) {
add(word);
}
return *this;
}
/*
* Check for DAWG in first 4 to identify as special binary format,
* otherwise assume ASCII, one word per line
*/
void DawgLexicon::addWordsFromFile(std::istream& input) {
char firstFour[4], expected[] = "DAWG";
if (input.fail()) {
error("DawgLexicon::addWordsFromFile: Couldn't read input");
}
input.read(firstFour, 4);
if (strncmp(firstFour, expected, 4) == 0) {
if (_otherWords.size() != 0) {
error("DawgLexicon::addWordsFromFile: Binary files require an empty lexicon");
}
readBinaryFile(input);
} else {
// plain text file
input.seekg(0);
std::string line;
while (getline(input, line)) {
add(line);
}
}
}
/*
* Check for DAWG in first 4 to identify as special binary format,
* otherwise assume ASCII, one word per line
*/
void DawgLexicon::addWordsFromFile(const std::string& filename) {
std::ifstream input(filename.c_str());
if (input.fail()) {
error("DawgLexicon::addWordsFromFile: Couldn't open lexicon file " + filename);
}
addWordsFromFile(input);
input.close();
}
void DawgLexicon::clear() {
if (_edges) {
delete[] _edges;
}
_edges = _start = nullptr;
_edgeCount = _dawgWordsCount = 0;
_otherWords.clear();
}
bool DawgLexicon::contains(const std::string& word) const {
std::string copy = word;
toLowerCaseInPlace(copy);
Edge* lastEdge = traceToLastEdge(copy);
if (lastEdge && lastEdge->accept) {
return true;
}
return _otherWords.contains(copy);
}
bool DawgLexicon::containsAll(const DawgLexicon& lex2) const {
for (const std::string& word : lex2) {
if (!contains(word)) {
return false;
}
}
return true;
}
bool DawgLexicon::containsAll(std::initializer_list<std::string> list) const {
for (const std::string& word : list) {
if (!contains(word)) {
return false;
}
}
return true;
}
bool DawgLexicon::containsPrefix(const std::string& prefix) const {
if (prefix.empty()) {
return true;
}
std::string copy = prefix;
toLowerCaseInPlace(copy);
if (traceToLastEdge(copy)) {
return true;
}
for (std::string word : _otherWords) {
if (startsWith(word, copy)) {
return true;
}
if (copy < word) {
return false;
}
}
return false;
}
bool DawgLexicon::equals(const DawgLexicon& lex2) const {
return stanfordcpplib::collections::equals(*this, lex2);
}
std::string DawgLexicon::front() const {
if (isEmpty()) {
error("DawgLexicon::front: lexicon is empty");
}
auto it = begin();
return *it;
}
void DawgLexicon::insert(const std::string& word) {
add(word);
}
bool DawgLexicon::isEmpty() const {
return size() == 0;
}
bool DawgLexicon::isSubsetOf(const DawgLexicon& lex2) const {
auto it = begin();
auto end = this->end();
while (it != end) {
if (!lex2.contains(*it)) {
return false;
}
++it;
}
return true;
}
bool DawgLexicon::isSubsetOf(std::initializer_list<std::string> list) const {
DawgLexicon lex2(list);
return isSubsetOf(lex2);
}
bool DawgLexicon::isSupersetOf(const DawgLexicon& lex2) const {
return containsAll(lex2);
}
bool DawgLexicon::isSupersetOf(std::initializer_list<std::string> list) const {
return containsAll(list);
}
void DawgLexicon::mapAll(void (*fn)(std::string)) const {
for (std::string word : *this) {
fn(word);
}
}
void DawgLexicon::mapAll(void (*fn)(const std::string &)) const {
for (std::string word : *this) {
fn(word);
}
}
int DawgLexicon::size() const {
return _dawgWordsCount + _otherWords.size();
}
std::string DawgLexicon::toString() const {
std::ostringstream out;
out << *this;
return out.str();
}
/*
* Operators
*/
bool DawgLexicon::operator ==(const DawgLexicon& lex2) const {
return equals(lex2);
}
bool DawgLexicon::operator !=(const DawgLexicon& lex2) const {
return !equals(lex2);
}
bool DawgLexicon::operator <(const DawgLexicon& lex2) const {
return stanfordcpplib::collections::compare(*this, lex2) < 0;
}
bool DawgLexicon::operator <=(const DawgLexicon& lex2) const {
return stanfordcpplib::collections::compare(*this, lex2) <= 0;
}
bool DawgLexicon::operator >(const DawgLexicon& lex2) const {
return stanfordcpplib::collections::compare(*this, lex2) > 0;
}
bool DawgLexicon::operator >=(const DawgLexicon& lex2) const {
return stanfordcpplib::collections::compare(*this, lex2) >= 0;
}
DawgLexicon DawgLexicon::operator +(const DawgLexicon& lex2) const {
DawgLexicon lex = *this;
lex.addAll(lex2);
return lex;
}
DawgLexicon DawgLexicon::operator +(std::initializer_list<std::string> list) const {
DawgLexicon lex = *this;
lex.addAll(list);
return lex;
}
DawgLexicon DawgLexicon::operator +(const std::string& word) const {
DawgLexicon lex = *this;
lex.add(word);
return lex;
}
DawgLexicon& DawgLexicon::operator +=(const DawgLexicon& lex2) {
return addAll(lex2);
}
DawgLexicon& DawgLexicon::operator +=(std::initializer_list<std::string> list) {
return addAll(list);
}
DawgLexicon& DawgLexicon::operator +=(const std::string& word) {
add(word);
return *this;
}
/*
* Private methods and helpers
*/
DawgLexicon& DawgLexicon::operator ,(const std::string& word) {
add(word);
return *this;
}
int DawgLexicon::countDawgWords(Edge* ep) const {
int count = 0;
while (true) {
if (ep->accept) count++;
if (ep->children != 0) {
count += countDawgWords(&_edges[ep->children]);
}
if (ep->lastEdge) break;
ep++;
}
return count;
}
void DawgLexicon::deepCopy(const DawgLexicon& src) {
if (!src._edges) {
_edges = nullptr;
_start = nullptr;
} else {
_edgeCount = src._edgeCount;
_edges = new Edge[src._edgeCount];
memcpy(_edges, src._edges, sizeof(Edge)*src._edgeCount);
_start = _edges + (src._start - src._edges);
}
_dawgWordsCount = src._dawgWordsCount;
_otherWords = src._otherWords;
}
/*
* Implementation notes: findEdgeForChar
* -------------------------------------
* Iterate over sequence of children to find one that
* matches the given char. Returns nullptr if we get to
* last child without finding a match (thus no such
* child edge exists).
*/
DawgLexicon::Edge* DawgLexicon::findEdgeForChar(Edge* children, char ch) const {
Edge* curEdge = children;
while (true) {
if (curEdge->letter == charToOrd(ch)) {
return curEdge;
}
if (curEdge->lastEdge) {
return nullptr;
}
curEdge++;
}
}
/*
* Implementation notes: readBinaryFile
* ------------------------------------
* The binary lexicon file format must follow this pattern:
* DAWG:<startnode index>:<num bytes>:<num bytes block of edge data>
*/
void DawgLexicon::readBinaryFile(std::istream& input) {
input.clear();
input.seekg(0, std::ios::beg);
long startIndex, numBytes;
char firstFour[4], expected[] = "DAWG";
if (input.fail()) {
error("DawgLexicon::addWordsFromFile: Couldn't read input");
}
input.read(firstFour, 4);
input.get();
input >> startIndex;
input.get();
input >> numBytes;
input.get();
if (input.fail() || strncmp(firstFour, expected, 4) != 0
|| startIndex < 0 || numBytes < 0) {
error("DawgLexicon::addWordsFromFile: Improperly formed lexicon file");
}
_edgeCount = numBytes / sizeof(Edge);
_edges = new Edge[_edgeCount];
_start = &_edges[startIndex];
input.read((char*) _edges, numBytes);
if (input.fail() && !input.eof()) {
error("DawgLexicon::addWordsFromFile: Improperly formed lexicon file");
}
#if defined(BYTE_ORDER) && BYTE_ORDER == LITTLE_ENDIAN
// uint32_t* cur = (uint32_t*) edges;
uint32_t* cur = reinterpret_cast<uint32_t*>(_edges);
for (int i = 0; i < _edgeCount; i++, cur++) {
*cur = my_ntohl(*cur);
}
#endif
_dawgWordsCount = countDawgWords(_start);
}
/*
* Implementation notes: readBinaryFile
* ------------------------------------
* The binary lexicon file format must follow this pattern:
* DAWG:<startnode index>:<num bytes>:<num bytes block of edge data>
*/
void DawgLexicon::readBinaryFile(const std::string& filename) {
#ifdef _foreachpatch_h
std::ifstream input(filename.c_str(), __IOS_IN__ | __IOS_BINARY__);
#else
std::ifstream input(filename.c_str(), std::ios::in | std::ios::binary);
#endif // _foreachpatch_h
if (input.fail()) {
error("DawgLexicon::addWordsFromFile: Couldn't open lexicon file " + filename);
}
readBinaryFile(input);
input.close();
}
/*
* Implementation notes: traceToLastEdge
* -------------------------------------
* Given a string, trace out path through the DAWG edge-by-edge.
* If a path exists, return last edge; otherwise return nullptr.
*/
DawgLexicon::Edge* DawgLexicon::traceToLastEdge(const std::string& s) const {
if (!_start) {
return nullptr;
}
Edge* curEdge = findEdgeForChar(_start, s[0]);
int len = (int) s.length();
for (int i = 1; i < len; i++) {
if (!curEdge || !curEdge->children) {
return nullptr;
}
curEdge = findEdgeForChar(&_edges[curEdge->children], s[i]);
}
return curEdge;
}
DawgLexicon& DawgLexicon::operator =(const DawgLexicon& src) {
if (this != &src) {
if (_edges) {
delete[] _edges;
}
deepCopy(src);
}
return *this;
}
void DawgLexicon::iterator::advanceToNextWordInSet() {
if (setIterator == setEnd) {
currentSetWord = "";
} else {
currentSetWord = *setIterator;
++setIterator;
}
}
void DawgLexicon::iterator::advanceToNextEdge() {
Edge *ep = edgePtr;