|
|
@@ -44,6 +44,14 @@ impl Hufftree {
|
|
|
pub fn get_character_code(&self, character: char) -> Result<BitVec, &str> {
|
|
|
match self.root.get_character_code(character) {
|
|
|
Ok(code) => {
|
|
|
+ if code.is_empty() {
|
|
|
+ // Single-character alphabet: the root is the only node, so the
|
|
|
+ // recursive walk returns no bits. Assign a 1-bit code so the
|
|
|
+ // encoded text is non-empty and decodable.
|
|
|
+ let mut single = BitVec::new();
|
|
|
+ single.push(false);
|
|
|
+ return Ok(single);
|
|
|
+ }
|
|
|
let code = code.iter().rev().collect();
|
|
|
Ok(code)
|
|
|
}
|
|
|
@@ -116,6 +124,19 @@ mod test {
|
|
|
assert_eq!(c_code.to_string(), "00");
|
|
|
}
|
|
|
|
|
|
+ #[test]
|
|
|
+ fn single_character_alphabet_roundtrip() {
|
|
|
+ let mut chars_and_freq: HashMap<char, i32> = HashMap::new();
|
|
|
+ chars_and_freq.insert('a', 5);
|
|
|
+
|
|
|
+ let huff = Hufftree::new(chars_and_freq);
|
|
|
+ let code = huff.get_character_code('a').unwrap();
|
|
|
+ assert_eq!(code.len(), 1);
|
|
|
+
|
|
|
+ let encoded = huff.convert_text("aaaaa".to_string()).unwrap();
|
|
|
+ assert_eq!(encoded.len(), 5);
|
|
|
+ }
|
|
|
+
|
|
|
#[test]
|
|
|
fn get_charcter_freq() {
|
|
|
let text = String::from("aaaaaabb cc");
|