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
extern crate hex;
extern crate serde;
use self::serde::{Deserialize, Serialize};
use std::collections::HashMap;
#[derive(Serialize, Deserialize, Debug)]
pub struct HuffmanData {
pub encoded_data: Vec<u8>,
pub encoding_map: HashMap<u8,String>,
}
pub fn huffman_decode(huffman_encoded_data: &HuffmanData) -> Vec<u8> {
let encoded_data_bin_string_padded = u8_vec_to_bin_string(&huffman_encoded_data.encoded_data);
let encoded_data_bin_string = unpad_encoded_data(&encoded_data_bin_string_padded);
let decoded_data = huffman_decode_bin_string(&encoded_data_bin_string,&huffman_encoded_data.encoding_map);
return decoded_data;
}
pub fn huffman_encode(data: &Vec<u8>) -> HuffmanData {
let frequency_map = build_frequency_map(&data);
let huffman_tree = build_huffman_tree(&frequency_map);
let mut encoding_map:HashMap<u8, String> = HashMap::new();
build_encoding_map(&huffman_tree,&mut encoding_map,"".to_string());
let encoded_data_bin = huffman_encode_string(&data,&encoding_map);
let padded_encoded_data_bin = pad_encoded_data(&encoded_data_bin);
let encoded_data_u8_vec = bin_string_to_u8_vec(&padded_encoded_data_bin);
get_stats(&data,&encoded_data_u8_vec);
let huffman_encoded_data = HuffmanData{encoded_data: encoded_data_u8_vec,encoding_map: encoding_map};
return huffman_encoded_data;
}
struct Node {
left: Option<Box<Node>>,
right: Option<Box<Node>>,
freq: i64,
value: Option<u8>,
}
fn build_frequency_map(data: &Vec<u8>) -> HashMap<u8, i64> {
let mut frequency_map: HashMap<u8, i64> = HashMap::new();
for byte in data {
match frequency_map.get_mut(&byte){
Some(result) => {
*result = *result + 1;
}
None => {
frequency_map.insert(*byte, 1);
}
}
}
return frequency_map;
}
fn build_huffman_tree(frequency_map: &HashMap<u8, i64>) -> Node {
let mut freq_list: Vec<Node> = Vec::new();
for (data, freq) in frequency_map {
freq_list.push(Node{left: None, right: None,value: Some(*data),freq: *freq});
}
freq_list.sort_by(|a, b| b.value.cmp(&a.value));
freq_list.sort_by(|a, b| b.freq.cmp(&a.freq));
while freq_list.len() != 1 {
let left_node = freq_list.pop().unwrap();
let right_node = freq_list.pop().unwrap();
let new_node_freq = left_node.freq + right_node.freq;
let new_node = Node{left: Some(Box::new(left_node)), right: Some(Box::new(right_node)),value: None,freq: new_node_freq};
freq_list.push(new_node);
freq_list.sort_by(|a, b| b.freq.cmp(&a.freq));
}
return freq_list.pop().unwrap();
}
fn build_encoding_map(node: &Node,encoding_map: &mut HashMap<u8, String>,code: String){
match node.value {
Some(value) => {
encoding_map.insert(value, code);
}
None => {
match &node.left {
Some(left) => {
build_encoding_map(left,encoding_map,code.clone() + "0");
}
None => {}
}
match &node.right {
Some(right) => {
build_encoding_map(right,encoding_map,code.clone() + "1");
}
None => {}
}
}
}
}
fn bin_string_to_u8_vec(bin_string: &String) -> Vec<u8>{
let mut temp_byte: String = String::new();
let mut u8_vec: Vec<u8> = Vec::new();
for bit in bin_string.chars() {
if temp_byte.len() == 8 {
let u8_byte = u8::from_str_radix(temp_byte.as_str(), 2).unwrap();
u8_vec.push(u8_byte);
temp_byte = "".to_string();
}
temp_byte.push(bit);
}
let u8_value = u8::from_str_radix(temp_byte.as_str(), 2).unwrap();
u8_vec.push(u8_value);
return u8_vec
}
fn u8_vec_to_bin_string(u8_vec: &Vec<u8>) -> String{
let mut bin_string: String = String::new();
for byte in u8_vec {
bin_string = bin_string + format!("{:b}", byte).as_str();
}
return bin_string;
}
fn pad_encoded_data(encoded_data: &String) -> String {
let mut padded_encoded_data: String = String::new();
let mut temp_padded_byte: String = "1".to_string();
for bit in encoded_data.chars() {
if temp_padded_byte.len() > 7 {
padded_encoded_data = padded_encoded_data + temp_padded_byte.as_str();
temp_padded_byte = "1".to_string();
}
temp_padded_byte = temp_padded_byte + &bit.to_string();
}
padded_encoded_data = padded_encoded_data + temp_padded_byte.as_str();
return padded_encoded_data;
}
fn unpad_encoded_data(padded_data: &String) -> String {
let mut data: String = String::new();
let mut temp_padded_byte: String = String::new();
for bit in padded_data.chars() {
if temp_padded_byte.len() > 7 {
let(_,byte) = temp_padded_byte.split_at(1);
data = data + byte;
temp_padded_byte = String::new();
}
temp_padded_byte = temp_padded_byte + &bit.to_string();
}
let(_,byte) = temp_padded_byte.split_at(1);
data = data + byte;
return data;
}
fn huffman_encode_string(data: &Vec<u8>,encoding_map: &HashMap<u8, String>) -> String {
let mut encoded_data = String::new();
for c in data {
match encoding_map.get(&c) {
Some(code) => {
encoded_data = encoded_data + code;
}
None =>{}
}
}
return encoded_data;
}
fn huffman_decode_bin_string(encoded_data: &String,encoding_map: &HashMap<u8, String>) -> Vec<u8>{
let inverted_encoding_map = invert_encoding_map(&encoding_map);
let mut data: Vec<u8> = Vec::new();
let mut temp_code = String::new();
let mut encoded_data_rev = encoded_data.chars().rev().collect::<String>();
loop {
match inverted_encoding_map.get(&temp_code) {
Some(byte) => {
temp_code = "".to_string();
data.push(*byte);
}
None =>{
match encoded_data_rev.pop() {
Some(code) => {
temp_code.push(code);
}
None => {
break;
}
}
}
}
}
return data;
}
fn invert_encoding_map(encoding_map: &HashMap<u8, String>) -> HashMap<String, u8>{
let mut inverted_encoding_map: HashMap<String, u8> = HashMap::new();
for (key,value) in encoding_map {
inverted_encoding_map.insert(value.to_owned(),*key);
}
return inverted_encoding_map;
}
fn get_stats(data: &Vec<u8>,encoded_data: &Vec<u8>){
let data_size = (data.len() * 8) as f32;
let encoded_size = (encoded_data.len() * 8) as f32;
let ratio = (1 as f32 - ( encoded_size / data_size ) as f32) * 100 as f32 ;
println!("Stats:");
println!("Data size in bits {}",data_size);
println!("Encoded data size in bits {}",encoded_size);
println!("Compression Ratio is {}%", ratio);
println!("");
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_pad_encoded_data(){
let input_data = "1011100101010000010100000110100101110101001010011011111000111001111011101001001010111010111111100001100".to_string();
let expected_data = "1101110011010100100010101000011011001011110101001101001110111110100111001111101111010010101010111101011111111000101100".to_string();
let test_output = pad_encoded_data(&input_data);
assert_eq!(expected_data,test_output);
}
#[test]
fn test_unpad_encoded_data(){
let input_data = "1101110011010100100010101000011011001011110101001101001110111110100111001111101111010010101010111101011111111000101100".to_string();
let expected_data = "1011100101010000010100000110100101110101001010011011111000111001111011101001001010111010111111100001100".to_string();
let test_output = unpad_encoded_data(&input_data);
assert_eq!(expected_data,test_output);
}
#[test]
fn test_bin_string_to_u8_vec(){
let input_data = "1101110011010100100010101000011011001011110101001101001110111110100111001111101111010010101010111101011111111000101100".to_string();
let expected_data: Vec<u8> = vec![220, 212, 138, 134, 203, 212, 211, 190, 156, 251, 210, 171, 215, 248, 44];
let test_output = bin_string_to_u8_vec(&input_data);
assert_eq!(expected_data,test_output);
}
#[test]
fn test_u8_vec_to_bin_string(){
let input_data: Vec<u8> = vec![220, 212, 138, 134, 203, 212, 211, 190, 156, 251, 210, 171, 215, 248, 44];
let expected_data = "1101110011010100100010101000011011001011110101001101001110111110100111001111101111010010101010111101011111111000101100".to_string();
let test_output = u8_vec_to_bin_string(&input_data);
assert_eq!(expected_data,test_output);
}
#[test]
fn test_build_frequency_map(){
let input_data: Vec<u8> = "this is a test string!".to_string().into_bytes();
let mut expected_data: HashMap<u8, i64> = HashMap::new();
expected_data.insert(b'h',1);
expected_data.insert(b'a',1);
expected_data.insert(b' ',4);
expected_data.insert(b'g',1);
expected_data.insert(b'i',3);
expected_data.insert(b's',4);
expected_data.insert(b'!',1);
expected_data.insert(b'n',1);
expected_data.insert(b'r',1);
expected_data.insert(b't',4);
expected_data.insert(b'e',1);
let test_output = build_frequency_map(&input_data);
assert_eq!(expected_data,test_output);
}
#[test]
fn test_build_huffman_tree_build_encoding_map(){
let mut input_data: HashMap<u8, i64> = HashMap::new();
input_data.insert(b'h',1);
input_data.insert(b'a',1);
input_data.insert(b' ',4);
input_data.insert(b'g',1);
input_data.insert(b'i',3);
input_data.insert(b's',4);
input_data.insert(b'!',1);
input_data.insert(b'n',1);
input_data.insert(b'r',1);
input_data.insert(b't',4);
input_data.insert(b'e',1);
let mut expected_data: HashMap<u8, String> = HashMap::new();
expected_data.insert(b'h',"10010".to_string());
expected_data.insert(b'a',"0011".to_string());
expected_data.insert(b' ',"01".to_string());
expected_data.insert(b'g',"0001".to_string());
expected_data.insert(b'i',"101".to_string());
expected_data.insert(b's',"110".to_string());
expected_data.insert(b'!',"0010".to_string());
expected_data.insert(b'n',"10011".to_string());
expected_data.insert(b'r',"1000".to_string());
expected_data.insert(b't',"111".to_string());
expected_data.insert(b'e',"0000".to_string());
let test_output_tree = build_huffman_tree(&input_data);
let mut test_output:HashMap<u8, String> = HashMap::new();
build_encoding_map(&test_output_tree,&mut test_output,"".to_string());
assert_eq!(expected_data,test_output);
}
#[test]
fn test_invert_encoding_map(){
let input_data: HashMap<u8, String> = [
(b'h',"10010".to_string()),
(b'a',"0011".to_string()),
(b' ',"01".to_string()),
(b'g',"0001".to_string()),
(b'i',"101".to_string()),
(b's',"110".to_string()),
(b'!',"0010".to_string()),
(b'n',"10011".to_string()),
(b'r',"1000".to_string()),
(b't',"111".to_string()),
(b'e',"0000".to_string())
].iter().cloned().collect();
let expected_data: HashMap<String, u8> = [
("10010".to_string(),b'h'),
("0011".to_string(),b'a'),
("01".to_string(),b' '),
("0001".to_string(),b'g'),
("101".to_string(),b'i'),
("110".to_string(),b's'),
("0010".to_string(),b'!'),
("10011".to_string(),b'n'),
("1000".to_string(),b'r'),
("111".to_string(),b't'),
("0000".to_string(),b'e'),
].iter().cloned().collect();
let test_output = invert_encoding_map(&input_data);
assert_eq!(expected_data,test_output);
}
#[test]
fn test_huffman_encode_string(){
let input_data: Vec<u8> = "this is a test string!".to_string().into_bytes();
let input_encoding_map: HashMap<u8, String> = [
(b'h',"10010".to_string()),
(b'a',"0011".to_string()),
(b' ',"01".to_string()),
(b'g',"0001".to_string()),
(b'i',"101".to_string()),
(b's',"110".to_string()),
(b'!',"0010".to_string()),
(b'n',"10011".to_string()),
(b'r',"1000".to_string()),
(b't',"111".to_string()),
(b'e',"0000".to_string())
].iter().cloned().collect();
let expected_data: String = "11110010101110011011100100110111100001101110111011110001011001100010010".to_string();
let test_output = huffman_encode_string(&input_data,&input_encoding_map);
assert_eq!(expected_data,test_output);
}
#[test]
fn test_huffman_decode_bin_string(){
let input_data: String = "11110010101110011011100100110111100001101110111011110001011001100010010".to_string();
let input_encoding_map: HashMap<u8, String> = [
(b'h',"10010".to_string()),
(b'a',"0011".to_string()),
(b' ',"01".to_string()),
(b'g',"0001".to_string()),
(b'i',"101".to_string()),
(b's',"110".to_string()),
(b'!',"0010".to_string()),
(b'n',"10011".to_string()),
(b'r',"1000".to_string()),
(b't',"111".to_string()),
(b'e',"0000".to_string())
].iter().cloned().collect();
let expected_data: Vec<u8> = "this is a test string!".to_string().into_bytes();
let test_output = huffman_decode_bin_string(&input_data,&input_encoding_map);
assert_eq!(expected_data,test_output);
}
}