Skip to content

Commit

Permalink
refactor: rename trie.get_value() to trie.get() and return a refe…
Browse files Browse the repository at this point in the history
…rence to the value instead of the value to be closer to hashmap API

BREAKING CHANGE: function `trie.get_value()` not available anymore
  • Loading branch information
vemonet committed Dec 22, 2023
1 parent e06dd4c commit fd1e530
Show file tree
Hide file tree
Showing 3 changed files with 13 additions and 9 deletions.
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -87,8 +87,8 @@ trie.insert("applet".bytes(), "Applet");

assert!(trie.contains_key("app".bytes()));
assert!(!trie.contains_key("not_existing_key".bytes()));
assert_eq!(trie.get_value("app".bytes()), Some("App"));
assert_eq!(trie.get_value("none".bytes()), None);
assert_eq!(trie.get("app".bytes()), Some("App").as_ref());
assert_eq!(trie.get("none".bytes()), None);

for (k, v) in trie.iter() {
println!("kv: {:?} {}", k, v);
Expand Down
16 changes: 9 additions & 7 deletions src/trie.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
//! Struct and functions for the `Trie` data structure
use crate::error::TrieError;
use crate::trie_node::TrieNode;
#[cfg(feature = "serde")]
Expand Down Expand Up @@ -153,17 +155,17 @@ impl<K: Eq + Ord + Clone, V: Clone> Trie<K, V> {
/// let mut t = Trie::new();
/// let data = "test".bytes();
/// let another_data = "notintest".bytes();
/// assert_eq!(t.get_value(data.clone()), None);
/// assert_eq!(t.get(data.clone()), None);
/// t.insert(data.clone(), 42);
///
/// assert_eq!(t.get_value(data), Some(42));
/// assert_eq!(t.get_value(another_data), None);
/// assert_eq!(t.get(data), Some(42).as_ref());
/// assert_eq!(t.get(another_data), None);
/// ```
pub fn get_value<I: Iterator<Item = K>>(&self, key: I) -> Option<V> {
pub fn get<I: Iterator<Item = K>>(&self, key: I) -> Option<&V> {
self.find_node(key)
.and_then(|node_id| self.nodes[node_id].get_value())
.and_then(|value_id| self.values.get(value_id))
.cloned()
// .cloned()
}

/// Sets the value pointed by a key
Expand All @@ -179,9 +181,9 @@ impl<K: Eq + Ord + Clone, V: Clone> Trie<K, V> {
///
/// t.insert(data.clone(), 42);
///
/// assert_eq!(t.get_value(data.clone()), Some(42));
/// assert_eq!(t.get(data.clone()), Some(42).as_ref());
/// assert!(t.set_value(data.clone(), 43).is_ok());
/// assert_eq!(t.get_value(data), Some(43));
/// assert_eq!(t.get(data), Some(43).as_ref());
/// assert!(t.set_value(another_data, 39)
/// .map_err(|e| assert!(e.to_string().starts_with("Key not found")))
/// .is_err());
Expand Down
2 changes: 2 additions & 0 deletions src/trie_node.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
//! Struct and functions for the `Trie` nodes
#[cfg(feature = "serde")]
use serde::{Deserialize, Serialize};
use std::clone::Clone;
Expand Down

0 comments on commit fd1e530

Please sign in to comment.