use super::pack;
use super::defs::*;
use super::rule::*;
pub struct RadixNode<V> {
pub path: Bytes,
pub data: Option<V>,
pub rule: RadixRule,
pub next: pack::RadixPack<V>,
}
impl<V> RadixNode<V> {
#[inline]
pub fn is_empty(&self) -> bool {
self.data.is_none()
}
#[inline]
pub fn item_ref(&self) -> Option<(&Bytes, &V)> {
self.data.as_ref().map(|data| (&self.path, data))
}
#[inline]
pub fn item_mut(&mut self) -> Option<(&Bytes, &mut V)> {
self.data.as_mut().map(|data| (&self.path, data))
}
#[inline]
pub fn iter(&self) -> Iter<V> {
Iter::from(self)
}
#[inline]
pub fn iter_mut(&mut self) -> IterMut<V> {
IterMut::from(self)
}
#[inline]
pub fn keys(&self) -> Keys<V> {
Keys::from(self)
}
#[inline]
pub fn values(&self) -> Values<V> {
Values::from(self)
}
#[inline]
pub fn values_mut(&mut self) -> ValuesMut<V> {
ValuesMut::from(self)
}
pub fn insert(&mut self, path: impl Into<Bytes>, data: V) -> RadixResult<Option<V>> {
let path = path.into();
let mut frag = path.clone();
let mut slot = self;
loop {
let next = RadixRule::try_from(frag.clone())?;
let used = next.origin().clone();
slot = slot.next.insert(next)?;
if used.len() == frag.len() {
let prev = slot.data.take();
slot.path = path;
slot.data = Some(data);
return Ok(prev);
}
frag = frag.slice(used.len()..);
}
}
pub fn lookup<'u>(&self, mut path: &'u [u8], data: bool, raw: bool, capture: &mut Vec<(Bytes, &'u [u8])>, enable: bool) -> Option<&RadixNode<V>> {
let mut current = self;
loop {
let share = match current.rule.longest(path, raw) {
Some(val) => val,
None => return None,
};
let equal = (!raw && current.rule.is_special()) || current.rule.origin().len() == share.len();
if share.len() != path.len() && !equal {
return None
}
if enable {
let ident = current.rule.identity();
if !ident.is_empty() {
capture.push((ident.clone(), share));
}
}
path = &path[share.len()..];
let byte = match path.first() {
Some(&val) => val as usize,
None if data && (!equal || current.is_empty()) => 0, None => return Some(current),
};
if let Some(node) = current.next.regular.get(byte) {
current = node;
continue;
}
for node in current.next.special.values() {
if let Some(find) = node.lookup(path, data, raw, capture, enable) {
return Some(find);
}
}
return None;
}
}
pub fn lookup_mut<'u>(&mut self, mut path: &'u [u8], data: bool, raw: bool, capture: &mut Vec<(Bytes, &'u [u8])>, enable: bool) -> Option<&mut RadixNode<V>> {
let mut current = self;
loop {
let share = match current.rule.longest(path, raw) {
Some(val) => val,
None => return None,
};
let equal = (!raw && current.rule.is_special()) || current.rule.origin().len() == share.len();
if share.len() != path.len() && !equal {
return None
}
if enable {
let ident = current.rule.identity();
if !ident.is_empty() {
capture.push((ident.clone(), share));
}
}
path = &path[share.len()..];
let byte = match path.first() {
Some(&val) => val as usize,
None if data && (!equal || current.is_empty()) => 0, None => return Some(current),
};
if let Some(node) = current.next.regular.get_mut(byte) {
current = node;
continue;
}
for node in current.next.special.values_mut() {
if let Some(find) = node.lookup_mut(path, data, raw, capture, enable) {
return Some(find);
}
}
return None;
}
}
#[inline]
pub fn divide(&mut self, len: usize) -> RadixResult<RadixNode<V>> {
Ok(RadixNode {
path: std::mem::take(&mut self.path),
data: self.data.take(),
rule: self.rule.divide(len)?,
next: std::mem::take(&mut self.next),
})
}
#[inline]
pub fn clear(&mut self) {
self.path.clear();
self.data = None;
self.rule = RadixRule::default();
self.next.clear();
}
}
impl<V> From<RadixRule> for RadixNode<V> {
#[inline]
fn from(rule: RadixRule) -> Self {
Self { path: Bytes::new(), data: None, rule, next: Default::default() }
}
}
impl<V> TryFrom<(Bytes, V)> for RadixNode<V> {
type Error = RadixError;
#[inline]
fn try_from((path, data): (Bytes, V)) -> RadixResult<Self> {
Ok(Self { path: path.clone(), data: Some(data), rule: RadixRule::try_from(path)?, next: Default::default() })
}
}
impl<V> TryFrom<(&'static [u8], V)> for RadixNode<V> {
type Error = RadixError;
#[inline]
fn try_from((path, data): (&'static [u8], V)) -> RadixResult<Self> {
(Bytes::from(path), data).try_into()
}
}
impl<V> TryFrom<(&'static str, V)> for RadixNode<V> {
type Error = RadixError;
#[inline]
fn try_from((path, data): (&'static str, V)) -> RadixResult<Self> {
(Bytes::from(path), data).try_into()
}
}
impl<V> Default for RadixNode<V> {
#[inline]
fn default() -> Self {
Self { path: Bytes::new(), data: None, rule: RadixRule::default(), next: pack::RadixPack::default() }
}
}
impl<V> Debug for RadixNode<V> {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
self.rule.fmt(f)
}
}
impl<V: Clone> Clone for RadixNode<V> {
#[inline]
fn clone(&self) -> Self {
Self {
path: self.path.clone(),
data: self.data.clone(),
rule: self.rule.clone(),
next: self.next.clone(),
}
}
}
#[derive(Debug, Clone, Hash, Eq, PartialEq, Ord, PartialOrd)]
pub enum Order {
Pre,
Post,
Level
}
impl Default for Order {
#[inline]
fn default() -> Self {
Self::Pre
}
}
#[derive(Default, Clone)]
pub struct Iter<'n, V> {
queue: VecDeque<Peekable<pack::Iter<'n, V>>>,
visit: Vec<Peekable<pack::Iter<'n, V>>>, order: Order,
empty: bool,
}
impl<'n, V> Iter<'n, V> {
pub fn with_prefix(mut self, path: &[u8], data: bool) -> Self {
let cursor = self.queue.pop_front();
self.queue.clear();
self.visit.clear();
let cursor = cursor
.and_then(|mut iter| iter.next())
.and_then(|node| match !path.is_empty() {
true => node.lookup(path, data, false, &mut vec![], false),
false => None,
});
if let Some(cursor) = cursor {
self.queue.push_front(pack::Iter::from(cursor).peekable());
}
self
}
#[inline]
pub fn with_order(mut self, order: Order) -> Self {
self.order = order;
self
}
#[inline]
pub fn with_empty(mut self) -> Self {
self.empty = true;
self
}
fn next_pre(&mut self) -> Option<&'n RadixNode<V>> {
loop {
let back = self.queue.back_mut()?;
match back.next() {
Some(node) => {
self.queue.push_back(node.next.iter().peekable());
return Some(node);
}
None => { self.queue.pop_back(); }
}
}
}
fn next_post(&mut self) -> Option<&'n RadixNode<V>> {
if let Some(mut back) = self.queue.pop_back() {
while let Some(node) = back.peek() {
let pack = node.next.iter().peekable();
self.visit.push(back);
back = pack;
}
return self.next_post();
}
loop {
let mut back = self.visit.pop()?;
if let Some(node) = back.next() {
if back.peek().is_some() {
self.queue.push_back(back);
}
return Some(node);
}
}
}
fn next_level(&mut self) -> Option<&'n RadixNode<V>> {
loop {
let front = self.queue.front_mut()?;
match front.next() {
Some(node) => {
self.queue.push_back(node.next.iter().peekable());
return Some(node);
}
None => { self.queue.pop_front(); }
}
}
}
}
impl<'n, V> From<&'n RadixNode<V>> for Iter<'n, V> {
#[inline]
fn from(start: &'n RadixNode<V>) -> Self {
Self { queue: VecDeque::from([pack::Iter::from(start).peekable()]), visit: vec![], order: Order::Pre, empty: false }
}
}
impl<'n, V> Iterator for Iter<'n, V> {
type Item = &'n RadixNode<V>;
fn next(&mut self) -> Option<Self::Item> {
loop {
let node = match self.order {
Order::Pre => self.next_pre(),
Order::Post => self.next_post(),
Order::Level => self.next_level(),
};
match node {
Some(node) if !self.empty && node.is_empty() => continue,
_ => return node,
}
}
}
}
#[derive(Default)]
pub struct IterMut<'n, V> {
queue: VecDeque<pack::IterMut<'n, V>>,
order: Order,
empty: bool,
}
impl<'n, V> IterMut<'n, V> {
pub fn with_prefix(mut self, path: &[u8], data: bool) -> Self {
let cursor = self.queue.pop_front();
self.queue.clear();
let cursor = cursor
.and_then(|mut iter| iter.next())
.and_then(|node| match !path.is_empty() {
true => node.lookup_mut(path, data, false, &mut vec![], false),
false => None,
});
if let Some(cursor) = cursor {
self.queue.push_front(pack::IterMut::from(cursor));
}
self
}
#[inline]
pub fn with_order(mut self, order: Order) -> Self {
self.order = order;
self
}
#[inline]
pub fn with_empty(mut self) -> Self {
self.empty = true;
self
}
fn next_pre(&mut self) -> Option<&'n mut RadixNode<V>> {
loop {
let back = self.queue.back_mut()?;
match back.next() {
Some(node) => {
let ptr = node as *mut RadixNode<V>;
self.queue.push_back(node.next.iter_mut());
unsafe { return Some(&mut *ptr); }
}
None => { self.queue.pop_back(); }
}
}
}
fn next_level(&mut self) -> Option<&'n mut RadixNode<V>> {
loop {
let front = self.queue.front_mut()?;
match front.next() {
Some(node) => {
let ptr = node as *mut RadixNode<V>;
self.queue.push_back(node.next.iter_mut());
unsafe { return Some(&mut *ptr); }
}
None => { self.queue.pop_front(); }
}
}
}
}
impl<'n, V> From<&'n mut RadixNode<V>> for IterMut<'n, V> {
#[inline]
fn from(start: &'n mut RadixNode<V>) -> Self {
Self { queue: VecDeque::from([pack::IterMut::from(start)]), order: Order::Pre, empty: false }
}
}
impl<'n, V> Iterator for IterMut<'n, V> {
type Item = &'n mut RadixNode<V>;
fn next(&mut self) -> Option<Self::Item> {
loop {
let node = match self.order {
Order::Pre => self.next_pre(),
Order::Level => self.next_level(),
_ => unimplemented!()
};
match node {
Some(node) if !self.empty && node.is_empty() => continue,
_ => return node,
}
}
}
}
#[derive(Default, Clone)]
pub struct Keys<'n, V> {
iter: Iter<'n, V>
}
impl<'n, V> Keys<'n, V> {
#[inline]
pub fn with_prefix(mut self, path: &[u8], data: bool) -> Self {
self.iter = self.iter.with_prefix(path, data);
self
}
#[inline]
pub fn with_order(mut self, order: Order) -> Self {
self.iter = self.iter.with_order(order);
self
}
}
impl<'n, V> From<&'n RadixNode<V>> for Keys<'n, V> {
#[inline]
fn from(value: &'n RadixNode<V>) -> Self {
Self { iter: Iter::from(value) }
}
}
impl<'n, V> Iterator for Keys<'n, V> {
type Item = &'n Bytes;
#[inline]
fn next(&mut self) -> Option<Self::Item> {
self.iter.next().map(|node| &node.path)
}
}
#[derive(Default, Clone)]
pub struct Values<'n, V> {
iter: Iter<'n, V>
}
impl<'n, V> Values<'n, V> {
#[inline]
pub fn with_prefix(mut self, path: &[u8], data: bool) -> Self {
self.iter = self.iter.with_prefix(path, data);
self
}
#[inline]
pub fn with_order(mut self, order: Order) -> Self {
self.iter = self.iter.with_order(order);
self
}
}
impl<'n, V> From<&'n RadixNode<V>> for Values<'n, V> {
#[inline]
fn from(value: &'n RadixNode<V>) -> Self {
Self { iter: Iter::from(value) }
}
}
impl<'n, V> Iterator for Values<'n, V> {
type Item = &'n V;
#[inline]
fn next(&mut self) -> Option<Self::Item> {
self.iter.next().and_then(|node| node.data.as_ref())
}
}
#[derive(Default)]
pub struct ValuesMut<'n, V> {
iter: IterMut<'n, V>
}
impl<'n, V> ValuesMut<'n, V> {
#[inline]
pub fn with_prefix(mut self, path: &[u8], data: bool) -> Self {
self.iter = self.iter.with_prefix(path, data);
self
}
#[inline]
pub fn with_order(mut self, order: Order) -> Self {
self.iter = self.iter.with_order(order);
self
}
}
impl<'n, V> From<&'n mut RadixNode<V>> for ValuesMut<'n, V> {
#[inline]
fn from(value: &'n mut RadixNode<V>) -> Self {
Self { iter: IterMut::from(value) }
}
}
impl<'n, V> Iterator for ValuesMut<'n, V> {
type Item = &'n mut V;
#[inline]
fn next(&mut self) -> Option<Self::Item> {
self.iter.next().and_then(|node| node.data.as_mut())
}
}