Skip to content

Commit

Permalink
fix: sorting in flatnode
Browse files Browse the repository at this point in the history
  • Loading branch information
arriqaaq authored Apr 24, 2024
1 parent a8ac628 commit 88577bd
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 6 deletions.
4 changes: 1 addition & 3 deletions src/art.rs
Original file line number Diff line number Diff line change
Expand Up @@ -588,9 +588,7 @@ impl<P: KeyTrait + Clone, V: Clone> Node<P, V> {
};

// Get the value from the TwigNode instance by the specified version.
let Some(val) = twig.get_leaf_by_version(version) else {
return None;
};
let val = twig.get_leaf_by_version(version)?;

// Return the retrieved key, value, and version as a tuple.
// TODO: should return copy of value or reference?
Expand Down
30 changes: 27 additions & 3 deletions src/node.rs
Original file line number Diff line number Diff line change
Expand Up @@ -171,9 +171,7 @@ impl<P: KeyTrait + Clone, N: Version, const WIDTH: usize> FlatNode<P, N, WIDTH>
}

fn find_pos(&self, key: u8) -> Option<usize> {
let idx = (0..self.num_children as usize)
.rev()
.find(|&i| key < self.keys[i]);
let idx = (0..self.num_children as usize).find(|&i| key < self.keys[i]);
idx.or(Some(self.num_children as usize))
}

Expand Down Expand Up @@ -673,6 +671,7 @@ mod tests {
use crate::FixedSizeKey;

use super::{FlatNode, Node256, Node48, NodeTrait, TwigNode, Version};
use rand::prelude::SliceRandom;
use std::sync::Arc;

macro_rules! impl_timestamp {
Expand Down Expand Up @@ -1156,4 +1155,29 @@ mod tests {
assert!(std::mem::size_of::<FlatNode::<FixedSizeKey<8>, usize, 4>>() <= 64);
assert!(std::mem::size_of::<FlatNode::<FixedSizeKey<8>, usize, 16>>() <= 64);
}

#[test]
fn verify_node_insert_order() {
let dummy_prefix: FixedSizeKey<8> = FixedSizeKey::create_key("foo".as_bytes());

let mut node4 = FlatNode::<FixedSizeKey<8>, usize, 4>::new(dummy_prefix.clone());
node4 = node4.add_child(4, 1);
node4 = node4.add_child(2, 1);
node4 = node4.add_child(1, 1);
node4 = node4.add_child(0, 1);

// verify the order of keys as [0, 1, 2, 4]
assert_eq!(node4.keys, [0, 1, 2, 4]);

let mut node16 = FlatNode::<FixedSizeKey<8>, usize, 16>::new(dummy_prefix.clone());
// Insert children into node16 in random order
let mut rng = rand::thread_rng();
let mut values: Vec<u8> = (0..16).collect();
values.shuffle(&mut rng);
for value in values {
node16 = node16.add_child(value, 1);
}
// Verify the keys have been inserted in order
assert_eq!(node16.keys, *(0..16).collect::<Vec<u8>>());
}
}

0 comments on commit 88577bd

Please sign in to comment.