-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfunctions.cpp
More file actions
1389 lines (1152 loc) · 41.4 KB
/
Copy pathfunctions.cpp
File metadata and controls
1389 lines (1152 loc) · 41.4 KB
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 "functions.h"
#include "graph.h"
using namespace std;
// ==================== Implement Post class functions ====================
// Constructor implementation
Post::Post(vector<string> topics, string content) {
post_Topics = topics;
post_Content = content;
}
// Method implementations
vector<string> Post::getTopics() {
return post_Topics;
}
string Post::getContent() {
return post_Content;
}
// Global BPE Dictionary
vector<DictionaryEntry> BPE_DICTIONARY;
// ==================== BPE Helper Functions ====================
vector<unsigned char> stringToBytes(const string &str)
{
return vector<unsigned char>(str.begin(), str.end());
}
string bytesToString(const vector<unsigned char> &bytes)
{
return string(bytes.begin(), bytes.end());
}
vector<unsigned char> readFileToBytes(const string &filename)
{
ifstream file(filename, ios::binary);
if (!file.is_open())
{
cerr << "Error: Could not open input file " << filename << endl;
return {};
}
return vector<unsigned char>((istreambuf_iterator<char>(file)), istreambuf_iterator<char>());
}
bool writeCompressedFile(const string &filename, const vector<unsigned char> &data, const vector<DictionaryEntry> &dictionary)
{
ofstream outfile(filename, ios::binary);
if (!outfile.is_open())
{
cerr << "Error: Could not open output file " << filename << endl;
return false;
}
// Write the number of dictionary entries
size_t dict_size = dictionary.size();
outfile.write((const char *)&dict_size, sizeof(dict_size));
// Write the dictionary entries
for (const auto &entry : dictionary)
{
outfile.write((const char *)&entry.first, sizeof(entry.first));
outfile.write((const char *)&entry.second, sizeof(entry.second));
}
// Write compressed data
outfile.write((const char *)data.data(), data.size());
outfile.close();
return true;
}
bool oneIterationBPE(vector<unsigned char> &data, unsigned char &nextFreeByte)
{
if (BPE_DICTIONARY.size() >= 128)
{
return false;
}
if (data.size() < 2 || nextFreeByte > 255)
{
return false;
}
// PairCount[i][j] stores the count of the pair (char)i followed by (char)j.
int pairCount[256][256] = {0};
int maxCount = 0;
unsigned char max_i = 0, max_j = 0;
// 1. Count Frequencies
for (size_t k = 0; k < data.size() - 1; ++k)
{
pairCount[data[k]][data[k + 1]]++;
}
// 2. Find Max Pair
for (int i = 0; i < 256; ++i)
{
for (int j = 0; j < 256; ++j)
{
// A pair must appear at least twice to be a "compression" benefit (maxCount > 1).
if (pairCount[i][j] > maxCount)
{
maxCount = pairCount[i][j];
max_i = (unsigned char)i;
max_j = (unsigned char)j;
}
}
}
if (maxCount < 2)
{
return false;
}
// 3. Perform Replacement
BPE_DICTIONARY.push_back({max_i, max_j});
unsigned char replacementByte = nextFreeByte;
vector<unsigned char> new_data;
for (size_t k = 0; k < data.size(); ++k)
{
if (k + 1 < data.size() && data[k] == max_i && data[k + 1] == max_j)
{
new_data.push_back(replacementByte); // Append single replacement byte
k++; // Skip the next character
}
else
{
new_data.push_back(data[k]); // Append original character
}
}
data = new_data;
nextFreeByte++;
return true;
}
// ==================== XML Processing Functions ====================
string verify(const string &xml) {
stack<string> tagStack;
string result = "";
int i = 0;
int lineNum = 1;
int numberOfErrors = 0;
while (i < xml.length()) {
if (xml[i] == '\n') {
lineNum++;
}
if(xml[i] == '>') {
// Check if this '>' has a matching '<' before it
bool hasMatchingOpen = false;
int searchPos = i - 1;
// Search backwards for '<'
while (searchPos >= 0 && xml[searchPos] != '<') {
if (xml[searchPos] == '<') {
hasMatchingOpen = true;
break;
}
if (xml[searchPos] == '>') {
// Found another '>' first, so this '>' is orphaned
break;
}
searchPos--;
}
if (!hasMatchingOpen) {
result += "Error at line " + to_string(lineNum) + ": Missing '<' for '>'\n";
numberOfErrors++;
}
i++;
} else if (xml[i] == '<') {
int nextOpenTag = xml.find('<', i + 1);
int tagEnd = xml.find_first_of('>', i);
if ((nextOpenTag != string::npos && nextOpenTag < tagEnd) || tagEnd == string::npos) {
result += "Error at line " + to_string(lineNum) + ": Unclosed tag bracket\n";
numberOfErrors++;
i++; // Move forward to avoid infinite loop
continue;
}
string tagContent = xml.substr(i + 1, tagEnd - i - 1);
if (tagContent[0] == '?') {
// XML declaration must end with '?'
if (tagContent.back() != '?') {
result += "Error at line " + to_string(lineNum) + ": Malformed XML declaration\n";
numberOfErrors++;
}
i = tagEnd + 1;
continue;
}
if (tagContent[0] == '!' || tagContent.back() == '/') {
// skip comments and self-closing tags
i = tagEnd + 1;
continue;
}
if (tagContent[0] == '/') {
// closing tag
string closingTag = tagContent.substr(1);
int spaceIndex = closingTag.find(' ');
if (spaceIndex != string::npos) {
closingTag = closingTag.substr(0, spaceIndex);
}
if (tagStack.empty()) {
result += "Error at line " + to_string(lineNum) + ": No matching opening tag for </" + closingTag + ">\n";
numberOfErrors++;
} else {
string expectedTag = tagStack.top();
if (expectedTag != closingTag) {
result += "Error at line " + to_string(lineNum) + ": Mismatched tags\n";
numberOfErrors++;
} else {
tagStack.pop();
}
}
} else {
// opening tag
string openTag = tagContent;
int spaceIndex = openTag.find(' ');
if (spaceIndex != string::npos) {
openTag = openTag.substr(0, spaceIndex);
}
tagStack.push(openTag);
}
i = tagEnd + 1;
} else {
i++;
}
}
// check for unclosed tags
if (!tagStack.empty()) {
result += "Error: Unclosed tags found:\n";
while (!tagStack.empty()) {
result += " - <" + tagStack.top() + ">\n";
tagStack.pop();
numberOfErrors++;
}
}
// final output to console
if (numberOfErrors == 0) {
result = "Valid";
cout << result << endl;
} else {
result = "Invalid\nTotal Errors: " + to_string(numberOfErrors) + "\n" + result;
cout << result << endl;
}
return result;
}
string fixation(const string &xml) {
cout << "begin fixing\n";
// XML has errors - fix the errors
string fixedXml = xml; // work on a copy
stack<string> tagStack;
stack<int> tagPositions; // track positions for inserting closing tags
int i = 0;
int lineNum = 1;
while (i < fixedXml.length()) {
if (fixedXml[i] == '\n') {
lineNum++;
}
if (fixedXml[i] == '<') {
int nextOpenTag = fixedXml.find('<', i + 1);
int tagEnd = fixedXml.find_first_of('>', i);
int previousCloseBracket = fixedXml.rfind('>', i - 1);
// fix 1: unclosed tag bracket
// fix 1: unclosed tag bracket
if ((nextOpenTag != string::npos && nextOpenTag < tagEnd) || tagEnd == string::npos) {
cout << "Missing close bracket\n";
if (tagEnd == string::npos) {
// no '>' found at all - find where tag name/attributes end
// look for whitespace or newline after the tag name
cout << "Add missing close bracket at file end\n";
int insertPos = i + 1;
while (insertPos < fixedXml.length() &&
fixedXml[insertPos] != ' ' &&
fixedXml[insertPos] != '\n' &&
fixedXml[insertPos] != '\t' &&
fixedXml[insertPos] != '<') {
insertPos++;
}
fixedXml.insert(insertPos, ">");
tagEnd = insertPos;
cout << "Finished adding missing close bracket at file end\n";
} else {
// there's a '<' before the '>'
// insert '>' right after tag name/attributes, not at nextOpenTag
cout << "Add missing close bracket at line: " << lineNum << "\n";
int insertPos = i + 1;
while (insertPos < nextOpenTag &&
fixedXml[insertPos] != '\n' &&
fixedXml[insertPos] != '<') {
insertPos++;
}
// back up to last non-whitespace character
while (insertPos > i + 1 &&
(fixedXml[insertPos - 1] == ' ' ||
fixedXml[insertPos - 1] == '\t')) {
insertPos--;
}
fixedXml.insert(insertPos, ">");
tagEnd = insertPos;
cout << "Finished adding missing close bracket at line: " << lineNum << "\n";
}
}
string tagContent = fixedXml.substr(i + 1, tagEnd - i - 1);
// fix 2: malformed XML declaration
if (tagContent[0] == '?') {
if (tagContent.back() != '?') {
cout << "Malformed XML declaration found\n";
fixedXml.insert(tagEnd, "?");
tagEnd++;
cout << "Fixed Malformed XML declaration\n";
}
i = tagEnd + 1;
continue;
}
// skip comments and self-closing tags
if (tagContent[0] == '!' || tagContent.back() == '/') {
cout << "skip comments and self-closing tags\n";
i = tagEnd + 1;
continue;
}
// handle closing tags
if (tagContent[0] == '/') {
string closingTag = tagContent.substr(1);
int spaceIndex = closingTag.find(' ');
if (spaceIndex != string::npos) {
closingTag = closingTag.substr(0, spaceIndex);
}
// fix 3: extra closing tag without opening tag
if (tagStack.empty()) {
// remove the extra closing tag
fixedXml.erase(i, tagEnd - i + 1);
continue; // don't increment i, as we removed characters
}
string expectedTag = tagStack.top();
// fix 4: mismatched closing tag
if (expectedTag != closingTag) {
// replace wrong closing tag with correct one
string correctClosing = "</" + expectedTag + ">";
fixedXml.replace(i, tagEnd - i + 1, correctClosing);
tagEnd = i + correctClosing.length() - 1;
}
tagStack.pop();
if (!tagPositions.empty()) {
tagPositions.pop();
}
}
// handle opening tags
else {
string openTag = tagContent;
int spaceIndex = openTag.find(' ');
if (spaceIndex != string::npos) {
openTag = openTag.substr(0, spaceIndex);
}
tagStack.push(openTag);
tagPositions.push(tagEnd + 1);
}
i = tagEnd + 1;
} else if (fixedXml[i] == '>') {
// check if this '>' has a matching '<' before it
bool hasMatchingOpen = false;
int searchPos = i - 1;
// search backwards for '<'
while (searchPos >= 0 && fixedXml[searchPos] != '<') {
if (fixedXml[searchPos] == '<') {
hasMatchingOpen = true;
break;
}
if (fixedXml[searchPos] == '>') {
// found another '>' first, so this '>' is orphaned
break;
}
searchPos--;
}
if (!hasMatchingOpen) {
cout << "Missing '<' for '>' at line: " << lineNum << "\n";
bool isClosingTag = false;
// find where tag name starts (backwards from '>')
int tagStart = i - 1;
while (tagStart > 0 &&
fixedXml[tagStart] != '\n' &&
fixedXml[tagStart] != '>' &&
fixedXml[tagStart] != '<' &&
fixedXml[tagStart] != '/') {
tagStart--;
}
// Move forward to the first non-whitespace character after the found position and stop at '/' if encountered
while (tagStart < i &&
(fixedXml[tagStart] == ' ' ||
fixedXml[tagStart] == '\t' ||
fixedXml[tagStart] == '\n' ||
fixedXml[tagStart] == '/')) {
if(fixedXml[tagStart] == '/') {
// if we hit a '/' before finding '<', it means it's a closing tag
// so we should insert '<' before the '/'
isClosingTag = true;
break;
} else {
tagStart++;
}
}
fixedXml.insert(tagStart, "<");
i++; // Adjust position after insertion
// push open tag in stack
if (!isClosingTag) {
// extract tag name
int tagEnd = fixedXml.find_first_of('>', tagStart);
string tagContent = fixedXml.substr(tagStart + 1, tagEnd - tagStart - 1);
int spaceIndex = tagContent.find(' ');
if (spaceIndex != string::npos) {
tagContent = tagContent.substr(0, spaceIndex);
}
tagStack.push(tagContent);
tagPositions.push(tagEnd + 1);
} else {
// it's a closing tag, so pop from stack
if (!tagStack.empty()) {
tagStack.pop();
if (!tagPositions.empty()) {
tagPositions.pop();
}
}
}
cout << "Added missing '<'\n";
}
i++;
} else {
i++;
}
}
// fix 5: add missing closing tags at the end
while (!tagStack.empty()) {
cout << "Adding missing closing tag for <" << tagStack.top() << ">\n";
string missingTag = tagStack.top();
tagStack.pop();
fixedXml += "</" + missingTag + ">";
}
if(fixedXml == xml) {
cout << "No fixes were necessary.\n";
} else {
cout << "Fixing complete.\n";
}
return fixedXml;
}
string trim_copy(const string &s)
{
size_t a = 0, b = s.size();
while (a < b && isspace((unsigned char)s[a])) a++;
while (b > a && isspace((unsigned char)s[b - 1])) b--;
return s.substr(a, b - a);
}
string extract_tag_name(const string &tag)
{
size_t i = 0;
if (tag[i] == '/') i++;
while (i < tag.size() && isspace((unsigned char)tag[i])) i++;
size_t start = i;
while (i < tag.size() && !isspace((unsigned char)tag[i]) && tag[i] != '/')
i++;
return tag.substr(start, i - start);
}
string format(const string &xml)
{
string out;
stack<string> st;
const string indent = " ";
size_t i = 0, n = xml.size();
while (i < n) {
// skip whitespace
if (isspace((unsigned char)xml[i])) {
i++;
continue;
}
// ================= OPENING TAG =================
if (xml[i] == '<' && i + 1 < n && xml[i + 1] != '/') {
// find tag end
size_t j = xml.find('>', i);
string tag = xml.substr(i, j - i + 1);
string tagContent = xml.substr(i + 1, j - i - 1);
string tagName = extract_tag_name(tagContent);
// look ahead for INLINE case
size_t textStart = j + 1;
size_t nextTag = xml.find('<', textStart);
bool inlineCase = false;
string text;
if (nextTag != string::npos &&
xml.compare(nextTag, 2, "</") == 0) {
text = trim_copy(xml.substr(textStart, nextTag - textStart));
size_t closeEnd = xml.find('>', nextTag);
string closingName = extract_tag_name(
xml.substr(nextTag + 2, closeEnd - nextTag - 2));
if (!text.empty() && closingName == tagName)
inlineCase = true;
}
// INLINE TAG
if (inlineCase) {
for (size_t k = 0; k < st.size(); k++) out += indent;
out += "<" + tagName + ">" + text + "</" + tagName + ">\n";
// skip text + closing tag
i = xml.find('>', nextTag) + 1;
continue;
}
// NORMAL OPENING TAG
for (size_t k = 0; k < st.size(); k++) out += indent;
out += tag + "\n";
st.push(tagName);
i = j + 1;
continue;
}
// ================= CLOSING TAG =================
if (xml[i] == '<' && i + 1 < n && xml[i + 1] == '/') {
size_t j = xml.find('>', i);
string tag = xml.substr(i, j - i + 1);
if (!st.empty()) st.pop();
for (size_t k = 0; k < st.size(); k++) out += indent;
out += tag + "\n";
i = j + 1;
continue;
}
// ================= MULTI-LINE TEXT =================
size_t nextTag = xml.find('<', i);
if (nextTag == string::npos) nextTag = n;
string text = trim_copy(xml.substr(i, nextTag - i));
if (!text.empty()) {
for (size_t k = 0; k < st.size(); k++) out += indent;
out += text + "\n";
}
i = nextTag;
}
return out;
}
// Helper to generate indentation spaces based on depth
string getIndent(int level)
{
return string(level * 4, ' '); // 4 spaces per level
}
struct JsonXMLNode
{
string name;
string content;
vector<JsonXMLNode *> children;
JsonXMLNode(string n) : name(n), content("") {} // new way to implement the constructor, it will intialize the values while making the object
~JsonXMLNode()
{
for (auto child : children)
{
delete child;
}
}
};
string trim(const string &str)
{ // عملت ال function دي عشان ميسجلش ال \n والt وال \r
size_t first = str.find_first_not_of(" \t\n\r");
if (first == string::npos)
return "";
size_t last = str.find_last_not_of(" \t\n\r");
return str.substr(first, (last - first + 1));
}
JsonXMLNode *parseXML(const string &xml)
{
JsonXMLNode *root = nullptr;
stack<JsonXMLNode *> nodeStack;
size_t pos = 0;
while (pos < xml.length())
{
size_t lt = xml.find('<', pos);
if (lt == string::npos)
break;
if (lt > pos)
{
string text = trim(xml.substr(pos, lt - pos));
if (!text.empty() && !nodeStack.empty())
{
nodeStack.top()->content = text;
}
}
size_t gt = xml.find('>', lt);
if (gt == string::npos)
break;
string tagContent = xml.substr(lt + 1, gt - lt - 1);
if (tagContent[0] == '/')
{
if (!nodeStack.empty())
{
nodeStack.pop();
}
}
else
{
string tagName = tagContent;
JsonXMLNode *newNode = new JsonXMLNode(tagName);
if (nodeStack.empty())
{
root = newNode;
}
else
{
nodeStack.top()->children.push_back(newNode); // هنا سواء انا كنت parent او
// children ما دام في children جديدة جت هيبقا اخر حاجة موجود في ال node stack هو ال parent بتاعها
}
nodeStack.push(newNode);
}
pos = gt + 1;
}
return root;
}
void nodeToJSON(JsonXMLNode *node, stringstream &ss, int level)
{
if (!node)
return;
// Case 1: It's a leaf node (just text content, no children)
if (node->children.empty())
{
ss << "\"" << node->content << "\"";
return;
}
// Case 2: It's an object (has children)
ss << "{\n";
map<string, vector<JsonXMLNode *>> groups;
vector<string> order;
// Group children by tag name to handle arrays
for (auto child : node->children)
{
if (groups.find(child->name) == groups.end())
{
order.push_back(child->name);
}
groups[child->name].push_back(child);
}
// Iterate through the grouped children
for (size_t i = 0; i < order.size(); ++i)
{
string key = order[i];
const auto &list = groups[key];
// Print Indentation + Key
ss << getIndent(level + 1) << "\"" << key << "\": ";
if (list.size() > 1)
{
// --- Handle Arrays ---
ss << "[\n";
for (size_t k = 0; k < list.size(); ++k)
{
ss << getIndent(level + 2); // Indent array items further
nodeToJSON(list[k], ss, level + 2);
if (k < list.size() - 1)
ss << ",\n"; // Comma between items
else
ss << "\n";
}
ss << getIndent(level + 1) << "]";
}
else
{
// --- Handle Single Objects ---
nodeToJSON(list[0], ss, level + 1);
}
// Comma between keys (if not the last one)
if (i < order.size() - 1)
ss << ",\n";
else
ss << "\n";
}
// Closing brace with proper indentation
ss << getIndent(level) << "}";
}
string json(const string &xml)
{
JsonXMLNode *root = parseXML(xml);
if (!root)
return "{}";
stringstream ss;
ss << "{\n";
// Fixed a small bug here: You had a space inside the quote "\" " which made keys look like " users"
ss << getIndent(1) << "\"" << root->name << "\": ";
nodeToJSON(root, ss, 1); // Start recursion at level 1
ss << "\n}"; // Close the main object
delete root;
return ss.str();
}
string mini(const string &xml)
{
string output = "";
bool inTag = false;
bool inText = false;
for (char c : xml)
{
if (c == '<')
{
inTag = true;
inText = false;
output += c;
}
else if (c == '>')
{
inTag = false;
inText = true;
output += c;
}
else
{
if (inTag)
{
if (c != ' ' && c != '\n' && c != '\t' && c != '\r')
output += c;
}
else if (inText)
{
if (c == '\n' || c == '\t' || c == '\r')
continue;
// Simulate output.back() without using back()
bool lastIsSpace = false;
bool lastIsTag = false;
if (output.length() > 0)
{
char last = output[output.length() - 1];
lastIsSpace = (last == ' ');
lastIsTag = (last == '>');
}
if (!(c == ' ' && (lastIsSpace || lastIsTag)))
output += c;
}
}
}
return output;
}
string compress(const string &xml)
{
// Convert string to bytes
vector<unsigned char> data = stringToBytes(xml);
if (data.empty())
{
cerr << "Error: Empty input for compression" << endl;
return "";
}
// Clear dictionary and perform BPE
BPE_DICTIONARY.clear();
unsigned char next_free = 128; // Start replacement symbols at 128
// Loop until no more pairs are found or we run out of free bytes (255)
while (oneIterationBPE(data, next_free))
;
// Build binary output
stringstream result;
// Write dictionary size (as binary)
size_t dict_size = BPE_DICTIONARY.size();
result.write(reinterpret_cast<const char *>(&dict_size), sizeof(dict_size));
// Write dictionary entries (raw bytes)
for (const auto &entry : BPE_DICTIONARY)
{
result.write(reinterpret_cast<const char *>(&entry.first), sizeof(entry.first));
result.write(reinterpret_cast<const char *>(&entry.second), sizeof(entry.second));
}
// Write compressed data (raw bytes)
result.write(reinterpret_cast<const char *>(data.data()), data.size());
size_t total_size = sizeof(dict_size) + (BPE_DICTIONARY.size() * 2) + data.size();
cout << "Compression complete. Original size: " << xml.length()
<< " bytes, Compressed size: " << total_size
<< " bytes (Saved: " << (int)xml.length() - (int)total_size << " bytes)" << endl;
return result.str();
}
string decompress(const string &xml)
{
// 1. Basic Validation
if (xml.empty())
{
cerr << "Error: Empty input passed to decompress function!" << endl;
return "";
}
// Print input size to debug "Text Mode" reading issues
cout << "Debug: Decompress received " << xml.size() << " bytes." << endl;
stringstream ss(xml);
// 2. Read Dictionary Size
size_t dict_size;
ss.read(reinterpret_cast<char *>(&dict_size), sizeof(dict_size));
if (ss.fail())
{
cerr << "Error: Failed to read dictionary size. Input too short?" << endl;
return "";
}
cout << "Debug: Dictionary size is " << dict_size << " entries." << endl;
// 3. Reconstruct Dictionary
vector<pair<unsigned char, unsigned char>> dict;
dict.reserve(dict_size);
for (size_t i = 0; i < dict_size; ++i)
{
unsigned char first, second;
ss.read(reinterpret_cast<char *>(&first), sizeof(first));
ss.read(reinterpret_cast<char *>(&second), sizeof(second));
dict.push_back({first, second});
}
// 4. Read Compressed Byte Data
// read directly from the current position to the end
streampos data_start = ss.tellg();
// Read the rest of the stream into a vector directly
string remaining_str = xml.substr(data_start);
vector<unsigned char> data(remaining_str.begin(), remaining_str.end());
cout << "Debug: Processing " << data.size() << " bytes of compressed data." << endl;
// 5. Recursive Expansion Logic
string output;
// Recursive lambda
function<void(unsigned char)> expand = [&](unsigned char b)
{
int index = (int)b - 128;
if (index >= 0 && index < (int)dict.size())
{
expand(dict[index].first);
expand(dict[index].second);
}
else
{
output += (char)b;
}
};
// 6. Generate Decompressed String
for (unsigned char b : data)
{
expand(b);
}
cout << "Debug: Decompressed output size is " << output.size() << " bytes." << endl;
return output;
}
string most_active(const string &xml)
{
struct User {
string id;
string name;
int postCount = 0; // Changed from followCount to postCount
};
vector<User> users;
// -------- 1) Read users (id + name) --------
int i = 0;
while (i < xml.length()) {
if (xml.substr(i, 6) == "<user>") {
i += 6;
User u;
while (xml.substr(i, 7) != "</user>") {
if (xml.substr(i, 4) == "<id>" && u.id.empty()) {
i += 4;
while (xml.substr(i, 5) != "</id>")
u.id += xml[i++];
i += 5;
}
else if (xml.substr(i, 6) == "<name>") {
i += 6;
while (xml.substr(i, 7) != "</name>")
u.name += xml[i++];
i += 7;
}
else if (xml.substr(i, 6) == "<post>") {
// Count posts
u.postCount++;
i += 6;
}
else {
i++;
}
}
users.push_back(u);
i += 7; // </user>
}
else {
i++;