1use std::ops::Shr;
2
3use crate::{error::PoolResult, mark::Mark, node::Node};
4
5use super::{MarkRef, NodeRef};
6
7impl<'a> Shr<Node> for NodeRef<'a> {
10    type Output = PoolResult<NodeRef<'a>>;
11    fn shr(
12        self,
13        node: Node,
14    ) -> Self::Output {
15        self.tree.add_node(&self.key.clone(), &vec![node])?;
17        Ok(NodeRef::new(self.tree, self.key.clone()))
18    }
19}
20
21impl<'a> Shr<Vec<Node>> for NodeRef<'a> {
24    type Output = PoolResult<NodeRef<'a>>;
25    fn shr(
26        self,
27        nodes: Vec<Node>,
28    ) -> Self::Output {
29        if !nodes.is_empty() {
30            self.tree.add_node(&self.key.clone(), &nodes)?;
31        }
32        Ok(NodeRef::new(self.tree, self.key.clone()))
33    }
34}
35
36impl<'a> Shr<usize> for NodeRef<'a> {
39    type Output = PoolResult<NodeRef<'a>>;
40    fn shr(
41        self,
42        positions: usize,
43    ) -> Self::Output {
44        if let Some(parent) = self.tree.get_parent_node(&self.key.clone()) {
46            let siblings = self.tree.children(&parent.id).unwrap_or_default();
47
48            if let Some(current_index) =
49                siblings.iter().position(|id| id.clone() == self.key)
50            {
51                let max_index = siblings.len().saturating_sub(1);
53                let new_index = (current_index + positions).min(max_index);
54
55                if new_index != current_index {
57                    let mut node = self
59                        .tree
60                        .get_node(&self.key.clone())
61                        .unwrap()
62                        .as_ref()
63                        .clone();
64                    let mut content = node.content.clone();
65                    content.swap(current_index, new_index);
66                    node.content = content;
67                    self.tree.update_node(node)?;
68                }
69            }
70        }
71
72        Ok(NodeRef::new(self.tree, self.key.clone()))
73    }
74}
75
76impl<'a> Shr<Mark> for MarkRef<'a> {
79    type Output = PoolResult<MarkRef<'a>>;
80    fn shr(
81        self,
82        mark: Mark,
83    ) -> Self::Output {
84        self.tree.add_mark(&self.key.clone(), &[mark])?;
86        Ok(MarkRef::new(self.tree, self.key.clone()))
87    }
88}
89
90impl<'a> Shr<Vec<Mark>> for MarkRef<'a> {
93    type Output = PoolResult<MarkRef<'a>>;
94    fn shr(
95        self,
96        marks: Vec<Mark>,
97    ) -> Self::Output {
98        if !marks.is_empty() {
99            self.tree.add_mark(&self.key.clone(), &marks)?;
100        }
101        Ok(MarkRef::new(self.tree, self.key.clone()))
102    }
103}