From 2cbf824e19ddbe21b8a951f68e75ea61686c351c Mon Sep 17 00:00:00 2001 From: Shane Celis Date: Sun, 12 May 2024 15:23:14 -0400 Subject: [PATCH] bug: Fix order dependent value erasure. This fixes issue#32. --- .../naive_trie/naive_trie_impl.rs | 10 ++++---- src/map/trie.rs | 25 +++++++++++++++++++ 2 files changed, 30 insertions(+), 5 deletions(-) diff --git a/src/internal_data_structure/naive_trie/naive_trie_impl.rs b/src/internal_data_structure/naive_trie/naive_trie_impl.rs index 0e01b6c..e1bc136 100644 --- a/src/internal_data_structure/naive_trie/naive_trie_impl.rs +++ b/src/internal_data_structure/naive_trie/naive_trie_impl.rs @@ -17,8 +17,6 @@ impl<'trie, Label: Ord, Value> NaiveTrie { pub fn push>(&'trie mut self, word: Arr, value: Value) { let mut trie = self; - let mut value = Some(value); - let mut word = word.peekable(); while let Some(chr) = word.next() { let res = trie .children() @@ -32,9 +30,7 @@ impl<'trie, Label: Ord, Value> NaiveTrie { }; } Err(j) => { - let is_terminal = word.peek().is_none(); - let child_trie = - Self::make_interm_or_leaf(chr, is_terminal.then(|| value.take().unwrap())); + let child_trie = Self::make_interm_or_leaf(chr, None); trie = match trie { NaiveTrie::Root(node) => { node.children.insert(j, child_trie); @@ -49,6 +45,10 @@ impl<'trie, Label: Ord, Value> NaiveTrie { } }; } + match trie { + NaiveTrie::IntermOrLeaf(node) => node.value = Some(value), + _ => panic!("Unexpected type"), + } } pub fn children(&self) -> &[Self] { diff --git a/src/map/trie.rs b/src/map/trie.rs index c92359f..ee44b81 100644 --- a/src/map/trie.rs +++ b/src/map/trie.rs @@ -341,6 +341,31 @@ mod search_tests { let _ = trie.common_prefix_search::("").next(); } + #[test] + fn insert_order_dependent() { + let trie = Trie::from_iter([("a", 0), ("app", 1), ("apple", 2)]); + let results: Vec<(String, &u8)> = trie.iter().collect(); + assert_eq!( + results, + [ + ("a".to_string(), &0u8), + ("app".to_string(), &1u8), + ("apple".to_string(), &2u8) + ] + ); + + let trie = Trie::from_iter([("a", 0), ("apple", 2), ("app", 1)]); + let results: Vec<(String, &u8)> = trie.iter().collect(); + assert_eq!( + results, + [ + ("a".to_string(), &0u8), + ("app".to_string(), &1u8), + ("apple".to_string(), &2u8) + ] + ); + } + mod exact_match_tests { macro_rules! parameterized_tests { ($($name:ident: $value:expr,)*) => {