operation.rs 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156
  1. use super::operation_serde::{deserialize_changeset, serialize_changeset};
  2. use crate::core::{Changeset, NodeData, Path};
  3. use crate::errors::OTError;
  4. use serde::{Deserialize, Serialize};
  5. use std::sync::Arc;
  6. #[derive(Debug, Clone, Serialize, Deserialize)]
  7. #[serde(tag = "op")]
  8. pub enum NodeOperation {
  9. #[serde(rename = "insert")]
  10. Insert { path: Path, nodes: Vec<NodeData> },
  11. #[serde(rename = "update")]
  12. #[serde(serialize_with = "serialize_changeset")]
  13. #[serde(deserialize_with = "deserialize_changeset")]
  14. Update { path: Path, changeset: Changeset },
  15. #[serde(rename = "delete")]
  16. Delete { path: Path, nodes: Vec<NodeData> },
  17. }
  18. impl NodeOperation {
  19. pub fn get_path(&self) -> &Path {
  20. match self {
  21. NodeOperation::Insert { path, .. } => path,
  22. NodeOperation::Delete { path, .. } => path,
  23. NodeOperation::Update { path, .. } => path,
  24. }
  25. }
  26. pub fn get_mut_path(&mut self) -> &mut Path {
  27. match self {
  28. NodeOperation::Insert { path, .. } => path,
  29. NodeOperation::Delete { path, .. } => path,
  30. NodeOperation::Update { path, .. } => path,
  31. }
  32. }
  33. pub fn invert(&self) -> NodeOperation {
  34. match self {
  35. NodeOperation::Insert { path, nodes } => NodeOperation::Delete {
  36. path: path.clone(),
  37. nodes: nodes.clone(),
  38. },
  39. NodeOperation::Delete { path, nodes } => NodeOperation::Insert {
  40. path: path.clone(),
  41. nodes: nodes.clone(),
  42. },
  43. NodeOperation::Update { path, changeset: body } => NodeOperation::Update {
  44. path: path.clone(),
  45. changeset: body.inverted(),
  46. },
  47. }
  48. }
  49. /// Make the `other` operation can be applied to the version after applying the `self` operation.
  50. /// The semantics of transform is used when editing conflicts occur, which is often determined by the version id。
  51. /// For example, if the inserted position has been acquired by others, then it's needed to do the transform to
  52. /// make sure the inserted position is right.
  53. ///
  54. /// # Arguments
  55. ///
  56. /// * `other`: The operation that is going to be transformed
  57. ///
  58. /// # Examples
  59. ///
  60. /// ```
  61. /// use lib_ot::core::{NodeDataBuilder, NodeOperation, Path};
  62. /// let node_1 = NodeDataBuilder::new("text_1").build();
  63. /// let node_2 = NodeDataBuilder::new("text_2").build();
  64. ///
  65. /// let op_1 = NodeOperation::Insert {
  66. /// path: Path(vec![0, 1]),
  67. /// nodes: vec![node_1],
  68. /// };
  69. ///
  70. /// let mut op_2 = NodeOperation::Insert {
  71. /// path: Path(vec![0, 1]),
  72. /// nodes: vec![node_2],
  73. /// };
  74. ///
  75. /// assert_eq!(serde_json::to_string(&op_2).unwrap(), r#"{"op":"insert","path":[0,1],"nodes":[{"type":"text_2"}]}"#);
  76. ///
  77. /// op_1.transform(&mut op_2);
  78. /// assert_eq!(serde_json::to_string(&op_2).unwrap(), r#"{"op":"insert","path":[0,2],"nodes":[{"type":"text_2"}]}"#);
  79. /// assert_eq!(serde_json::to_string(&op_1).unwrap(), r#"{"op":"insert","path":[0,1],"nodes":[{"type":"text_1"}]}"#);
  80. /// ```
  81. pub fn transform(&self, other: &mut NodeOperation) {
  82. match self {
  83. NodeOperation::Insert { path, nodes } => {
  84. let new_path = path.transform(other.get_path(), nodes.len());
  85. *other.get_mut_path() = new_path;
  86. }
  87. NodeOperation::Delete { path, nodes } => {
  88. let new_path = path.transform(other.get_path(), nodes.len());
  89. *other.get_mut_path() = new_path;
  90. }
  91. _ => {
  92. // Only insert/delete will change the path.
  93. }
  94. }
  95. }
  96. }
  97. #[derive(Debug, Clone, Serialize, Deserialize, Default)]
  98. pub struct NodeOperations {
  99. operations: Vec<Arc<NodeOperation>>,
  100. }
  101. impl NodeOperations {
  102. pub fn into_inner(self) -> Vec<Arc<NodeOperation>> {
  103. self.operations
  104. }
  105. pub fn add_op(&mut self, operation: NodeOperation) {
  106. self.operations.push(Arc::new(operation));
  107. }
  108. }
  109. impl std::ops::Deref for NodeOperations {
  110. type Target = Vec<Arc<NodeOperation>>;
  111. fn deref(&self) -> &Self::Target {
  112. &self.operations
  113. }
  114. }
  115. impl std::ops::DerefMut for NodeOperations {
  116. fn deref_mut(&mut self) -> &mut Self::Target {
  117. &mut self.operations
  118. }
  119. }
  120. impl std::convert::From<Vec<NodeOperation>> for NodeOperations {
  121. fn from(operations: Vec<NodeOperation>) -> Self {
  122. Self::new(operations)
  123. }
  124. }
  125. impl NodeOperations {
  126. pub fn new(operations: Vec<NodeOperation>) -> Self {
  127. Self {
  128. operations: operations.into_iter().map(Arc::new).collect(),
  129. }
  130. }
  131. pub fn from_bytes(bytes: Vec<u8>) -> Result<Self, OTError> {
  132. let operation_list = serde_json::from_slice(&bytes).map_err(|err| OTError::serde().context(err))?;
  133. Ok(operation_list)
  134. }
  135. pub fn to_bytes(&self) -> Result<Vec<u8>, OTError> {
  136. let bytes = serde_json::to_vec(self).map_err(|err| OTError::serde().context(err))?;
  137. Ok(bytes)
  138. }
  139. }