-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCompressionHelper.cs
More file actions
1216 lines (1052 loc) · 41.8 KB
/
CompressionHelper.cs
File metadata and controls
1216 lines (1052 loc) · 41.8 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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Zippy;
/// <research>
/// https://en.wikipedia.org/wiki/Huffman_coding
/// https://en.wikipedia.org/wiki/Canonical_Huffman_code
/// </research>
#region [Char Version]
public class HuffmanCharNode
{
public char? Character { get; set; }
public int Frequency { get; set; }
public HuffmanCharNode Left { get; set; }
public HuffmanCharNode Right { get; set; }
}
public class HuffmanCharTree
{
HuffmanCharNode root;
Dictionary<char, string> codes = new Dictionary<char, string>();
bool noRepeatsForEncoding = false;
/// <summary>
/// Build the Huffman Tree from the input text
/// </summary>
public void Build(string text)
{
if (string.IsNullOrEmpty(text))
return;
// Add repeating header for successful tree encoding (for non-repeat character strings).
if (!text.StartsWith("000"))
text = "000" + text;
// Edge case: If text contains only one unique character, directly assign "0" as its Huffman code
if (text.Distinct().Count() == 1 || text.Distinct().Count() == text.Length)
{
char uniqueChar = text[0];
codes[uniqueChar] = "0";
noRepeatsForEncoding = true;
return;
}
else
{
noRepeatsForEncoding = false;
}
// Step 1: Calculate frequency of each character in the text
var frequencies = text.GroupBy(c => c)
.ToDictionary(g => g.Key, g => g.Count());
// Step 2: Create a priority queue (sorted list) to hold all nodes
var priorityQueue = new SortedList<int, List<HuffmanCharNode>>();
// Populate priority queue with leaf nodes
foreach (var kvp in frequencies)
{
AddNodeToPriorityQueue(priorityQueue, new HuffmanCharNode { Character = kvp.Key, Frequency = kvp.Value });
}
// Step 3: Build the Huffman tree by merging the lowest frequency nodes
while (priorityQueue.Count > 1)
{
// Remove two nodes with the lowest frequency
var leftNode = RemoveMinNodeFromPriorityQueue(priorityQueue);
var rightNode = RemoveMinNodeFromPriorityQueue(priorityQueue);
// Create a new internal node with these two nodes as children
var newNode = new HuffmanCharNode
{
Character = null, // Non-leaf node
Frequency = leftNode.Frequency + rightNode.Frequency,
Left = leftNode,
Right = rightNode
};
// Add the new node back into the priority queue
AddNodeToPriorityQueue(priorityQueue, newNode);
}
// Step 4: The remaining node is the root of the Huffman Tree
root = priorityQueue.First().Value.First();
// Step 5: Generate Huffman codes by traversing the tree
GenerateCodes(root, "");
}
/// <summary>
/// Adds a node to the priority queue based on its frequency
/// </summary>
void AddNodeToPriorityQueue(SortedList<int, List<HuffmanCharNode>> queue, HuffmanCharNode node)
{
if (!queue.ContainsKey(node.Frequency))
queue[node.Frequency] = new List<HuffmanCharNode>();
queue[node.Frequency].Add(node);
}
/// <summary>
/// Removes the node with the lowest frequency from the priority queue
/// </summary>
HuffmanCharNode RemoveMinNodeFromPriorityQueue(SortedList<int, List<HuffmanCharNode>> queue)
{
var minFreq = queue.First().Key;
var nodeList = queue[minFreq];
var node = nodeList.First();
nodeList.RemoveAt(0);
if (nodeList.Count == 0)
queue.Remove(minFreq);
return node;
}
/// <summary>
/// Generate Huffman codes for each character by traversing the tree
/// </summary>
void GenerateCodes(HuffmanCharNode node, string code)
{
if (node == null)
return;
if (node.Character.HasValue)
codes[node.Character.Value] = code;
GenerateCodes(node.Left, code + "0");
GenerateCodes(node.Right, code + "1");
}
/// <summary>
/// Compress the input text to a binary string using the Huffman codes.
/// This can be used with a <see cref="System.IO.BinaryWriter"/> to efficiently write the data to disk.
/// </summary>
/// <remarks>
/// If extremely large amounts of data are to be compressed then this method could throw
/// <see cref="System.OutOfMemoryException"/> since the <see cref="System.Text.StringBuilder"/>
/// has a limit to how much data it can hold, approx 200MB.
/// </remarks>
public string Compress(string text)
{
if (codes.Count == 0)
throw new Exception("There are no HuffmanNodes in the tree. You must call Build first before any compress/decompress methods can be used.");
if (noRepeatsForEncoding)
return text;
try
{
StringBuilder sb = new StringBuilder();
foreach (var ch in text)
{
if (codes.TryGetValue(ch, out string value))
{
sb.Append(value);
}
}
return sb.ToString();
}
catch (Exception ex) // System.Collections.Generic.KeyNotFoundException
{
Console.WriteLine($"[ERROR] {ex.Message}");
}
return text;
}
/// <summary>
/// Compress the input text and encode it as Base64, embedding the bit length in the data
/// </summary>
public string CompressToBase64(string text)
{
if (codes.Count == 0)
throw new Exception("There are no HuffmanNodes in the tree. You must call Build first before any compress/decompress methods can be used.");
if (noRepeatsForEncoding)
return text;
try
{ // Compress to binary string
StringBuilder binaryBuilder = new StringBuilder();
foreach (var ch in text) { binaryBuilder.Append(codes[ch]); }
string binaryString = binaryBuilder.ToString();
int originalBitLength = binaryString.Length; // Store the original bit length
// Convert the binary string to a byte array
byte[] byteArray = ConvertBinaryStringToByteArray(binaryString);
// Create a new array to hold the original bit length and the compressed data
byte[] resultArray = new byte[byteArray.Length + 4]; // 4 bytes for the length (int)
// Store the bit length in the first 4 bytes
byte[] bitLengthBytes = BitConverter.GetBytes(originalBitLength);
if (BitConverter.IsLittleEndian) Array.Reverse(bitLengthBytes); // Ensure big-endian order
Array.Copy(bitLengthBytes, resultArray, 4);
// Copy the compressed data after the bit length
Array.Copy(byteArray, 0, resultArray, 4, byteArray.Length);
// Encode the result array to Base64
return Convert.ToBase64String(resultArray);
}
catch (Exception ex) // System.Collections.Generic.KeyNotFoundException
{
Console.WriteLine($"[ERROR] {ex.Message}");
}
return text;
}
/// <summary>
/// Decompress from Base64, automatically extracting the bit length from the encoded data
/// </summary>
public string DecompressFromBase64(string base64Text)
{
if (noRepeatsForEncoding)
return base64Text;
try
{ // Decode the Base64 string to a byte array
byte[] resultArray = Convert.FromBase64String(base64Text);
// Extract the original bit length from the first 4 bytes
byte[] bitLengthBytes = new byte[4];
Array.Copy(resultArray, bitLengthBytes, 4);
if (BitConverter.IsLittleEndian) Array.Reverse(bitLengthBytes); // Ensure big-endian order
int originalBitLength = BitConverter.ToInt32(bitLengthBytes, 0);
// Extract the compressed data after the bit length
byte[] byteArray = new byte[resultArray.Length - 4];
Array.Copy(resultArray, 4, byteArray, 0, byteArray.Length);
// Convert byte array back to a binary string, truncated to the original bit length
string binaryString = ConvertByteArrayToBinaryString(byteArray, originalBitLength);
// Decompress the binary string using the Huffman tree
return Decompress(binaryString);
}
catch (Exception ex) // FormatException
{
Console.WriteLine($"[ERROR] {ex.Message}");
}
return base64Text;
}
/// <summary>
/// Decompress the binary string back to the original text
/// </summary>
public string Decompress(string binaryText)
{
if (noRepeatsForEncoding)
return binaryText;
StringBuilder sb = new StringBuilder();
HuffmanCharNode currentNode = root;
foreach (var bit in binaryText)
{
if (currentNode != null && currentNode.Left != null && currentNode.Right != null)
{
currentNode = bit == '0' ? currentNode.Left : currentNode.Right;
if (currentNode.Left == null && currentNode.Right == null) // Leaf node
{
sb.Append(currentNode.Character.Value);
currentNode = root;
}
}
}
var result = $"{sb}";
if (result.StartsWith("000"))
return result.Substring(3);
else
return result;
}
/// <summary>
/// Compress and write the Huffman tree and compressed binary data using BinaryWriter
/// </summary>
public void CompressToStream(string text, string fileName)
{
try
{
// Compress the text and write it to a file using BinaryWriter
using (FileStream fs = new FileStream(fileName, FileMode.Create))
{
using (BinaryWriter bw = new BinaryWriter(fs))
{
CompressToStream(text, bw);
}
}
}
catch (Exception) { }
}
/// <summary>
/// Compress and write the Huffman tree and compressed binary data using BinaryWriter
/// </summary>
public void CompressToStream(string text, BinaryWriter writer)
{
// First build the Huffman tree for the given text
Build(text);
// Write the character-to-binary-code mappings (Huffman tree)
writer.Write(codes.Count); // Number of mappings
foreach (var kvp in codes)
{
writer.Write(kvp.Key); // Character
writer.Write(kvp.Value); // Corresponding binary code
}
// Compress the text to a binary string
string binaryString = Compress(text);
// Convert the binary string to a byte array
byte[] byteArray = ConvertBinaryStringToByteArray(binaryString);
// Write the compressed data length (in bytes) and the exact bit length
writer.Write(byteArray.Length); // Number of bytes
writer.Write(binaryString.Length); // Exact number of bits used
// Write the compressed byte array
writer.Write(byteArray);
}
/// <summary>
/// Read the Huffman tree and compressed binary data using BinaryReader and decompress it
/// </summary>
public string DecompressFromStream(string fileName)
{
string result = string.Empty;
try
{
using (FileStream fs = new FileStream(fileName, FileMode.Open))
{
using (BinaryReader reader = new BinaryReader(fs))
{
result = DecompressFromStream(reader);
}
}
}
catch (Exception) { }
return result;
}
/// <summary>
/// Read the Huffman tree and compressed binary data using BinaryReader and decompress it
/// </summary>
public string DecompressFromStream(BinaryReader reader)
{
// Read the Huffman tree (character-to-binary-code mappings)
int mappingsCount = reader.ReadInt32(); // Number of mappings
codes = new Dictionary<char, string>();
for (int i = 0; i < mappingsCount; i++)
{
char character = reader.ReadChar(); // Character
string code = reader.ReadString(); // Binary code
codes[character] = code;
}
// Rebuild the Huffman tree from the mappings
RebuildTreeFromMappings();
// Read the compressed data
int byteArrayLength = reader.ReadInt32(); // Number of bytes in the compressed data
int bitLength = reader.ReadInt32(); // Number of valid bits in the binary string
byte[] byteArray = reader.ReadBytes(byteArrayLength);
// Convert the byte array back to a binary string
string binaryString = ConvertByteArrayToBinaryString(byteArray, bitLength);
// Decompress the binary string
return Decompress(binaryString);
}
/// <summary>
/// Rebuild the Huffman tree from the character-to-binary-code mappings
/// </summary>
void RebuildTreeFromMappings()
{
root = new HuffmanCharNode();
foreach (var kvp in codes)
{
InsertIntoTree(root, kvp.Key, kvp.Value);
}
}
/// <summary>
/// Helper method to insert a character into the Huffman tree using its binary code
/// </summary>
void InsertIntoTree(HuffmanCharNode node, char character, string code)
{
foreach (char c in code)
{
if (c == '0')
{
if (node.Left == null)
node.Left = new HuffmanCharNode();
node = node.Left;
}
else
{
if (node.Right == null)
node.Right = new HuffmanCharNode();
node = node.Right;
}
}
node.Character = character;
}
/// <summary>
/// Convert a binary string (e.g., "101010") into a byte array
/// </summary>
byte[] ConvertBinaryStringToByteArray(string binaryString)
{
int numOfBytes = (binaryString.Length + 7) / 8; // +7 to round up to the nearest byte
byte[] byteArray = new byte[numOfBytes];
for (int i = 0; i < binaryString.Length; i++)
{
if (binaryString[i] == '1')
{
byteArray[i / 8] |= (byte)(1 << (7 - (i % 8)));
}
}
return byteArray;
}
/// <summary>
/// Convert a byte array back into a binary string, truncated to the original length
/// </summary>
string ConvertByteArrayToBinaryString(byte[] byteArray, int originalBitLength)
{
StringBuilder binaryStringBuilder = new StringBuilder();
foreach (var b in byteArray)
{
binaryStringBuilder.Append(Convert.ToString(b, 2).PadLeft(8, '0')); // Ensure 8 bits per byte
}
// Truncate the binary string to the original bit length
return binaryStringBuilder.ToString().Substring(0, originalBitLength);
}
}
#endregion
#region [Byte Version]
public class HuffmanByteNode
{
public byte? ByteValue { get; set; }
public int Frequency { get; set; }
public HuffmanByteNode Left { get; set; }
public HuffmanByteNode Right { get; set; }
}
/// <summary>
/// To load a character string into the system from a byte stream you need to know
/// the source encoding to therefore interpret and subsequently translate it correctly
/// (otherwise the codes will be taken as already being in the system's default encoding
/// and thus render gibberish). Similarly, when a string is written to an external source,
/// it will be written in a particular encoding.
/// </summary>
public class HuffmanByteTree
{
HuffmanByteNode root;
Dictionary<byte, string> codes = new Dictionary<byte, string>();
/// <summary>
/// Build the Huffman Tree from the input byte array
/// </summary>
public void Build(byte[] data)
{
// Step 1: Calculate frequency of each byte in the array
var frequencies = data.GroupBy(b => b)
.ToDictionary(g => g.Key, g => g.Count());
// Step 2: Create a priority queue (sorted list) to hold all nodes
var priorityQueue = new SortedList<int, List<HuffmanByteNode>>();
// Populate priority queue with leaf nodes (each distinct byte)
foreach (var kvp in frequencies)
{
var node = new HuffmanByteNode { ByteValue = kvp.Key, Frequency = kvp.Value };
AddNodeToPriorityQueue(priorityQueue, node);
}
// If there's only one distinct byte, we need to handle it separately
if (priorityQueue.Count == 1)
{
var singleNode = priorityQueue.First().Value.First();
codes[singleNode.ByteValue.Value] = "0"; // Assign a default code
return;
}
// Step 3: Build the Huffman tree by merging the lowest frequency nodes
while (priorityQueue.Count > 1)
{
// Remove two nodes with the lowest frequency
var leftNode = RemoveMinNodeFromPriorityQueue(priorityQueue);
var rightNode = RemoveMinNodeFromPriorityQueue(priorityQueue);
// Create a new internal node with these two nodes as children
var newNode = new HuffmanByteNode
{
Frequency = leftNode.Frequency + rightNode.Frequency,
Left = leftNode,
Right = rightNode
};
// Add the new node back into the priority queue
AddNodeToPriorityQueue(priorityQueue, newNode);
}
// Step 4: The remaining node is the root of the Huffman Tree
root = priorityQueue.First().Value.First();
// Step 5: Generate Huffman codes by traversing the tree
GenerateCodes(root, "");
}
/// <summary>
/// Build the Huffman Tree from the input string
/// </summary>
public void Build(string text, Encoding? enc)
{
if (enc is null)
enc = Encoding.UTF8;
var data = enc.GetBytes(text);
// Step 1: Calculate frequency of each byte in the array
var frequencies = data.GroupBy(b => b)
.ToDictionary(g => g.Key, g => g.Count());
// Step 2: Create a priority queue (sorted list) to hold all nodes
var priorityQueue = new SortedList<int, List<HuffmanByteNode>>();
// Populate priority queue with leaf nodes (each distinct byte)
foreach (var kvp in frequencies)
{
var node = new HuffmanByteNode { ByteValue = kvp.Key, Frequency = kvp.Value };
AddNodeToPriorityQueue(priorityQueue, node);
}
// If there's only one distinct byte, we need to handle it separately
if (priorityQueue.Count == 1)
{
var singleNode = priorityQueue.First().Value.First();
codes[singleNode.ByteValue.Value] = "0"; // Assign a default code
return;
}
// Step 3: Build the Huffman tree by merging the lowest frequency nodes
while (priorityQueue.Count > 1)
{
// Remove two nodes with the lowest frequency
var leftNode = RemoveMinNodeFromPriorityQueue(priorityQueue);
var rightNode = RemoveMinNodeFromPriorityQueue(priorityQueue);
// Create a new internal node with these two nodes as children
var newNode = new HuffmanByteNode
{
Frequency = leftNode.Frequency + rightNode.Frequency,
Left = leftNode,
Right = rightNode
};
// Add the new node back into the priority queue
AddNodeToPriorityQueue(priorityQueue, newNode);
}
// Step 4: The remaining node is the root of the Huffman Tree
root = priorityQueue.First().Value.First();
// Step 5: Generate Huffman codes by traversing the tree
GenerateCodes(root, "");
}
/// <summary>
/// Adds a node to the priority queue based on its frequency
/// </summary>
void AddNodeToPriorityQueue(SortedList<int, List<HuffmanByteNode>> queue, HuffmanByteNode node)
{
if (!queue.ContainsKey(node.Frequency))
queue[node.Frequency] = new List<HuffmanByteNode>();
queue[node.Frequency].Add(node);
}
/// <summary>
/// Removes the node with the lowest frequency from the priority queue
/// </summary>
HuffmanByteNode RemoveMinNodeFromPriorityQueue(SortedList<int, List<HuffmanByteNode>> queue)
{
var minFreq = queue.First().Key;
var nodeList = queue[minFreq];
var node = nodeList.First();
nodeList.RemoveAt(0);
if (nodeList.Count == 0)
queue.Remove(minFreq);
return node;
}
/// <summary>
/// Generate Huffman codes for each byte by traversing the tree
/// </summary>
void GenerateCodes(HuffmanByteNode node, string code)
{
if (node == null)
return;
if (node.ByteValue.HasValue)
{
codes[node.ByteValue.Value] = code;
}
GenerateCodes(node.Left, code + "0");
GenerateCodes(node.Right, code + "1");
}
/// <summary>
/// Compress the input byte array and return the binary string representation
/// </summary>
/// <remarks>
/// If extremely large amounts of data are to be compressed then this method could throw
/// <see cref="System.OutOfMemoryException"/> since the <see cref="System.Text.StringBuilder"/>
/// has a limit to how much data it can hold, approx 200MB.
/// </remarks>
public string Compress(byte[] data)
{
StringBuilder sb = new StringBuilder();
foreach (var b in data)
{
if (codes.TryGetValue(b, out string? value))
{
sb.Append(value);
}
}
return sb.ToString();
}
/// <summary>
/// Compress and write the Huffman tree and compressed binary data using BinaryWriter
/// </summary>
public void CompressByteArrayToStream(byte[] data, string fileName)
{
try
{
// Compress the text and write it to a file using BinaryWriter
using (FileStream fs = new FileStream(fileName, FileMode.Create))
{
using (BinaryWriter bw = new BinaryWriter(fs))
{
CompressByteArrayToStream(data, bw);
}
}
}
catch (Exception ex)
{
throw new Exception($"CompressByteArrayToStream: {ex.Message}", ex);
}
}
/// <summary>
/// Compress and write the Huffman tree and compressed binary data using BinaryWriter
/// </summary>
public void CompressByteArrayToStream(byte[] data, BinaryWriter writer)
{
// First build the Huffman tree for the given byte array
Build(data);
if (codes.Count == 0)
throw new Exception("There are no Huffman codes available for writing. If allowed to continue, this will result in a zero-byte file.");
// Write the byte-to-binary-code mappings (Huffman tree)
writer.Write(codes.Count); // Number of mappings
foreach (var kvp in codes)
{
writer.Write(kvp.Key); // Byte
writer.Write(kvp.Value); // Corresponding binary code
}
// Compress the byte array to a binary string
string binaryString = Compress(data);
// Convert the binary string to a byte array
byte[] byteArray = ConvertBinaryStringToByteArray(binaryString);
// Write the compressed data length (in bytes) and the exact bit length
writer.Write(byteArray.Length); // Number of bytes
writer.Write(binaryString.Length); // Exact number of bits used
// Write the compressed byte array
writer.Write(byteArray);
}
/// <summary>
/// Read the Huffman tree and compressed binary data using BinaryReader and decompress it
/// </summary>
public byte[] DecompressByteArrayFromStream(string fileName)
{
byte[] result;
try
{
using (FileStream fs = new FileStream(fileName, FileMode.Open))
{
using (BinaryReader reader = new BinaryReader(fs))
{
result = DecompressByteArrayFromStream(reader);
}
}
}
catch (Exception ex)
{
//result = [];
throw new Exception($"DecompressByteArrayFromStream: {ex.Message}", ex);
}
return result;
}
/// <summary>
/// Read the Huffman tree and compressed binary data using BinaryReader and decompress it
/// </summary>
public byte[] DecompressByteArrayFromStream(BinaryReader reader)
{
// Read the Huffman tree (byte-to-binary-code mappings)
int mappingsCount = reader.ReadInt32(); // Number of mappings
codes = new Dictionary<byte, string>();
for (int i = 0; i < mappingsCount; i++)
{
try
{
byte byteValue = reader.ReadByte(); // Byte
string code = reader.ReadString(); // Binary code
codes[byteValue] = code;
}
catch (Exception ex)
{
Console.WriteLine($"[WARNING] DecompressByteArrayFromStream: {ex.Message}");
}
}
// Rebuild the Huffman tree from the mappings
RebuildTreeFromMappings();
// Read the compressed data
int byteArrayLength = reader.ReadInt32(); // Number of bytes in the compressed data
int bitLength = reader.ReadInt32(); // Number of valid bits in the binary string
byte[] byteArray = reader.ReadBytes(byteArrayLength);
// Convert the byte array back to a binary string
string binaryString = ConvertByteArrayToBinaryString(byteArray, bitLength);
// Decompress the binary string into the original byte array
return Decompress(binaryString);
}
/// <summary>
/// Rebuild the Huffman tree from the byte-to-binary-code mappings
/// </summary>
void RebuildTreeFromMappings()
{
root = new HuffmanByteNode();
foreach (var kvp in codes)
{
InsertIntoTree(root, kvp.Key, kvp.Value);
}
}
/// <summary>
/// Helper method to insert a byte into the Huffman tree using its binary code
/// </summary>
void InsertIntoTree(HuffmanByteNode node, byte byteValue, string code)
{
foreach (char c in code)
{
if (c == '0')
{
if (node.Left == null)
node.Left = new HuffmanByteNode();
node = node.Left;
}
else
{
if (node.Right == null)
node.Right = new HuffmanByteNode();
node = node.Right;
}
}
node.ByteValue = byteValue;
}
/// <summary>
/// Decompress the binary string back to the original byte array
/// </summary>
byte[] Decompress(string binaryText)
{
List<byte> byteList = new List<byte>();
HuffmanByteNode currentNode = root;
foreach (var bit in binaryText)
{
currentNode = bit == '0' ? currentNode.Left : currentNode.Right;
if (currentNode.Left == null && currentNode.Right == null) // Leaf node
{
byteList.Add(currentNode.ByteValue.Value);
currentNode = root;
}
}
return byteList.ToArray();
}
/// <summary>
/// Convert a binary string (e.g., "101010") into a byte array
/// </summary>
byte[] ConvertBinaryStringToByteArray(string binaryString)
{
int numOfBytes = (binaryString.Length + 7) / 8; // +7 to round up to the nearest byte
byte[] byteArray = new byte[numOfBytes];
for (int i = 0; i < binaryString.Length; i++)
{
if (binaryString[i] == '1')
{
byteArray[i / 8] |= (byte)(1 << (7 - (i % 8)));
}
}
return byteArray;
}
/// <summary>
/// Convert a byte array back into a binary string, truncate to bitLength
/// </summary>
string ConvertByteArrayToBinaryString(byte[] byteArray, int bitLength)
{
StringBuilder binaryStringBuilder = new StringBuilder();
foreach (var b in byteArray)
{
binaryStringBuilder.Append(Convert.ToString(b, 2).PadLeft(8, '0')); // Ensure 8 bits per byte
}
// Truncate the binary string to the exact bit length
return binaryStringBuilder.ToString().Substring(0, bitLength);
}
}
#endregion
#region [Short Version]
public class HuffmanShortNode
{
public short? ShortValue { get; set; } // System.Int16
public int Frequency { get; set; }
public HuffmanShortNode Left { get; set; }
public HuffmanShortNode Right { get; set; }
}
public class HuffmanShortTree
{
HuffmanShortNode root;
Dictionary<short, string> codes = new Dictionary<short, string>();
/// <summary>
/// Build the Huffman Tree from the input short array
/// </summary>
public void Build(short[] data)
{
// Step 1: Calculate frequency of each byte in the array
var frequencies = data.GroupBy(b => b)
.ToDictionary(g => g.Key, g => g.Count());
// Step 2: Create a priority queue (sorted list) to hold all nodes
var priorityQueue = new SortedList<int, List<HuffmanShortNode>>();
// Populate priority queue with leaf nodes (each distinct byte)
foreach (var kvp in frequencies)
{
var node = new HuffmanShortNode { ShortValue = kvp.Key, Frequency = kvp.Value };
AddNodeToPriorityQueue(priorityQueue, node);
}
// If there's only one distinct byte, we need to handle it separately
if (priorityQueue.Count == 1)
{
var singleNode = priorityQueue.First().Value.First();
codes[singleNode.ShortValue.Value] = "0"; // Assign a default code
return;
}
// Step 3: Build the Huffman tree by merging the lowest frequency nodes
while (priorityQueue.Count > 1)
{
// Remove two nodes with the lowest frequency
var leftNode = RemoveMinNodeFromPriorityQueue(priorityQueue);
var rightNode = RemoveMinNodeFromPriorityQueue(priorityQueue);
// Create a new internal node with these two nodes as children
var newNode = new HuffmanShortNode
{
Frequency = leftNode.Frequency + rightNode.Frequency,
Left = leftNode,
Right = rightNode
};
// Add the new node back into the priority queue
AddNodeToPriorityQueue(priorityQueue, newNode);
}
// Step 4: The remaining node is the root of the Huffman Tree
root = priorityQueue.First().Value.First();
// Step 5: Generate Huffman codes by traversing the tree
GenerateCodes(root, "");
}
/// <summary>
/// ORIGINAL - Adds a node to the priority queue based on its frequency
/// </summary>
//void AddNodeToPriorityQueue(SortedList<int, List<HuffmanShortNode>> queue, HuffmanShortNode node)
//{
// int frequency = 1; // Since we only care about the structure, assign frequency = 1 for unique shorts
// if (!queue.ContainsKey(frequency))
// queue[frequency] = new List<HuffmanShortNode>();
//
// queue[frequency].Add(node);
//}
/// <summary>
/// MODIFIED - Adds a node to the priority queue based on its frequency
/// </summary>
void AddNodeToPriorityQueue(SortedList<int, List<HuffmanShortNode>> queue, HuffmanShortNode node)
{
if (!queue.ContainsKey(node.Frequency))
queue[node.Frequency] = new List<HuffmanShortNode>();
queue[node.Frequency].Add(node);
}
/// <summary>
/// Removes the node with the lowest frequency from the priority queue
/// </summary>
HuffmanShortNode RemoveMinNodeFromPriorityQueue(SortedList<int, List<HuffmanShortNode>> queue)
{
var minFreq = queue.First().Key;
var nodeList = queue[minFreq];
var node = nodeList.First();
nodeList.RemoveAt(0);
if (nodeList.Count == 0)
queue.Remove(minFreq);
return node;
}
/// <summary>
/// Generate Huffman codes for each short value by traversing the tree
/// </summary>
void GenerateCodes(HuffmanShortNode node, string code)
{
if (node == null)
return;
if (node.ShortValue.HasValue)
{
codes[node.ShortValue.Value] = code;
}
GenerateCodes(node.Left, code + "0");
GenerateCodes(node.Right, code + "1");
}
/// <summary>
/// Compress the input short array and return the binary string representation
/// </summary>
/// <remarks>
/// If extremely large amounts of data are to be compressed then this method could throw
/// <see cref="System.OutOfMemoryException"/> since the <see cref="System.Text.StringBuilder"/>
/// has a limit to how much data it can hold, approx 200MB.
/// </remarks>
public string Compress(short[] data)
{
StringBuilder sb = new StringBuilder();
foreach (var s in data)
{
if (codes.TryGetValue(s, out string? value))
{
sb.Append(value);
}
}
return sb.ToString();
}
/// <summary>
/// Compress and write the Huffman tree and compressed binary data using BinaryWriter
/// </summary>
public void CompressShortArrayToStream(short[] data, string fileName)
{
try
{
// Compress the text and write it to a file using BinaryWriter
using (FileStream fs = new FileStream(fileName, FileMode.Create))
{
using (BinaryWriter bw = new BinaryWriter(fs))