Skip to content

Commit

Permalink
refactor(arena): use slice::as_ptr_range in Arena::get_node_id
Browse files Browse the repository at this point in the history
Also changed up the control flow to reduce nesting, which is purely a style preference.
  • Loading branch information
alexmozaidze authored and saschagrunert committed Jun 25, 2024
1 parent cd3d680 commit 83be098
Showing 1 changed file with 12 additions and 11 deletions.
23 changes: 12 additions & 11 deletions src/arena.rs
Original file line number Diff line number Diff line change
Expand Up @@ -79,18 +79,19 @@ impl<T> Arena<T> {
/// assert_eq!(*arena[node_id].get(), "foo");
/// ```
pub fn get_node_id(&self, node: &Node<T>) -> Option<NodeId> {
// self.nodes.as_ptr_range() is not stable until rust 1.48
let start = self.nodes.as_ptr() as usize;
let end = start + self.nodes.len() * core::mem::size_of::<Node<T>>();
let p = node as *const Node<T> as usize;
if (start..end).contains(&p) {
let node_id = (p - start) / core::mem::size_of::<Node<T>>();
NonZeroUsize::new(node_id.wrapping_add(1)).map(|node_id_non_zero| {
NodeId::from_non_zero_usize(node_id_non_zero, self.nodes[node_id].stamp)
})
} else {
None
let nodes_range = self.nodes.as_ptr_range();
let p = node as *const Node<T>;

if !nodes_range.contains(&p) {
return None;
}

let node_index = (p as usize - nodes_range.start as usize) / core::mem::size_of::<Node<T>>();
let Some(node_id) = NonZeroUsize::new(node_index.wrapping_add(1)) else {
return None;
};

Some(NodeId::from_non_zero_usize(node_id, self.nodes[node_index].stamp))
}

/// Retrieves the `NodeId` corresponding to the `Node` at `index` in the `Arena`, if it exists.
Expand Down

0 comments on commit 83be098

Please sign in to comment.