-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcompression.diff
More file actions
309 lines (296 loc) · 9.51 KB
/
Copy pathcompression.diff
File metadata and controls
309 lines (296 loc) · 9.51 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
--- input/input.rs
+++ output/output.rs
@@ -134,26 +134,7 @@
fn build_huffman_tree(frequencies: HashMap<char, usize>) -> Option<HuffmanNode> {
if frequencies.is_empty() {
return None;
- }
-
- let mut heap: BinaryHeap<HeapNode> = frequencies
- .into_iter()
- .map(|(ch, freq)| HeapNode(HuffmanNode::new_leaf(ch, freq)))
- .collect();
-
- // Special case: only one unique character
- if heap.len() == 1 {
- return heap.pop().map(|node| node.0);
- }
-
- // Build the tree by combining nodes
- while heap.len() > 1 {
- let left = heap.pop().unwrap().0;
- let right = heap.pop().unwrap().0;
- let parent = HuffmanNode::new_internal(left, right);
- heap.push(HeapNode(parent));
- }
-
+ { … 20 line(s) … ⟦tj:064d775e95f8871ec78f7fd58d176e86⟧ }
heap.pop().map(|node| node.0)
}
@@ -167,20 +148,7 @@
fn generate_codes(node: &HuffmanNode, code: String, codes: &mut HashMap<char, String>) {
match node {
HuffmanNode::Leaf { character, .. } => {
- // Use "0" for single character case
- codes.insert(
- *character,
- if code.is_empty() {
- "0".to_string()
- } else {
- code
- },
- );
- }
- HuffmanNode::Internal { left, right, .. } => {
- generate_codes(left, format!("{code}0"), codes);
- generate_codes(right, format!("{code}1"), codes);
- }
+ { … 14 line(s) … ⟦tj:b2545f120ee7414ce39ae09952c97947⟧ }
}
}
@@ -208,16 +176,7 @@
pub fn huffman_encode(text: &str) -> (String, HashMap<char, String>) {
if text.is_empty() {
return (String::new(), HashMap::new());
- }
-
- let frequencies = build_frequency_map(text);
- let tree = build_huffman_tree(frequencies).expect("Failed to build Huffman tree");
-
- let mut codes = HashMap::new();
- generate_codes(&tree, String::new(), &mut codes);
-
- let encoded: String = text.chars().map(|ch| codes[&ch].as_str()).collect();
-
+ { … 10 line(s) … ⟦tj:c652b7d04a32ef25b2ab55585f8d6d18⟧ }
(encoded, codes)
}
@@ -245,25 +204,7 @@
pub fn huffman_decode(encoded: &str, codes: &HashMap<char, String>) -> String {
if encoded.is_empty() {
return String::new();
- }
-
- // Reverse the code map for decoding
- let reverse_codes: HashMap<&str, char> = codes
- .iter()
- .map(|(ch, code)| (code.as_str(), *ch))
- .collect();
-
- let mut decoded = String::new();
- let mut current_code = String::new();
-
- for bit in encoded.chars() {
- current_code.push(bit);
- if let Some(&character) = reverse_codes.get(current_code.as_str()) {
- decoded.push(character);
- current_code.clear();
- }
- }
-
+ { … 19 line(s) … ⟦tj:814c2f954559ff95c1e75e4dc73820c9⟧ }
decoded
}
@@ -303,90 +244,7 @@
pub fn demonstrate_huffman_from_file(file_path: &str) -> std::io::Result<()> {
// Read the file contents
let text = fs::read_to_string(file_path)?;
-
- if text.is_empty() {
- println!("File is empty!");
- return Ok(());
- }
-
- // Encode using Huffman coding
- let (encoded, codes) = huffman_encode(&text);
-
- // Display the results
- println!("Huffman Coding of {file_path}: ");
- println!();
-
- // Show the code table
- println!("Character Codes:");
- println!("{:-<40}", "");
- let mut sorted_codes: Vec<_> = codes.iter().collect();
- sorted_codes.sort_by_key(|(ch, _)| *ch);
-
- for (ch, code) in sorted_codes {
- let display_char = if ch.is_whitespace() {
- format!("'{}' (space/whitespace)", ch.escape_default())
- } else {
- format!("'{ch}'")
- };
- println!("{display_char:20} -> {code}");
- }
- println!("{:-<40}", "");
- println!();
-
- // Show encoding statistics
- let original_bits = text.len() * 8; // Assuming 8-bit characters
- let compressed_bits = encoded.len();
- let compression_ratio = if original_bits > 0 {
- (1.0 - (compressed_bits as f64 / original_bits as f64)) * 100.0
- } else {
- 0.0
- };
-
- println!("Statistics:");
- println!(
- " Original size: {} characters ({} bits)",
- text.len(),
- original_bits
- );
- println!(" Encoded size: {compressed_bits} bits");
- println!(" Compression: {compression_ratio:.2}%");
- println!();
-
- // Show the encoded output (limited to avoid overwhelming the terminal)
- println!("Encoded output:");
- if encoded.len() <= 500 {
- // Split into chunks of 50 for readability
- for (i, chunk) in encoded.as_bytes().chunks(50).enumerate() {
- print!("{:4}: ", i * 50);
- for &byte in chunk {
- print!("{}", byte as char);
- }
- println!();
- }
- } else {
- // Show first and last portions for very long outputs
- println!(" (showing first and last 200 bits)");
- print!(" Start: ");
- for &byte in &encoded.as_bytes()[..200] {
- print!("{}", byte as char);
- }
- println!();
- print!(" End: ");
- for &byte in &encoded.as_bytes()[encoded.len() - 200..] {
- print!("{}", byte as char);
- }
- println!();
- }
- println!();
-
- // Verify decoding
- let decoded = huffman_decode(&encoded, &codes);
- if decoded == text {
- println!("✓ Decoding verification: SUCCESS");
- } else {
- println!("✗ Decoding verification: FAILED");
- }
-
+ { … 84 line(s) … ⟦tj:7d015b08e96d0e5f84e4d4cc8aef60f7⟧ }
Ok(())
}
@@ -409,50 +267,19 @@
}
#[test]
- fn test_simple_string() {
- let text = "hello";
- let (encoded, codes) = huffman_encode(text);
+ fn test_simple_string() { … 13 line(s) … ⟦tj:b5d3168afcefd227097185cf4a892d56⟧ }
- // Verify all characters have codes
- for ch in text.chars() {
- assert!(codes.contains_key(&ch), "Missing code for '{ch}'");
- }
-
- // Verify decoding returns original text
- let decoded = huffman_decode(&encoded, &codes);
- assert_eq!(decoded, text);
- }
-
#[test]
fn test_encode_decode_roundtrip() {
let test_cases = vec![
"a",
- "ab",
- "hello world",
- "the quick brown fox jumps over the lazy dog",
- "aaaaabbbbbcccccdddddeeeeefffffggggghhhhhiiiii",
- ];
-
- for text in test_cases {
- let (encoded, codes) = huffman_encode(text);
- let decoded = huffman_decode(&encoded, &codes);
- assert_eq!(decoded, text, "Failed roundtrip for: '{text}'");
+ { … 10 line(s) … ⟦tj:458b4802df972876258794181648e230⟧ }
}
- }
+}
#[test]
- fn test_frequency_based_encoding() {
- // In "aaabbc", 'a' should have shorter code than 'b' or 'c'
- let (_, codes) = huffman_encode("aaabbc");
- let a_len = codes[&'a'].len();
- let b_len = codes[&'b'].len();
- let c_len = codes[&'c'].len();
+ fn test_frequency_based_encoding() { … 11 line(s) … ⟦tj:c04a515a030b920e368aa1913b936520⟧ }
- // 'a' appears most frequently, so should have shortest or equal code
- assert!(a_len <= b_len);
- assert!(a_len <= c_len);
- }
-
#[test]
fn test_compression_ratio() {
let text = "aaaaaaaaaa"; // 10 'a's
@@ -465,18 +292,8 @@
}
#[test]
- fn test_all_unique_characters() {
- let text = "abcdefg";
- let (encoded, codes) = huffman_encode(text);
+ fn test_all_unique_characters() { … 11 line(s) … ⟦tj:1e5e6ba854ac5f255e7b42126d713fb8⟧ }
- // All characters should have codes
- assert_eq!(codes.len(), 7);
-
- // Verify roundtrip
- let decoded = huffman_decode(&encoded, &codes);
- assert_eq!(decoded, text);
- }
-
#[test]
fn test_build_frequency_map() {
let frequencies = build_frequency_map("hello");
@@ -498,33 +315,12 @@
fn test_demonstrate_huffman_from_file() {
use std::fs::File;
use std::io::Write;
-
- // Create a temporary test file
- let test_file = "/tmp/huffman_test.txt";
- let test_content = "The quick brown fox jumps over the lazy dog";
-
- {
- let mut file = File::create(test_file).unwrap();
- file.write_all(test_content.as_bytes()).unwrap();
- }
-
- // Test the demonstrate function
- let result = demonstrate_huffman_from_file(test_file);
+ { … 12 line(s) … ⟦tj:fd25005adf28e082faa828e72fdc7e69⟧ }
assert!(result.is_ok());
- }
+}
#[test]
- fn test_demonstrate_empty_file() {
- use std::fs::File;
-
- // Create an empty test file
- let test_file = "/tmp/huffman_empty.txt";
- File::create(test_file).unwrap();
-
- // Test with empty file
- let result = demonstrate_huffman_from_file(test_file);
- assert!(result.is_ok());
- }
+ fn test_demonstrate_empty_file() { … 11 line(s) … ⟦tj:1df06dbde8733d172cd00ee10b4737e0⟧ }
}
/// Main function for command-line usage
@@ -565,3 +361,6 @@
}
}
}
+[omitted blocks are individually retrievable: call tinyjuice_retrieve with the token inside an omission marker to expand just that block]
+
+[PARTIAL view — full original (16293 bytes): call tinyjuice_retrieve with token "e84401ece504123913332f21543191c2"]
\ No newline at end of file