소스 검색

refactor: remove Box in DocumentOperation

appflowy 2 년 전
부모
커밋
800e02d85e

+ 40 - 26
shared-lib/lib-ot/src/core/document/document.rs

@@ -1,4 +1,4 @@
-use crate::core::document::position::Position;
+use crate::core::document::position::Path;
 use crate::core::{
     DocumentOperation, NodeAttributes, NodeData, NodeSubTree, OperationTransform, TextDelta, Transaction,
 };
@@ -23,27 +23,41 @@ impl DocumentTree {
         DocumentTree { arena, root }
     }
 
-    pub fn node_at_path(&self, position: &Position) -> Option<NodeId> {
-        if position.is_empty() {
+    pub fn node_at_path(&self, path: &Path) -> Option<NodeId> {
+        if path.is_empty() {
             return Some(self.root);
         }
 
         let mut iterate_node = self.root;
-
-        for id in &position.0 {
-            let child = self.child_at_index_of_path(iterate_node, *id);
-            iterate_node = match child {
-                Some(node) => node,
-                None => return None,
-            };
+        for id in path.iter() {
+            iterate_node = self.child_at_index_of_path(iterate_node, *id)?;
         }
-
         Some(iterate_node)
     }
 
-    pub fn path_of_node(&self, node_id: NodeId) -> Position {
+    ///
+    ///
+    /// # Arguments
+    ///
+    /// * `node_id`:
+    ///
+    /// returns: Path
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// use lib_ot::core::{DocumentOperation, DocumentTree, NodeSubTree, Path};
+    /// let text_node = NodeSubTree::new("text");
+    /// let path: Path = vec![0].into();
+    /// let op = DocumentOperation::Insert {path: path.clone(),nodes: vec![text_node
+    /// ]};
+    /// let mut document = DocumentTree::new();
+    /// document.apply_op(&op).unwrap();
+    /// let node_id = document.node_at_path(&path).unwrap();
+    ///
+    /// ```
+    pub fn path_of_node(&self, node_id: NodeId) -> Path {
         let mut path: Vec<usize> = Vec::new();
-
         let mut ancestors = node_id.ancestors(&self.arena);
         let mut current_node = node_id;
         let mut parent = ancestors.next();
@@ -56,7 +70,7 @@ impl DocumentTree {
             parent = ancestors.next();
         }
 
-        Position(path)
+        Path(path)
     }
 
     fn index_of_node(&self, parent_node: NodeId, child_node: NodeId) -> usize {
@@ -96,7 +110,7 @@ impl DocumentTree {
         Ok(())
     }
 
-    fn apply_op(&mut self, op: &DocumentOperation) -> Result<(), OTError> {
+    pub fn apply_op(&mut self, op: &DocumentOperation) -> Result<(), OTError> {
         match op {
             DocumentOperation::Insert { path, nodes } => self.apply_insert(path, nodes),
             DocumentOperation::Update { path, attributes, .. } => self.apply_update(path, attributes),
@@ -105,21 +119,21 @@ impl DocumentTree {
         }
     }
 
-    fn apply_insert(&mut self, path: &Position, nodes: &[Box<NodeSubTree>]) -> Result<(), OTError> {
+    fn apply_insert(&mut self, path: &Path, nodes: &[NodeSubTree]) -> Result<(), OTError> {
         let parent_path = &path.0[0..(path.0.len() - 1)];
         let last_index = path.0[path.0.len() - 1];
         let parent_node = self
-            .node_at_path(&Position(parent_path.to_vec()))
+            .node_at_path(&Path(parent_path.to_vec()))
             .ok_or_else(|| ErrorBuilder::new(OTErrorCode::PathNotFound).build())?;
 
-        self.insert_child_at_index(parent_node, last_index, nodes.as_ref())
+        self.insert_child_at_index(parent_node, last_index, nodes)
     }
 
     fn insert_child_at_index(
         &mut self,
         parent: NodeId,
         index: usize,
-        insert_children: &[Box<NodeSubTree>],
+        insert_children: &[NodeSubTree],
     ) -> Result<(), OTError> {
         if index == 0 && parent.children(&self.arena).next().is_none() {
             self.append_subtree(&parent, insert_children);
@@ -142,25 +156,25 @@ impl DocumentTree {
     }
 
     // recursive append the subtrees to the node
-    fn append_subtree(&mut self, parent: &NodeId, insert_children: &[Box<NodeSubTree>]) {
+    fn append_subtree(&mut self, parent: &NodeId, insert_children: &[NodeSubTree]) {
         for child in insert_children {
             let child_id = self.arena.new_node(child.to_node_data());
             parent.append(child_id, &mut self.arena);
 
-            self.append_subtree(&child_id, child.children.as_ref());
+            self.append_subtree(&child_id, &child.children);
         }
     }
 
-    fn insert_subtree_before(&mut self, before: &NodeId, insert_children: &[Box<NodeSubTree>]) {
+    fn insert_subtree_before(&mut self, before: &NodeId, insert_children: &[NodeSubTree]) {
         for child in insert_children {
             let child_id = self.arena.new_node(child.to_node_data());
             before.insert_before(child_id, &mut self.arena);
 
-            self.append_subtree(&child_id, child.children.as_ref());
+            self.append_subtree(&child_id, &child.children);
         }
     }
 
-    fn apply_update(&mut self, path: &Position, attributes: &NodeAttributes) -> Result<(), OTError> {
+    fn apply_update(&mut self, path: &Path, attributes: &NodeAttributes) -> Result<(), OTError> {
         let update_node = self
             .node_at_path(path)
             .ok_or_else(|| ErrorBuilder::new(OTErrorCode::PathNotFound).build())?;
@@ -177,7 +191,7 @@ impl DocumentTree {
         Ok(())
     }
 
-    fn apply_delete(&mut self, path: &Position, len: usize) -> Result<(), OTError> {
+    fn apply_delete(&mut self, path: &Path, len: usize) -> Result<(), OTError> {
         let mut update_node = self
             .node_at_path(path)
             .ok_or_else(|| ErrorBuilder::new(OTErrorCode::PathNotFound).build())?;
@@ -193,7 +207,7 @@ impl DocumentTree {
         Ok(())
     }
 
-    fn apply_text_edit(&mut self, path: &Position, delta: &TextDelta) -> Result<(), OTError> {
+    fn apply_text_edit(&mut self, path: &Path, delta: &TextDelta) -> Result<(), OTError> {
         let edit_node = self
             .node_at_path(path)
             .ok_or_else(|| ErrorBuilder::new(OTErrorCode::PathNotFound).build())?;

+ 25 - 31
shared-lib/lib-ot/src/core/document/document_operation.rs

@@ -1,36 +1,30 @@
-use crate::core::document::position::Position;
+use crate::core::document::position::Path;
 use crate::core::{NodeAttributes, NodeSubTree, TextDelta};
 
 #[derive(Clone, serde::Serialize, serde::Deserialize)]
 #[serde(tag = "op")]
 pub enum DocumentOperation {
     #[serde(rename = "insert")]
-    Insert {
-        path: Position,
-        nodes: Vec<Box<NodeSubTree>>,
-    },
+    Insert { path: Path, nodes: Vec<NodeSubTree> },
     #[serde(rename = "update")]
     Update {
-        path: Position,
+        path: Path,
         attributes: NodeAttributes,
         #[serde(rename = "oldAttributes")]
         old_attributes: NodeAttributes,
     },
     #[serde(rename = "delete")]
-    Delete {
-        path: Position,
-        nodes: Vec<Box<NodeSubTree>>,
-    },
+    Delete { path: Path, nodes: Vec<NodeSubTree> },
     #[serde(rename = "text-edit")]
     TextEdit {
-        path: Position,
+        path: Path,
         delta: TextDelta,
         inverted: TextDelta,
     },
 }
 
 impl DocumentOperation {
-    pub fn path(&self) -> &Position {
+    pub fn path(&self) -> &Path {
         match self {
             DocumentOperation::Insert { path, .. } => path,
             DocumentOperation::Update { path, .. } => path,
@@ -64,7 +58,7 @@ impl DocumentOperation {
             },
         }
     }
-    pub fn clone_with_new_path(&self, path: Position) -> DocumentOperation {
+    pub fn clone_with_new_path(&self, path: Path) -> DocumentOperation {
         match self {
             DocumentOperation::Insert { nodes, .. } => DocumentOperation::Insert {
                 path,
@@ -93,11 +87,11 @@ impl DocumentOperation {
     pub fn transform(a: &DocumentOperation, b: &DocumentOperation) -> DocumentOperation {
         match a {
             DocumentOperation::Insert { path: a_path, nodes } => {
-                let new_path = Position::transform(a_path, b.path(), nodes.len() as i64);
+                let new_path = Path::transform(a_path, b.path(), nodes.len() as i64);
                 b.clone_with_new_path(new_path)
             }
             DocumentOperation::Delete { path: a_path, nodes } => {
-                let new_path = Position::transform(a_path, b.path(), nodes.len() as i64);
+                let new_path = Path::transform(a_path, b.path(), nodes.len() as i64);
                 b.clone_with_new_path(new_path)
             }
             _ => b.clone(),
@@ -107,12 +101,12 @@ impl DocumentOperation {
 
 #[cfg(test)]
 mod tests {
-    use crate::core::{Delta, DocumentOperation, NodeAttributes, NodeSubTree, Position};
+    use crate::core::{Delta, DocumentOperation, NodeAttributes, NodeSubTree, Path};
 
     #[test]
     fn test_transform_path_1() {
         assert_eq!(
-            { Position::transform(&Position(vec![0, 1]), &Position(vec![0, 1]), 1) }.0,
+            { Path::transform(&Path(vec![0, 1]), &Path(vec![0, 1]), 1) }.0,
             vec![0, 2]
         );
     }
@@ -120,7 +114,7 @@ mod tests {
     #[test]
     fn test_transform_path_2() {
         assert_eq!(
-            { Position::transform(&Position(vec![0, 1]), &Position(vec![0, 2]), 1) }.0,
+            { Path::transform(&Path(vec![0, 1]), &Path(vec![0, 2]), 1) }.0,
             vec![0, 3]
         );
     }
@@ -128,7 +122,7 @@ mod tests {
     #[test]
     fn test_transform_path_3() {
         assert_eq!(
-            { Position::transform(&Position(vec![0, 1]), &Position(vec![0, 2, 7, 8, 9]), 1) }.0,
+            { Path::transform(&Path(vec![0, 1]), &Path(vec![0, 2, 7, 8, 9]), 1) }.0,
             vec![0, 3, 7, 8, 9]
         );
     }
@@ -136,15 +130,15 @@ mod tests {
     #[test]
     fn test_transform_path_not_changed() {
         assert_eq!(
-            { Position::transform(&Position(vec![0, 1, 2]), &Position(vec![0, 0, 7, 8, 9]), 1) }.0,
+            { Path::transform(&Path(vec![0, 1, 2]), &Path(vec![0, 0, 7, 8, 9]), 1) }.0,
             vec![0, 0, 7, 8, 9]
         );
         assert_eq!(
-            { Position::transform(&Position(vec![0, 1, 2]), &Position(vec![0, 1]), 1) }.0,
+            { Path::transform(&Path(vec![0, 1, 2]), &Path(vec![0, 1]), 1) }.0,
             vec![0, 1]
         );
         assert_eq!(
-            { Position::transform(&Position(vec![1, 1]), &Position(vec![1, 0]), 1) }.0,
+            { Path::transform(&Path(vec![1, 1]), &Path(vec![1, 0]), 1) }.0,
             vec![1, 0]
         );
     }
@@ -152,7 +146,7 @@ mod tests {
     #[test]
     fn test_transform_delta() {
         assert_eq!(
-            { Position::transform(&Position(vec![0, 1]), &Position(vec![0, 1]), 5) }.0,
+            { Path::transform(&Path(vec![0, 1]), &Path(vec![0, 1]), 5) }.0,
             vec![0, 6]
         );
     }
@@ -160,8 +154,8 @@ mod tests {
     #[test]
     fn test_serialize_insert_operation() {
         let insert = DocumentOperation::Insert {
-            path: Position(vec![0, 1]),
-            nodes: vec![Box::new(NodeSubTree::new("text"))],
+            path: Path(vec![0, 1]),
+            nodes: vec![NodeSubTree::new("text")],
         };
         let result = serde_json::to_string(&insert).unwrap();
         assert_eq!(
@@ -173,13 +167,13 @@ mod tests {
     #[test]
     fn test_serialize_insert_sub_trees() {
         let insert = DocumentOperation::Insert {
-            path: Position(vec![0, 1]),
-            nodes: vec![Box::new(NodeSubTree {
+            path: Path(vec![0, 1]),
+            nodes: vec![NodeSubTree {
                 node_type: "text".into(),
                 attributes: NodeAttributes::new(),
                 delta: None,
-                children: vec![Box::new(NodeSubTree::new("text"))],
-            })],
+                children: vec![NodeSubTree::new("text")],
+            }],
         };
         let result = serde_json::to_string(&insert).unwrap();
         assert_eq!(
@@ -191,7 +185,7 @@ mod tests {
     #[test]
     fn test_serialize_update_operation() {
         let insert = DocumentOperation::Update {
-            path: Position(vec![0, 1]),
+            path: Path(vec![0, 1]),
             attributes: NodeAttributes::new(),
             old_attributes: NodeAttributes::new(),
         };
@@ -205,7 +199,7 @@ mod tests {
     #[test]
     fn test_serialize_text_edit_operation() {
         let insert = DocumentOperation::TextEdit {
-            path: Position(vec![0, 1]),
+            path: Path(vec![0, 1]),
             delta: Delta::new(),
             inverted: Delta::new(),
         };

+ 1 - 1
shared-lib/lib-ot/src/core/document/node.rs

@@ -25,7 +25,7 @@ pub struct NodeSubTree {
     #[serde(skip_serializing_if = "Option::is_none")]
     pub delta: Option<TextDelta>,
     #[serde(skip_serializing_if = "Vec::is_empty")]
-    pub children: Vec<Box<NodeSubTree>>,
+    pub children: Vec<NodeSubTree>,
 }
 
 impl NodeSubTree {

+ 11 - 12
shared-lib/lib-ot/src/core/document/position.rs

@@ -1,18 +1,17 @@
 #[derive(Clone, serde::Serialize, serde::Deserialize)]
-pub struct Position(pub Vec<usize>);
+pub struct Path(pub Vec<usize>);
 
-impl Position {
-    pub fn is_empty(&self) -> bool {
-        self.0.is_empty()
-    }
-    pub fn len(&self) -> usize {
-        self.0.len()
+impl std::ops::Deref for Path {
+    type Target = Vec<usize>;
+
+    fn deref(&self) -> &Self::Target {
+        &self.0
     }
 }
 
-impl Position {
+impl Path {
     // delta is default to be 1
-    pub fn transform(pre_insert_path: &Position, b: &Position, offset: i64) -> Position {
+    pub fn transform(pre_insert_path: &Path, b: &Path, offset: i64) -> Path {
         if pre_insert_path.len() > b.len() {
             return b.clone();
         }
@@ -36,12 +35,12 @@ impl Position {
         }
         prefix.append(&mut suffix);
 
-        Position(prefix)
+        Path(prefix)
     }
 }
 
-impl From<Vec<usize>> for Position {
+impl From<Vec<usize>> for Path {
     fn from(v: Vec<usize>) -> Self {
-        Position(v)
+        Path(v)
     }
 }

+ 10 - 11
shared-lib/lib-ot/src/core/document/transaction.rs

@@ -1,4 +1,4 @@
-use crate::core::document::position::Position;
+use crate::core::document::position::Path;
 use crate::core::{DocumentOperation, DocumentTree, NodeAttributes, NodeSubTree};
 use indextree::NodeId;
 use std::collections::HashMap;
@@ -26,14 +26,14 @@ impl<'a> TransactionBuilder<'a> {
         }
     }
 
-    pub fn insert_nodes_at_path(&mut self, path: &Position, nodes: &[Box<NodeSubTree>]) {
+    pub fn insert_nodes_at_path(&mut self, path: &Path, nodes: &[NodeSubTree]) {
         self.push(DocumentOperation::Insert {
             path: path.clone(),
             nodes: nodes.to_vec(),
         });
     }
 
-    pub fn update_attributes_at_path(&mut self, path: &Position, attributes: HashMap<String, Option<String>>) {
+    pub fn update_attributes_at_path(&mut self, path: &Path, attributes: HashMap<String, Option<String>>) {
         let mut old_attributes: HashMap<String, Option<String>> = HashMap::new();
         let node = self.document.node_at_path(path).unwrap();
         let node_data = self.document.arena.get(node).unwrap().get();
@@ -54,14 +54,13 @@ impl<'a> TransactionBuilder<'a> {
         })
     }
 
-    pub fn delete_node_at_path(&mut self, path: &Position) {
+    pub fn delete_node_at_path(&mut self, path: &Path) {
         self.delete_nodes_at_path(path, 1);
     }
 
-    pub fn delete_nodes_at_path(&mut self, path: &Position, length: usize) {
+    pub fn delete_nodes_at_path(&mut self, path: &Path, length: usize) {
         let mut node = self.document.node_at_path(path).unwrap();
-        let mut deleted_nodes: Vec<Box<NodeSubTree>> = Vec::new();
-
+        let mut deleted_nodes  = vec![];
         for _ in 0..length {
             deleted_nodes.push(self.get_deleted_nodes(node));
             node = node.following_siblings(&self.document.arena).next().unwrap();
@@ -73,20 +72,20 @@ impl<'a> TransactionBuilder<'a> {
         })
     }
 
-    fn get_deleted_nodes(&self, node_id: NodeId) -> Box<NodeSubTree> {
+    fn get_deleted_nodes(&self, node_id: NodeId) -> NodeSubTree {
         let node_data = self.document.arena.get(node_id).unwrap().get();
 
-        let mut children: Vec<Box<NodeSubTree>> = vec![];
+        let mut children  = vec![];
         node_id.children(&self.document.arena).for_each(|child_id| {
             children.push(self.get_deleted_nodes(child_id));
         });
 
-        Box::new(NodeSubTree {
+        NodeSubTree {
             node_type: node_data.node_type.clone(),
             attributes: node_data.attributes.clone(),
             delta: node_data.delta.clone(),
             children,
-        })
+        }
     }
 
     pub fn push(&mut self, op: DocumentOperation) {

+ 20 - 20
shared-lib/lib-ot/tests/main.rs

@@ -1,4 +1,4 @@
-use lib_ot::core::{DocumentTree, NodeAttributes, NodeSubTree, Position, TransactionBuilder};
+use lib_ot::core::{DocumentTree, NodeAttributes, NodeSubTree, Path, TransactionBuilder};
 use lib_ot::errors::OTErrorCode;
 use std::collections::HashMap;
 
@@ -13,7 +13,7 @@ fn test_documents() {
     let mut document = DocumentTree::new();
     let transaction = {
         let mut tb = TransactionBuilder::new(&document);
-        tb.insert_nodes_at_path(&vec![0].into(), &[Box::new(NodeSubTree::new("text"))]);
+        tb.insert_nodes_at_path(&vec![0].into(), &[NodeSubTree::new("text")]);
         tb.finalize()
     };
     document.apply(transaction).unwrap();
@@ -47,16 +47,16 @@ fn test_inserts_nodes() {
     let mut document = DocumentTree::new();
     let transaction = {
         let mut tb = TransactionBuilder::new(&document);
-        tb.insert_nodes_at_path(&vec![0].into(), &[Box::new(NodeSubTree::new("text"))]);
-        tb.insert_nodes_at_path(&vec![1].into(), &[Box::new(NodeSubTree::new("text"))]);
-        tb.insert_nodes_at_path(&vec![2].into(), &[Box::new(NodeSubTree::new("text"))]);
+        tb.insert_nodes_at_path(&vec![0].into(), &[NodeSubTree::new("text")]);
+        tb.insert_nodes_at_path(&vec![1].into(), &[NodeSubTree::new("text")]);
+        tb.insert_nodes_at_path(&vec![2].into(), &[NodeSubTree::new("text")]);
         tb.finalize()
     };
     document.apply(transaction).unwrap();
 
     let transaction = {
         let mut tb = TransactionBuilder::new(&document);
-        tb.insert_nodes_at_path(&vec![1].into(), &[Box::new(NodeSubTree::new("text"))]);
+        tb.insert_nodes_at_path(&vec![1].into(), &[NodeSubTree::new("text")]);
         tb.finalize()
     };
     document.apply(transaction).unwrap();
@@ -69,18 +69,18 @@ fn test_inserts_subtrees() {
         let mut tb = TransactionBuilder::new(&document);
         tb.insert_nodes_at_path(
             &vec![0].into(),
-            &[Box::new(NodeSubTree {
+            &[NodeSubTree {
                 node_type: "text".into(),
                 attributes: NodeAttributes::new(),
                 delta: None,
-                children: vec![Box::new(NodeSubTree::new("image"))],
-            })],
+                children: vec![NodeSubTree::new("image")],
+            }],
         );
         tb.finalize()
     };
     document.apply(transaction).unwrap();
 
-    let node = document.node_at_path(&Position(vec![0, 0])).unwrap();
+    let node = document.node_at_path(&Path(vec![0, 0])).unwrap();
     let data = document.arena.get(node).unwrap().get();
     assert_eq!(data.node_type, "image");
 }
@@ -90,9 +90,9 @@ fn test_update_nodes() {
     let mut document = DocumentTree::new();
     let transaction = {
         let mut tb = TransactionBuilder::new(&document);
-        tb.insert_nodes_at_path(&vec![0].into(), &[Box::new(NodeSubTree::new("text"))]);
-        tb.insert_nodes_at_path(&vec![1].into(), &[Box::new(NodeSubTree::new("text"))]);
-        tb.insert_nodes_at_path(&vec![2].into(), &[Box::new(NodeSubTree::new("text"))]);
+        tb.insert_nodes_at_path(&vec![0].into(), &[NodeSubTree::new("text")]);
+        tb.insert_nodes_at_path(&vec![1].into(), &[NodeSubTree::new("text")]);
+        tb.insert_nodes_at_path(&vec![2].into(), &[NodeSubTree::new("text")]);
         tb.finalize()
     };
     document.apply(transaction).unwrap();
@@ -104,7 +104,7 @@ fn test_update_nodes() {
     };
     document.apply(transaction).unwrap();
 
-    let node = document.node_at_path(&Position(vec![1])).unwrap();
+    let node = document.node_at_path(&Path(vec![1])).unwrap();
     let node_data = document.arena.get(node).unwrap().get();
     let is_bold = node_data.attributes.0.get("bolded").unwrap().clone();
     assert_eq!(is_bold.unwrap(), "true");
@@ -115,16 +115,16 @@ fn test_delete_nodes() {
     let mut document = DocumentTree::new();
     let transaction = {
         let mut tb = TransactionBuilder::new(&document);
-        tb.insert_nodes_at_path(&vec![0].into(), &[Box::new(NodeSubTree::new("text"))]);
-        tb.insert_nodes_at_path(&vec![1].into(), &[Box::new(NodeSubTree::new("text"))]);
-        tb.insert_nodes_at_path(&vec![2].into(), &[Box::new(NodeSubTree::new("text"))]);
+        tb.insert_nodes_at_path(&vec![0].into(), &[NodeSubTree::new("text")]);
+        tb.insert_nodes_at_path(&vec![1].into(), &[NodeSubTree::new("text")]);
+        tb.insert_nodes_at_path(&vec![2].into(), &[NodeSubTree::new("text")]);
         tb.finalize()
     };
     document.apply(transaction).unwrap();
 
     let transaction = {
         let mut tb = TransactionBuilder::new(&document);
-        tb.delete_node_at_path(&Position(vec![1]));
+        tb.delete_node_at_path(&Path(vec![1]));
         tb.finalize()
     };
     document.apply(transaction).unwrap();
@@ -138,8 +138,8 @@ fn test_errors() {
     let mut document = DocumentTree::new();
     let transaction = {
         let mut tb = TransactionBuilder::new(&document);
-        tb.insert_nodes_at_path(&vec![0].into(), &[Box::new(NodeSubTree::new("text"))]);
-        tb.insert_nodes_at_path(&vec![100].into(), &[Box::new(NodeSubTree::new("text"))]);
+        tb.insert_nodes_at_path(&vec![0].into(), &[NodeSubTree::new("text")]);
+        tb.insert_nodes_at_path(&vec![100].into(), &[NodeSubTree::new("text")]);
         tb.finalize()
     };
     let result = document.apply(transaction);