use std::ops::Shl;
use crate::{error::PoolResult, error_helpers, node::Node};
use super::{NodeRef};
impl<'a> Shl<Node> for NodeRef<'a> {
type Output = PoolResult<NodeRef<'a>>;
fn shl(
self,
node: Node,
) -> Self::Output {
self.tree.add_at_index(&self.key.clone(), 0, &node)?;
Ok(NodeRef::new(self.tree, self.key.clone()))
}
}
impl<'a> Shl<Vec<Node>> for NodeRef<'a> {
type Output = PoolResult<NodeRef<'a>>;
fn shl(
self,
nodes: Vec<Node>,
) -> Self::Output {
for (i, node) in nodes.into_iter().enumerate() {
self.tree.add_at_index(&self.key.clone(), i, &node)?;
}
Ok(NodeRef::new(self.tree, self.key.clone()))
}
}
impl<'a> Shl<usize> for NodeRef<'a> {
type Output = PoolResult<NodeRef<'a>>;
fn shl(
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 new_index = current_index.saturating_sub(positions);
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()))
}
}