From 88577bd7700cdbbc59defa9d6b54e1c5de3fac2f Mon Sep 17 00:00:00 2001 From: Farhan Date: Wed, 24 Apr 2024 12:36:48 +0530 Subject: [PATCH] fix: sorting in flatnode --- src/art.rs | 4 +--- src/node.rs | 30 +++++++++++++++++++++++++++--- 2 files changed, 28 insertions(+), 6 deletions(-) diff --git a/src/art.rs b/src/art.rs index 4e6e424..43a01b6 100644 --- a/src/art.rs +++ b/src/art.rs @@ -588,9 +588,7 @@ impl Node { }; // 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? diff --git a/src/node.rs b/src/node.rs index 942dae5..9ed98d6 100644 --- a/src/node.rs +++ b/src/node.rs @@ -171,9 +171,7 @@ impl FlatNode } fn find_pos(&self, key: u8) -> Option { - 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)) } @@ -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 { @@ -1156,4 +1155,29 @@ mod tests { assert!(std::mem::size_of::, usize, 4>>() <= 64); assert!(std::mem::size_of::, usize, 16>>() <= 64); } + + #[test] + fn verify_node_insert_order() { + let dummy_prefix: FixedSizeKey<8> = FixedSizeKey::create_key("foo".as_bytes()); + + let mut node4 = FlatNode::, 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::, usize, 16>::new(dummy_prefix.clone()); + // Insert children into node16 in random order + let mut rng = rand::thread_rng(); + let mut values: Vec = (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::>()); + } }