use crate::{alloc::Flags, bindings, container_of, error::Result, prelude::*};
use core::{
cmp::{Ord, Ordering},
marker::PhantomData,
mem::MaybeUninit,
ptr::{addr_of_mut, from_mut, NonNull},
};
pub struct RBTree<K, V> {
root: bindings::rb_root,
_p: PhantomData<Node<K, V>>,
}
unsafe impl<K: Send, V: Send> Send for RBTree<K, V> {}
unsafe impl<K: Sync, V: Sync> Sync for RBTree<K, V> {}
impl<K, V> RBTree<K, V> {
pub fn new() -> Self {
Self {
root: bindings::rb_root::default(),
_p: PhantomData,
}
}
#[inline]
pub fn is_empty(&self) -> bool {
self.root.rb_node.is_null()
}
pub fn iter(&self) -> Iter<'_, K, V> {
Iter {
_tree: PhantomData,
iter_raw: IterRaw {
next: unsafe { bindings::rb_first(&self.root) },
_phantom: PhantomData,
},
}
}
pub fn iter_mut(&mut self) -> IterMut<'_, K, V> {
IterMut {
_tree: PhantomData,
iter_raw: IterRaw {
next: unsafe { bindings::rb_first(from_mut(&mut self.root)) },
_phantom: PhantomData,
},
}
}
pub fn keys(&self) -> impl Iterator<Item = &'_ K> {
self.iter().map(|(k, _)| k)
}
pub fn values(&self) -> impl Iterator<Item = &'_ V> {
self.iter().map(|(_, v)| v)
}
pub fn values_mut(&mut self) -> impl Iterator<Item = &'_ mut V> {
self.iter_mut().map(|(_, v)| v)
}
pub fn cursor_front_mut(&mut self) -> Option<CursorMut<'_, K, V>> {
let root = addr_of_mut!(self.root);
let current = unsafe { bindings::rb_first(root) };
NonNull::new(current).map(|current| {
CursorMut {
current,
tree: self,
}
})
}
pub fn cursor_front(&self) -> Option<Cursor<'_, K, V>> {
let root = &raw const self.root;
let current = unsafe { bindings::rb_first(root) };
NonNull::new(current).map(|current| {
Cursor {
current,
_tree: PhantomData,
}
})
}
pub fn cursor_back_mut(&mut self) -> Option<CursorMut<'_, K, V>> {
let root = addr_of_mut!(self.root);
let current = unsafe { bindings::rb_last(root) };
NonNull::new(current).map(|current| {
CursorMut {
current,
tree: self,
}
})
}
pub fn cursor_back(&self) -> Option<Cursor<'_, K, V>> {
let root = &raw const self.root;
let current = unsafe { bindings::rb_last(root) };
NonNull::new(current).map(|current| {
Cursor {
current,
_tree: PhantomData,
}
})
}
}
impl<K, V> RBTree<K, V>
where
K: Ord,
{
pub fn try_create_and_insert(
&mut self,
key: K,
value: V,
flags: Flags,
) -> Result<Option<RBTreeNode<K, V>>> {
Ok(self.insert(RBTreeNode::new(key, value, flags)?))
}
pub fn insert(&mut self, node: RBTreeNode<K, V>) -> Option<RBTreeNode<K, V>> {
match self.raw_entry(&node.node.key) {
RawEntry::Occupied(entry) => Some(entry.replace(node)),
RawEntry::Vacant(entry) => {
entry.insert(node);
None
}
}
}
fn raw_entry(&mut self, key: &K) -> RawEntry<'_, K, V> {
let raw_self: *mut RBTree<K, V> = self;
let mut parent = core::ptr::null_mut();
let mut child_field_of_parent: &mut *mut bindings::rb_node =
unsafe { &mut (*raw_self).root.rb_node };
while !(*child_field_of_parent).is_null() {
let curr = *child_field_of_parent;
let node = unsafe { container_of!(curr, Node<K, V>, links) };
match key.cmp(unsafe { &(*node).key }) {
Ordering::Less => child_field_of_parent = unsafe { &mut (*curr).rb_left },
Ordering::Greater => child_field_of_parent = unsafe { &mut (*curr).rb_right },
Ordering::Equal => {
return RawEntry::Occupied(OccupiedEntry {
rbtree: self,
node_links: curr,
})
}
}
parent = curr;
}
RawEntry::Vacant(RawVacantEntry {
rbtree: raw_self,
parent,
child_field_of_parent,
_phantom: PhantomData,
})
}
pub fn entry(&mut self, key: K) -> Entry<'_, K, V> {
match self.raw_entry(&key) {
RawEntry::Occupied(entry) => Entry::Occupied(entry),
RawEntry::Vacant(entry) => Entry::Vacant(VacantEntry { raw: entry, key }),
}
}
pub fn find_mut(&mut self, key: &K) -> Option<OccupiedEntry<'_, K, V>> {
match self.raw_entry(key) {
RawEntry::Occupied(entry) => Some(entry),
RawEntry::Vacant(_entry) => None,
}
}
pub fn get(&self, key: &K) -> Option<&V> {
let mut node = self.root.rb_node;
while !node.is_null() {
let this = unsafe { container_of!(node, Node<K, V>, links) };
let this_ref = unsafe { &*this };
let node_ref = unsafe { &*node };
node = match key.cmp(&this_ref.key) {
Ordering::Less => node_ref.rb_left,
Ordering::Greater => node_ref.rb_right,
Ordering::Equal => return Some(&this_ref.value),
}
}
None
}
pub fn get_mut(&mut self, key: &K) -> Option<&mut V> {
self.find_mut(key).map(|node| node.into_mut())
}
pub fn remove_node(&mut self, key: &K) -> Option<RBTreeNode<K, V>> {
self.find_mut(key).map(OccupiedEntry::remove_node)
}
pub fn remove(&mut self, key: &K) -> Option<V> {
self.find_mut(key).map(OccupiedEntry::remove)
}
pub fn cursor_lower_bound_mut(&mut self, key: &K) -> Option<CursorMut<'_, K, V>>
where
K: Ord,
{
let best = self.find_best_match(key)?;
NonNull::new(best.as_ptr()).map(|current| {
CursorMut {
current,
tree: self,
}
})
}
pub fn cursor_lower_bound(&self, key: &K) -> Option<Cursor<'_, K, V>>
where
K: Ord,
{
let best = self.find_best_match(key)?;
NonNull::new(best.as_ptr()).map(|current| {
Cursor {
current,
_tree: PhantomData,
}
})
}
fn find_best_match(&self, key: &K) -> Option<NonNull<bindings::rb_node>> {
let mut node = self.root.rb_node;
let mut best_key: Option<&K> = None;
let mut best_links: Option<NonNull<bindings::rb_node>> = None;
while !node.is_null() {
let this = unsafe { container_of!(node, Node<K, V>, links) };
let this_key = unsafe { &(*this).key };
let node_ref = unsafe { &*node };
match key.cmp(this_key) {
Ordering::Equal => {
best_links = Some(unsafe { NonNull::new_unchecked(&mut (*this).links) });
break;
}
Ordering::Greater => {
node = node_ref.rb_right;
}
Ordering::Less => {
let is_better_match = match best_key {
None => true,
Some(best) => best > this_key,
};
if is_better_match {
best_key = Some(this_key);
best_links = Some(unsafe { NonNull::new_unchecked(&mut (*this).links) });
}
node = node_ref.rb_left;
}
};
}
best_links
}
}
impl<K, V> Default for RBTree<K, V> {
fn default() -> Self {
Self::new()
}
}
impl<K, V> Drop for RBTree<K, V> {
fn drop(&mut self) {
let mut next = unsafe { bindings::rb_first_postorder(&self.root) };
while !next.is_null() {
let this = unsafe { container_of!(next, Node<K, V>, links) };
next = unsafe { bindings::rb_next_postorder(next) };
unsafe { drop(KBox::from_raw(this)) };
}
}
}
pub struct CursorMut<'a, K, V> {
tree: &'a mut RBTree<K, V>,
current: NonNull<bindings::rb_node>,
}
pub struct Cursor<'a, K, V> {
_tree: PhantomData<&'a RBTree<K, V>>,
current: NonNull<bindings::rb_node>,
}
unsafe impl<'a, K: Sync, V: Sync> Send for Cursor<'a, K, V> {}
unsafe impl<'a, K: Sync, V: Sync> Sync for Cursor<'a, K, V> {}
impl<'a, K, V> Cursor<'a, K, V> {
pub fn current(&self) -> (&K, &V) {
unsafe { Self::to_key_value(self.current) }
}
unsafe fn to_key_value<'b>(node: NonNull<bindings::rb_node>) -> (&'b K, &'b V) {
let this = unsafe { container_of!(node.as_ptr(), Node<K, V>, links) };
let k = unsafe { &(*this).key };
let v = unsafe { &(*this).value };
(k, v)
}
pub fn peek_prev(&self) -> Option<(&K, &V)> {
self.peek(Direction::Prev)
}
pub fn peek_next(&self) -> Option<(&K, &V)> {
self.peek(Direction::Next)
}
fn peek(&self, direction: Direction) -> Option<(&K, &V)> {
self.get_neighbor_raw(direction).map(|neighbor| {
unsafe { Self::to_key_value(neighbor) }
})
}
fn get_neighbor_raw(&self, direction: Direction) -> Option<NonNull<bindings::rb_node>> {
let neighbor = unsafe {
match direction {
Direction::Prev => bindings::rb_prev(self.current.as_ptr()),
Direction::Next => bindings::rb_next(self.current.as_ptr()),
}
};
NonNull::new(neighbor)
}
}
unsafe impl<'a, K: Send, V: Send> Send for CursorMut<'a, K, V> {}
unsafe impl<'a, K: Sync, V: Sync> Sync for CursorMut<'a, K, V> {}
impl<'a, K, V> CursorMut<'a, K, V> {
pub fn current(&self) -> (&K, &V) {
unsafe { Self::to_key_value(self.current) }
}
pub fn current_mut(&mut self) -> (&K, &mut V) {
unsafe { Self::to_key_value_mut(self.current) }
}
pub fn remove_current(self) -> (Option<Self>, RBTreeNode<K, V>) {
let prev = self.get_neighbor_raw(Direction::Prev);
let next = self.get_neighbor_raw(Direction::Next);
let this = unsafe { container_of!(self.current.as_ptr(), Node<K, V>, links) };
let node = unsafe { KBox::from_raw(this) };
let node = RBTreeNode { node };
unsafe { bindings::rb_erase(&mut (*this).links, addr_of_mut!(self.tree.root)) };
let cursor = next.or(prev).map(|current| Self {
current,
tree: self.tree,
});
(cursor, node)
}
pub fn remove_prev(&mut self) -> Option<RBTreeNode<K, V>> {
self.remove_neighbor(Direction::Prev)
}
pub fn remove_next(&mut self) -> Option<RBTreeNode<K, V>> {
self.remove_neighbor(Direction::Next)
}
fn remove_neighbor(&mut self, direction: Direction) -> Option<RBTreeNode<K, V>> {
if let Some(neighbor) = self.get_neighbor_raw(direction) {
let neighbor = neighbor.as_ptr();
unsafe { bindings::rb_erase(neighbor, addr_of_mut!(self.tree.root)) };
let this = unsafe { container_of!(neighbor, Node<K, V>, links) };
let node = unsafe { KBox::from_raw(this) };
return Some(RBTreeNode { node });
}
None
}
pub fn move_prev(self) -> Option<Self> {
self.mv(Direction::Prev)
}
pub fn move_next(self) -> Option<Self> {
self.mv(Direction::Next)
}
fn mv(self, direction: Direction) -> Option<Self> {
self.get_neighbor_raw(direction).map(|neighbor| Self {
tree: self.tree,
current: neighbor,
})
}
pub fn peek_prev(&self) -> Option<(&K, &V)> {
self.peek(Direction::Prev)
}
pub fn peek_next(&self) -> Option<(&K, &V)> {
self.peek(Direction::Next)
}
fn peek(&self, direction: Direction) -> Option<(&K, &V)> {
self.get_neighbor_raw(direction).map(|neighbor| {
unsafe { Self::to_key_value(neighbor) }
})
}
pub fn peek_prev_mut(&mut self) -> Option<(&K, &mut V)> {
self.peek_mut(Direction::Prev)
}
pub fn peek_next_mut(&mut self) -> Option<(&K, &mut V)> {
self.peek_mut(Direction::Next)
}
fn peek_mut(&mut self, direction: Direction) -> Option<(&K, &mut V)> {
self.get_neighbor_raw(direction).map(|neighbor| {
unsafe { Self::to_key_value_mut(neighbor) }
})
}
fn get_neighbor_raw(&self, direction: Direction) -> Option<NonNull<bindings::rb_node>> {
let neighbor = unsafe {
match direction {
Direction::Prev => bindings::rb_prev(self.current.as_ptr()),
Direction::Next => bindings::rb_next(self.current.as_ptr()),
}
};
NonNull::new(neighbor)
}
unsafe fn to_key_value<'b>(node: NonNull<bindings::rb_node>) -> (&'b K, &'b V) {
let (k, v) = unsafe { Self::to_key_value_raw(node) };
(k, unsafe { &*v })
}
unsafe fn to_key_value_mut<'b>(node: NonNull<bindings::rb_node>) -> (&'b K, &'b mut V) {
let (k, v) = unsafe { Self::to_key_value_raw(node) };
(k, unsafe { &mut *v })
}
unsafe fn to_key_value_raw<'b>(node: NonNull<bindings::rb_node>) -> (&'b K, *mut V) {
let this = unsafe { container_of!(node.as_ptr(), Node<K, V>, links) };
let k = unsafe { &(*this).key };
let v = unsafe { addr_of_mut!((*this).value) };
(k, v)
}
}
enum Direction {
Prev,
Next,
}
impl<'a, K, V> IntoIterator for &'a RBTree<K, V> {
type Item = (&'a K, &'a V);
type IntoIter = Iter<'a, K, V>;
fn into_iter(self) -> Self::IntoIter {
self.iter()
}
}
pub struct Iter<'a, K, V> {
_tree: PhantomData<&'a RBTree<K, V>>,
iter_raw: IterRaw<K, V>,
}
unsafe impl<'a, K: Sync, V: Sync> Send for Iter<'a, K, V> {}
unsafe impl<'a, K: Sync, V: Sync> Sync for Iter<'a, K, V> {}
impl<'a, K, V> Iterator for Iter<'a, K, V> {
type Item = (&'a K, &'a V);
fn next(&mut self) -> Option<Self::Item> {
self.iter_raw.next().map(|(k, v)| unsafe { (&*k, &*v) })
}
}
impl<'a, K, V> IntoIterator for &'a mut RBTree<K, V> {
type Item = (&'a K, &'a mut V);
type IntoIter = IterMut<'a, K, V>;
fn into_iter(self) -> Self::IntoIter {
self.iter_mut()
}
}
pub struct IterMut<'a, K, V> {
_tree: PhantomData<&'a mut RBTree<K, V>>,
iter_raw: IterRaw<K, V>,
}
unsafe impl<'a, K: Send, V: Send> Send for IterMut<'a, K, V> {}
unsafe impl<'a, K: Sync, V: Sync> Sync for IterMut<'a, K, V> {}
impl<'a, K, V> Iterator for IterMut<'a, K, V> {
type Item = (&'a K, &'a mut V);
fn next(&mut self) -> Option<Self::Item> {
self.iter_raw.next().map(|(k, v)|
unsafe { (&*k, &mut *v) })
}
}
struct IterRaw<K, V> {
next: *mut bindings::rb_node,
_phantom: PhantomData<fn() -> (K, V)>,
}
impl<K, V> Iterator for IterRaw<K, V> {
type Item = (*mut K, *mut V);
fn next(&mut self) -> Option<Self::Item> {
if self.next.is_null() {
return None;
}
let cur = unsafe { container_of!(self.next, Node<K, V>, links) };
self.next = unsafe { bindings::rb_next(self.next) };
Some(unsafe { (addr_of_mut!((*cur).key), addr_of_mut!((*cur).value)) })
}
}
pub struct RBTreeNodeReservation<K, V> {
node: KBox<MaybeUninit<Node<K, V>>>,
}
impl<K, V> RBTreeNodeReservation<K, V> {
pub fn new(flags: Flags) -> Result<RBTreeNodeReservation<K, V>> {
Ok(RBTreeNodeReservation {
node: KBox::new_uninit(flags)?,
})
}
}
unsafe impl<K, V> Send for RBTreeNodeReservation<K, V> {}
unsafe impl<K, V> Sync for RBTreeNodeReservation<K, V> {}
impl<K, V> RBTreeNodeReservation<K, V> {
pub fn into_node(self, key: K, value: V) -> RBTreeNode<K, V> {
let node = KBox::write(
self.node,
Node {
key,
value,
links: bindings::rb_node::default(),
},
);
RBTreeNode { node }
}
}
pub struct RBTreeNode<K, V> {
node: KBox<Node<K, V>>,
}
impl<K, V> RBTreeNode<K, V> {
pub fn new(key: K, value: V, flags: Flags) -> Result<RBTreeNode<K, V>> {
Ok(RBTreeNodeReservation::new(flags)?.into_node(key, value))
}
pub fn to_key_value(self) -> (K, V) {
let node = KBox::into_inner(self.node);
(node.key, node.value)
}
}
unsafe impl<K: Send, V: Send> Send for RBTreeNode<K, V> {}
unsafe impl<K: Sync, V: Sync> Sync for RBTreeNode<K, V> {}
impl<K, V> RBTreeNode<K, V> {
pub fn into_reservation(self) -> RBTreeNodeReservation<K, V> {
RBTreeNodeReservation {
node: KBox::drop_contents(self.node),
}
}
}
pub enum Entry<'a, K, V> {
Vacant(VacantEntry<'a, K, V>),
Occupied(OccupiedEntry<'a, K, V>),
}
enum RawEntry<'a, K, V> {
Vacant(RawVacantEntry<'a, K, V>),
Occupied(OccupiedEntry<'a, K, V>),
}
pub struct VacantEntry<'a, K, V> {
key: K,
raw: RawVacantEntry<'a, K, V>,
}
struct RawVacantEntry<'a, K, V> {
rbtree: *mut RBTree<K, V>,
parent: *mut bindings::rb_node,
child_field_of_parent: *mut *mut bindings::rb_node,
_phantom: PhantomData<&'a mut RBTree<K, V>>,
}
impl<'a, K, V> RawVacantEntry<'a, K, V> {
fn insert(self, node: RBTreeNode<K, V>) -> &'a mut V {
let node = KBox::into_raw(node.node);
let node_links = unsafe { addr_of_mut!((*node).links) };
unsafe { bindings::rb_link_node(node_links, self.parent, self.child_field_of_parent) };
unsafe { bindings::rb_insert_color(node_links, addr_of_mut!((*self.rbtree).root)) };
unsafe { &mut (*node).value }
}
}
impl<'a, K, V> VacantEntry<'a, K, V> {
pub fn insert(self, value: V, reservation: RBTreeNodeReservation<K, V>) -> &'a mut V {
self.raw.insert(reservation.into_node(self.key, value))
}
}
pub struct OccupiedEntry<'a, K, V> {
rbtree: &'a mut RBTree<K, V>,
node_links: *mut bindings::rb_node,
}
impl<'a, K, V> OccupiedEntry<'a, K, V> {
pub fn get(&self) -> &V {
unsafe { &(*container_of!(self.node_links, Node<K, V>, links)).value }
}
pub fn get_mut(&mut self) -> &mut V {
unsafe { &mut (*(container_of!(self.node_links, Node<K, V>, links))).value }
}
pub fn into_mut(self) -> &'a mut V {
unsafe { &mut (*(container_of!(self.node_links, Node<K, V>, links))).value }
}
pub fn remove_node(self) -> RBTreeNode<K, V> {
unsafe { bindings::rb_erase(self.node_links, &mut self.rbtree.root) };
RBTreeNode {
node: unsafe { KBox::from_raw(container_of!(self.node_links, Node<K, V>, links)) },
}
}
pub fn remove(self) -> V {
let rb_node = self.remove_node();
let node = KBox::into_inner(rb_node.node);
node.value
}
fn replace(self, node: RBTreeNode<K, V>) -> RBTreeNode<K, V> {
let node = KBox::into_raw(node.node);
let new_node_links = unsafe { addr_of_mut!((*node).links) };
unsafe {
bindings::rb_replace_node(self.node_links, new_node_links, &mut self.rbtree.root)
};
let old_node = unsafe { KBox::from_raw(container_of!(self.node_links, Node<K, V>, links)) };
RBTreeNode { node: old_node }
}
}
struct Node<K, V> {
links: bindings::rb_node,
key: K,
value: V,
}