Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor(arena): use slice::as_ptr_range in Arena::get_node_id #108

Merged
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 15 additions & 11 deletions src/arena.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ use alloc::vec::Vec;

#[cfg(not(feature = "std"))]
use core::{
mem,
num::NonZeroUsize,
ops::{Index, IndexMut},
};
Expand All @@ -17,6 +18,7 @@ use serde::{Deserialize, Serialize};

#[cfg(feature = "std")]
use std::{
mem,
num::NonZeroUsize,
ops::{Index, IndexMut},
};
Expand Down Expand Up @@ -79,18 +81,20 @@ 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) / mem::size_of::<Node<T>>();
let node_id = NonZeroUsize::new(node_index.wrapping_add(1))?;

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
Loading