sequence.rs 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195
  1. use std::{io, result::Result};
  2. use serde::{Deserialize, Serialize};
  3. use unicode_segmentation::UnicodeSegmentation;
  4. use darkfi::util::serial::{Decodable, Encodable, SerialDecodable, SerialEncodable};
  5. use crate::error::DarkWikiError;
  6. #[derive(PartialEq, Serialize, Deserialize, Clone, Debug)]
  7. pub enum OperationMethod {
  8. Delete(u64),
  9. Insert(String),
  10. Retain(u64),
  11. }
  12. #[derive(PartialEq, Serialize, Deserialize, SerialEncodable, SerialDecodable, Clone, Debug)]
  13. pub struct Operation {
  14. id: String,
  15. method: OperationMethod,
  16. }
  17. impl Operation {
  18. pub fn id(&self) -> String {
  19. self.id.clone()
  20. }
  21. }
  22. #[derive(PartialEq, Serialize, Deserialize, Clone, Debug)]
  23. pub struct Sequence {
  24. id: String,
  25. operations: Vec<OperationMethod>,
  26. len: u64,
  27. }
  28. impl Sequence {
  29. pub fn new(id: &str) -> Self {
  30. Self { id: id.to_string(), operations: vec![], len: 0 }
  31. }
  32. ///
  33. /// Apply all operations to the provided &str
  34. /// Return the final String
  35. ///
  36. pub fn apply(&self, s: &str) -> String {
  37. let mut st = vec![];
  38. let mut chars = s.graphemes(true).collect::<Vec<&str>>();
  39. for op in &self.operations {
  40. match op {
  41. OperationMethod::Retain(n) => {
  42. st.extend(chars[..(*n as usize)].to_vec());
  43. }
  44. OperationMethod::Delete(n) => {
  45. chars.drain(0..(*n as usize));
  46. }
  47. OperationMethod::Insert(insert) => {
  48. st.extend(insert.graphemes(true).collect::<Vec<&str>>());
  49. }
  50. }
  51. }
  52. st.join("")
  53. }
  54. ///
  55. /// Add new operation
  56. /// Return AddOperationFailed error if failed
  57. ///
  58. pub fn add_op(&mut self, op: &Operation) -> Result<(), DarkWikiError> {
  59. match &op.method {
  60. OperationMethod::Delete(n) => {
  61. if *n == 0 {
  62. return Ok(())
  63. }
  64. }
  65. OperationMethod::Insert(insert) => {
  66. if insert.is_empty() {
  67. return Ok(())
  68. }
  69. }
  70. OperationMethod::Retain(n) => {
  71. if *n == 0 {
  72. return Ok(())
  73. }
  74. }
  75. }
  76. self.operations.push(op.method.clone());
  77. Ok(())
  78. }
  79. ///
  80. /// Insert string at `n` position with Insert Operation
  81. /// Return AddOperationFailed if failed
  82. ///
  83. pub fn insert(&mut self, st: &str) -> Result<Operation, DarkWikiError> {
  84. let method = OperationMethod::Insert(st.into());
  85. let op = Operation { id: self.id.clone(), method };
  86. self.add_op(&op)?;
  87. Ok(op)
  88. }
  89. ///
  90. /// Move the position of cursor
  91. /// Return AddOperationFailed if failed
  92. ///
  93. pub fn retain(&mut self, n: u64) -> Result<Operation, DarkWikiError> {
  94. let method = OperationMethod::Retain(n);
  95. let op = Operation { id: self.id.clone(), method };
  96. self.add_op(&op)?;
  97. Ok(op)
  98. }
  99. ///
  100. /// Delete string at `n` position with Delete Operation
  101. /// Return AddOperationFailed if failed
  102. ///
  103. pub fn delete(&mut self, n: u64) -> Result<Operation, DarkWikiError> {
  104. let method = OperationMethod::Delete(n);
  105. let op = Operation { id: self.id.clone(), method };
  106. self.add_op(&op)?;
  107. Ok(op)
  108. }
  109. }
  110. impl Encodable for OperationMethod {
  111. fn encode<S: io::Write>(&self, mut s: S) -> darkfi::Result<usize> {
  112. let len: usize = match self {
  113. Self::Delete(i) => (0 as u8).encode(&mut s)? + i.encode(&mut s)?,
  114. Self::Insert(t) => (1 as u8).encode(&mut s)? + t.encode(&mut s)?,
  115. Self::Retain(i) => (2 as u8).encode(&mut s)? + i.encode(&mut s)?,
  116. };
  117. Ok(len)
  118. }
  119. }
  120. impl Decodable for OperationMethod {
  121. fn decode<D: io::Read>(mut d: D) -> darkfi::Result<Self> {
  122. let com: u8 = Decodable::decode(&mut d)?;
  123. match com {
  124. 0 => {
  125. let i: u64 = Decodable::decode(&mut d)?;
  126. Ok(Self::Delete(i))
  127. }
  128. 1 => {
  129. let t: String = Decodable::decode(d)?;
  130. Ok(Self::Insert(t))
  131. }
  132. 2 => {
  133. let i: u64 = Decodable::decode(&mut d)?;
  134. Ok(Self::Retain(i))
  135. }
  136. _ => Err(darkfi::Error::ParseFailed("Parse OperationMethod failed")),
  137. }
  138. }
  139. }
  140. #[cfg(test)]
  141. mod tests {
  142. use super::*;
  143. use darkfi::util::{
  144. gen_id,
  145. serial::{deserialize, serialize},
  146. };
  147. #[test]
  148. fn test_seq() {
  149. //
  150. // English
  151. //
  152. let _t = "this is the first paragraph";
  153. let mut seq = Sequence::new(&gen_id(30));
  154. //
  155. // Korean
  156. //
  157. let _t = "안녕하십니까";
  158. let mut seq = Sequence::new(&gen_id(30));
  159. //
  160. // Arabic
  161. //
  162. let _t = "عربي";
  163. let mut seq = Sequence::new(&gen_id(30));
  164. }
  165. #[test]
  166. fn test_serialize() {
  167. let op_method = OperationMethod::Delete(3);
  168. let op_method_ser = serialize(&op_method);
  169. let op_method_deser = deserialize(&op_method_ser).unwrap();
  170. assert_eq!(op_method, op_method_deser);
  171. }
  172. }