use std::ops::Shr;
use crate::{error::PoolResult, error_helpers, mark::Mark, node::Node};
use super::{MarkRef, NodeRef};
impl<'a> Shr<Node> for NodeRef<'a> {
type Output = PoolResult<NodeRef<'a>>;
fn shr(
self,
node: Node,
) -> Self::Output {
self.tree.add_node(&self.key.clone(), &vec![node])?;
Ok(NodeRef::new(self.tree, self.key.clone()))
}
}
impl<'a> Shr<Vec<Node>> for NodeRef<'a> {
type Output = PoolResult<NodeRef<'a>>;
fn shr(
self,
nodes: Vec<Node>,
) -> Self::Output {
if !nodes.is_empty() {
self.tree.add_node(&self.key.clone(), &nodes)?;
}
Ok(NodeRef::new(self.tree, self.key.clone()))
}
}
impl<'a> Shr<usize> for NodeRef<'a> {
type Output = PoolResult<NodeRef<'a>>;
fn shr(
self,
positions: usize,
) -> Self::Output {
if let Some(parent) = self.tree.get_parent_node(&self.key.clone()) {
let siblings = self.tree.children(&parent.id).unwrap_or_default();
if let Some(current_index) =
siblings.iter().position(|id| id.clone() == self.key)
{
let max_index = siblings.len().saturating_sub(1);
let new_index = (current_index + positions).min(max_index);
if new_index != current_index {
let node = {
let node = {
match self.tree.get_node(&self.key.clone()) {
Some(n) => n,
None => {
return Err(error_helpers::node_not_found(
self.key.clone(),
));
},
}
};
match node.swap(current_index, new_index) {
Some(n) => n,
None => return Err(anyhow::anyhow!("下标越界了")),
}
};
self.tree.update_node(node)?;
}
}
}
Ok(NodeRef::new(self.tree, self.key.clone()))
}
}
impl<'a> Shr<Mark> for MarkRef<'a> {
type Output = PoolResult<MarkRef<'a>>;
fn shr(
self,
mark: Mark,
) -> Self::Output {
self.tree.add_mark(&self.key.clone(), &[mark])?;
Ok(MarkRef::new(self.tree, self.key.clone()))
}
}
impl<'a> Shr<Vec<Mark>> for MarkRef<'a> {
type Output = PoolResult<MarkRef<'a>>;
fn shr(
self,
marks: Vec<Mark>,
) -> Self::Output {
if !marks.is_empty() {
self.tree.add_mark(&self.key.clone(), &marks)?;
}
Ok(MarkRef::new(self.tree, self.key.clone()))
}
}