use std::ops::Shl;
use crate::{error::PoolResult, 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().into(), 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().into(), 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().into())
{
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 mut node = self
.tree
.get_node(&self.key.clone().into())
.unwrap()
.as_ref()
.clone();
let mut content = node.content.clone();
content.swap(current_index, new_index);
node.content = content;
self.tree.update_node(node)?;
}
}
}
Ok(NodeRef::new(self.tree, self.key.clone()))
}
}