Skip to content

Commit

Permalink
Update Node::{insert(), get()} to handle String key correctly
Browse files Browse the repository at this point in the history
  • Loading branch information
sile committed Nov 30, 2023
1 parent d2ec1a6 commit c41401d
Show file tree
Hide file tree
Showing 3 changed files with 9 additions and 10 deletions.
2 changes: 1 addition & 1 deletion src/map.rs
Original file line number Diff line number Diff line change
Expand Up @@ -145,7 +145,7 @@ impl<K: Bytes, V> GenericPatriciaMap<K, V> {
/// assert_eq!(map.get("bar"), None);
/// ```
pub fn get<Q: AsRef<K::Borrowed>>(&self, key: Q) -> Option<&V> {
self.tree.get(key.as_ref().as_bytes())
self.tree.get(key.as_ref())
}

/// Returns a mutable reference to the value corresponding to the key.
Expand Down
15 changes: 7 additions & 8 deletions src/node.rs
Original file line number Diff line number Diff line change
Expand Up @@ -405,21 +405,21 @@ impl<V> Node<V> {
}
}

pub(crate) fn get(&self, key: &[u8]) -> Option<&V> {
let common_prefix_len = self.skip_common_prefix(key);
let next = &key[common_prefix_len..];
pub(crate) fn get<K: ?Sized + BorrowedBytes>(&self, key: &K) -> Option<&V> {
let (next, common_prefix_len) = key.strip_common_prefix_and_len(self.label());
if common_prefix_len == self.label().len() {
if next.is_empty() {
if next.as_bytes().is_empty() {
self.value()
} else {
self.child().and_then(|child| child.get(next))
}
} else if common_prefix_len == 0 && self.label().first() <= key.first() {
} else if common_prefix_len == 0 && key.cmp_first_item(self.label()).is_ge() {
self.sibling().and_then(|sibling| sibling.get(next))
} else {
None
}
}

pub(crate) fn get_mut(&mut self, key: &[u8]) -> Option<&mut V> {
let common_prefix_len = self.skip_common_prefix(key);
let next = &key[common_prefix_len..];
Expand Down Expand Up @@ -583,7 +583,7 @@ impl<V> Node<V> {
}
}
pub(crate) fn insert<K: ?Sized + BorrowedBytes>(&mut self, key: &K, value: V) -> Option<V> {
if self.label().first() > key.as_bytes().first() {
if key.cmp_first_item(self.label()).is_lt() {
let this = Node {
ptr: self.ptr,
_value: PhantomData,
Expand All @@ -594,8 +594,7 @@ impl<V> Node<V> {
return None;
}

let next = key.strip_common_prefix(self.label());
let common_prefix_len = key.as_bytes().len() - next.as_bytes().len();
let (next, common_prefix_len) = key.strip_common_prefix_and_len(self.label());
let is_label_matched = common_prefix_len == self.label().len();
if next.as_bytes().is_empty() {
if is_label_matched {
Expand Down
2 changes: 1 addition & 1 deletion src/tree.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ impl<V> PatriciaTree<V> {
None
}
}
pub fn get(&self, key: &[u8]) -> Option<&V> {
pub fn get<K: ?Sized + BorrowedBytes>(&self, key: &K) -> Option<&V> {
self.root.get(key)
}
pub fn get_mut(&mut self, key: &[u8]) -> Option<&mut V> {
Expand Down

0 comments on commit c41401d

Please sign in to comment.