delta.rs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496
  1. use crate::{
  2. core::{attributes::*, operation::*, DeltaIter, FlowyStr, Interval, OperationTransformable, MAX_IV_LEN},
  3. errors::{ErrorBuilder, OTError, OTErrorCode},
  4. };
  5. use bytes::Bytes;
  6. use std::{
  7. cmp::{min, Ordering},
  8. fmt,
  9. iter::FromIterator,
  10. str,
  11. str::FromStr,
  12. };
  13. // Opti: optimize the memory usage with Arc_mut or Cow
  14. #[derive(Clone, Debug, PartialEq, Eq)]
  15. pub struct Delta {
  16. pub ops: Vec<Operation>,
  17. pub base_len: usize,
  18. pub target_len: usize,
  19. }
  20. impl Default for Delta {
  21. fn default() -> Self {
  22. Self {
  23. ops: Vec::new(),
  24. base_len: 0,
  25. target_len: 0,
  26. }
  27. }
  28. }
  29. impl FromStr for Delta {
  30. type Err = ();
  31. fn from_str(s: &str) -> Result<Delta, Self::Err> {
  32. let mut delta = Delta::with_capacity(1);
  33. delta.add(Operation::Insert(s.into()));
  34. Ok(delta)
  35. }
  36. }
  37. impl std::convert::TryFrom<Vec<u8>> for Delta {
  38. type Error = OTError;
  39. fn try_from(bytes: Vec<u8>) -> Result<Self, Self::Error> { Delta::from_bytes(bytes) }
  40. }
  41. impl std::convert::TryFrom<Bytes> for Delta {
  42. type Error = OTError;
  43. fn try_from(bytes: Bytes) -> Result<Self, Self::Error> { Delta::from_bytes(&bytes) }
  44. }
  45. impl fmt::Display for Delta {
  46. fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
  47. // f.write_str(&serde_json::to_string(self).unwrap_or("".to_owned()))?;
  48. f.write_str("[ ")?;
  49. for op in &self.ops {
  50. f.write_fmt(format_args!("{} ", op))?;
  51. }
  52. f.write_str("]")?;
  53. Ok(())
  54. }
  55. }
  56. impl FromIterator<Operation> for Delta {
  57. fn from_iter<T: IntoIterator<Item = Operation>>(ops: T) -> Self {
  58. let mut operations = Delta::default();
  59. for op in ops {
  60. operations.add(op);
  61. }
  62. operations
  63. }
  64. }
  65. impl Delta {
  66. pub fn new() -> Self { Self::default() }
  67. pub fn from_json(json: &str) -> Result<Self, OTError> {
  68. let delta: Delta = serde_json::from_str(json).map_err(|e| {
  69. tracing::trace!("Deserialize failed: {:?}", e);
  70. tracing::trace!("{:?}", json);
  71. e
  72. })?;
  73. Ok(delta)
  74. }
  75. pub fn to_json(&self) -> String { serde_json::to_string(self).unwrap_or("".to_owned()) }
  76. pub fn from_bytes<T: AsRef<[u8]>>(bytes: T) -> Result<Self, OTError> {
  77. let json = str::from_utf8(bytes.as_ref())?;
  78. Self::from_json(json)
  79. }
  80. pub fn to_bytes(&self) -> Bytes {
  81. let json = self.to_json();
  82. Bytes::from(json.into_bytes())
  83. }
  84. #[inline]
  85. pub fn with_capacity(capacity: usize) -> Self {
  86. Self {
  87. ops: Vec::with_capacity(capacity),
  88. base_len: 0,
  89. target_len: 0,
  90. }
  91. }
  92. pub fn add(&mut self, op: Operation) {
  93. match op {
  94. Operation::Delete(i) => self.delete(i),
  95. Operation::Insert(i) => self.insert(&i.s, i.attributes),
  96. Operation::Retain(r) => self.retain(r.n, r.attributes),
  97. }
  98. }
  99. pub fn delete(&mut self, n: usize) {
  100. if n == 0 {
  101. return;
  102. }
  103. self.base_len += n as usize;
  104. if let Some(Operation::Delete(n_last)) = self.ops.last_mut() {
  105. *n_last += n;
  106. } else {
  107. self.ops.push(OpBuilder::delete(n).build());
  108. }
  109. }
  110. pub fn insert(&mut self, s: &str, attributes: Attributes) {
  111. let s: FlowyStr = s.into();
  112. if s.is_empty() {
  113. return;
  114. }
  115. self.target_len += s.count_utf16_code_units();
  116. let new_last = match self.ops.as_mut_slice() {
  117. [.., Operation::Insert(insert)] => {
  118. //
  119. insert.merge_or_new_op(&s, attributes)
  120. },
  121. [.., Operation::Insert(pre_insert), Operation::Delete(_)] => {
  122. //
  123. pre_insert.merge_or_new_op(&s, attributes)
  124. },
  125. [.., op_last @ Operation::Delete(_)] => {
  126. let new_last = op_last.clone();
  127. *op_last = OpBuilder::insert(&s).attributes(attributes).build();
  128. Some(new_last)
  129. },
  130. _ => Some(OpBuilder::insert(&s).attributes(attributes).build()),
  131. };
  132. match new_last {
  133. None => {},
  134. Some(new_last) => self.ops.push(new_last),
  135. }
  136. }
  137. pub fn retain(&mut self, n: usize, attributes: Attributes) {
  138. if n == 0 {
  139. return;
  140. }
  141. self.base_len += n as usize;
  142. self.target_len += n as usize;
  143. if let Some(Operation::Retain(retain)) = self.ops.last_mut() {
  144. if let Some(new_op) = retain.merge_or_new(n, attributes) {
  145. self.ops.push(new_op);
  146. }
  147. } else {
  148. self.ops.push(OpBuilder::retain(n).attributes(attributes).build());
  149. }
  150. }
  151. /// Applies an operation to a string, returning a new string.
  152. pub fn apply(&self, s: &str) -> Result<String, OTError> {
  153. let s: FlowyStr = s.into();
  154. if s.count_utf16_code_units() != self.base_len {
  155. return Err(ErrorBuilder::new(OTErrorCode::IncompatibleLength).build());
  156. }
  157. let mut new_s = String::new();
  158. let chars = &mut s.chars();
  159. for op in &self.ops {
  160. match &op {
  161. Operation::Retain(retain) => {
  162. for c in chars.take(retain.n as usize) {
  163. new_s.push(c);
  164. }
  165. },
  166. Operation::Delete(delete) => {
  167. for _ in 0..*delete {
  168. chars.next();
  169. }
  170. },
  171. Operation::Insert(insert) => {
  172. new_s += &insert.s;
  173. },
  174. }
  175. }
  176. Ok(new_s)
  177. }
  178. /// Computes the inverse of an operation. The inverse of an operation is the
  179. /// operation that reverts the effects of the operation
  180. pub fn invert_str(&self, s: &str) -> Self {
  181. let mut inverted = Delta::default();
  182. let chars = &mut s.chars();
  183. for op in &self.ops {
  184. match &op {
  185. Operation::Retain(retain) => {
  186. inverted.retain(retain.n, Attributes::default());
  187. // TODO: use advance_by instead, but it's unstable now
  188. // chars.advance_by(retain.num)
  189. for _ in 0..retain.n {
  190. chars.next();
  191. }
  192. },
  193. Operation::Insert(insert) => {
  194. inverted.delete(insert.count_of_code_units());
  195. },
  196. Operation::Delete(delete) => {
  197. inverted.insert(&chars.take(*delete as usize).collect::<String>(), op.get_attributes());
  198. },
  199. }
  200. }
  201. inverted
  202. }
  203. /// Checks if this operation has no effect.
  204. #[inline]
  205. pub fn is_noop(&self) -> bool {
  206. match self.ops.as_slice() {
  207. [] => true,
  208. [Operation::Retain(_)] => true,
  209. _ => false,
  210. }
  211. }
  212. pub fn is_empty(&self) -> bool { self.ops.is_empty() }
  213. pub fn extend(&mut self, other: Self) { other.ops.into_iter().for_each(|op| self.add(op)); }
  214. }
  215. impl OperationTransformable for Delta {
  216. fn compose(&self, other: &Self) -> Result<Self, OTError>
  217. where
  218. Self: Sized,
  219. {
  220. let mut new_delta = Delta::default();
  221. let mut iter = DeltaIter::new(self);
  222. let mut other_iter = DeltaIter::new(other);
  223. while iter.has_next() || other_iter.has_next() {
  224. if other_iter.is_next_insert() {
  225. new_delta.add(other_iter.next_op().unwrap());
  226. continue;
  227. }
  228. if iter.is_next_delete() {
  229. new_delta.add(iter.next_op().unwrap());
  230. continue;
  231. }
  232. let length = min(
  233. iter.next_op_len().unwrap_or(MAX_IV_LEN),
  234. other_iter.next_op_len().unwrap_or(MAX_IV_LEN),
  235. );
  236. let op = iter
  237. .next_op_with_len(length)
  238. .unwrap_or(OpBuilder::retain(length).build());
  239. let other_op = other_iter
  240. .next_op_with_len(length)
  241. .unwrap_or(OpBuilder::retain(length).build());
  242. debug_assert_eq!(op.len(), other_op.len());
  243. match (&op, &other_op) {
  244. (Operation::Retain(retain), Operation::Retain(other_retain)) => {
  245. let composed_attrs = retain.attributes.compose(&other_retain.attributes)?;
  246. new_delta.add(OpBuilder::retain(retain.n).attributes(composed_attrs).build())
  247. },
  248. (Operation::Insert(insert), Operation::Retain(other_retain)) => {
  249. let mut composed_attrs = insert.attributes.compose(&other_retain.attributes)?;
  250. composed_attrs.remove_empty();
  251. new_delta.add(OpBuilder::insert(op.get_data()).attributes(composed_attrs).build())
  252. },
  253. (Operation::Retain(_), Operation::Delete(_)) => {
  254. new_delta.add(other_op);
  255. },
  256. (a, b) => {
  257. debug_assert_eq!(a.is_insert(), true);
  258. debug_assert_eq!(b.is_delete(), true);
  259. continue;
  260. },
  261. }
  262. }
  263. Ok(new_delta)
  264. }
  265. fn transform(&self, other: &Self) -> Result<(Self, Self), OTError>
  266. where
  267. Self: Sized,
  268. {
  269. if self.base_len != other.base_len {
  270. return Err(ErrorBuilder::new(OTErrorCode::IncompatibleLength)
  271. .msg(format!(
  272. "cur base length: {}, other base length: {}",
  273. self.base_len, other.base_len
  274. ))
  275. .build());
  276. }
  277. let mut a_prime = Delta::default();
  278. let mut b_prime = Delta::default();
  279. let mut ops1 = self.ops.iter().cloned();
  280. let mut ops2 = other.ops.iter().cloned();
  281. let mut next_op1 = ops1.next();
  282. let mut next_op2 = ops2.next();
  283. loop {
  284. match (&next_op1, &next_op2) {
  285. (None, None) => break,
  286. (Some(Operation::Insert(insert)), _) => {
  287. // let composed_attrs = transform_attributes(&next_op1, &next_op2, true);
  288. a_prime.insert(&insert.s, insert.attributes.clone());
  289. b_prime.retain(insert.count_of_code_units(), insert.attributes.clone());
  290. next_op1 = ops1.next();
  291. },
  292. (_, Some(Operation::Insert(o_insert))) => {
  293. let composed_attrs = transform_op_attribute(&next_op1, &next_op2);
  294. a_prime.retain(o_insert.count_of_code_units(), composed_attrs.clone());
  295. b_prime.insert(&o_insert.s, composed_attrs);
  296. next_op2 = ops2.next();
  297. },
  298. (None, _) => {
  299. return Err(ErrorBuilder::new(OTErrorCode::IncompatibleLength).build());
  300. },
  301. (_, None) => {
  302. return Err(ErrorBuilder::new(OTErrorCode::IncompatibleLength).build());
  303. },
  304. (Some(Operation::Retain(retain)), Some(Operation::Retain(o_retain))) => {
  305. let composed_attrs = transform_op_attribute(&next_op1, &next_op2);
  306. match retain.cmp(&o_retain) {
  307. Ordering::Less => {
  308. a_prime.retain(retain.n, composed_attrs.clone());
  309. b_prime.retain(retain.n, composed_attrs.clone());
  310. next_op2 = Some(OpBuilder::retain(o_retain.n - retain.n).build());
  311. next_op1 = ops1.next();
  312. },
  313. Ordering::Equal => {
  314. a_prime.retain(retain.n, composed_attrs.clone());
  315. b_prime.retain(retain.n, composed_attrs.clone());
  316. next_op1 = ops1.next();
  317. next_op2 = ops2.next();
  318. },
  319. Ordering::Greater => {
  320. a_prime.retain(o_retain.n, composed_attrs.clone());
  321. b_prime.retain(o_retain.n, composed_attrs.clone());
  322. next_op1 = Some(OpBuilder::retain(retain.n - o_retain.n).build());
  323. next_op2 = ops2.next();
  324. },
  325. };
  326. },
  327. (Some(Operation::Delete(i)), Some(Operation::Delete(j))) => match i.cmp(&j) {
  328. Ordering::Less => {
  329. next_op2 = Some(OpBuilder::delete(*j - *i).build());
  330. next_op1 = ops1.next();
  331. },
  332. Ordering::Equal => {
  333. next_op1 = ops1.next();
  334. next_op2 = ops2.next();
  335. },
  336. Ordering::Greater => {
  337. next_op1 = Some(OpBuilder::delete(*i - *j).build());
  338. next_op2 = ops2.next();
  339. },
  340. },
  341. (Some(Operation::Delete(i)), Some(Operation::Retain(o_retain))) => {
  342. match i.cmp(&o_retain) {
  343. Ordering::Less => {
  344. a_prime.delete(*i);
  345. next_op2 = Some(OpBuilder::retain(o_retain.n - *i).build());
  346. next_op1 = ops1.next();
  347. },
  348. Ordering::Equal => {
  349. a_prime.delete(*i);
  350. next_op1 = ops1.next();
  351. next_op2 = ops2.next();
  352. },
  353. Ordering::Greater => {
  354. a_prime.delete(o_retain.n);
  355. next_op1 = Some(OpBuilder::delete(*i - o_retain.n).build());
  356. next_op2 = ops2.next();
  357. },
  358. };
  359. },
  360. (Some(Operation::Retain(retain)), Some(Operation::Delete(j))) => {
  361. match retain.cmp(&j) {
  362. Ordering::Less => {
  363. b_prime.delete(retain.n);
  364. next_op2 = Some(OpBuilder::delete(*j - retain.n).build());
  365. next_op1 = ops1.next();
  366. },
  367. Ordering::Equal => {
  368. b_prime.delete(retain.n);
  369. next_op1 = ops1.next();
  370. next_op2 = ops2.next();
  371. },
  372. Ordering::Greater => {
  373. b_prime.delete(*j);
  374. next_op1 = Some(OpBuilder::retain(retain.n - *j).build());
  375. next_op2 = ops2.next();
  376. },
  377. };
  378. },
  379. }
  380. }
  381. Ok((a_prime, b_prime))
  382. }
  383. fn invert(&self, other: &Self) -> Self {
  384. let mut inverted = Delta::default();
  385. if other.is_empty() {
  386. return inverted;
  387. }
  388. tracing::trace!("🌜Calculate invert delta");
  389. tracing::trace!("current: {}", self);
  390. tracing::trace!("other: {}", other);
  391. let mut index = 0;
  392. for op in &self.ops {
  393. let len: usize = op.len() as usize;
  394. match op {
  395. Operation::Delete(n) => {
  396. invert_from_other(&mut inverted, other, op, index, index + *n);
  397. index += len;
  398. },
  399. Operation::Retain(_) => {
  400. match op.has_attribute() {
  401. true => invert_from_other(&mut inverted, other, op, index, index + len),
  402. false => {
  403. tracing::trace!("invert retain: {} by retain {} {}", op, len, op.get_attributes());
  404. inverted.retain(len as usize, op.get_attributes())
  405. },
  406. }
  407. index += len;
  408. },
  409. Operation::Insert(_) => {
  410. tracing::trace!("invert insert: {} by delete {}", op, len);
  411. inverted.delete(len as usize);
  412. },
  413. }
  414. }
  415. tracing::trace!("🌛invert result: {}", inverted);
  416. inverted
  417. }
  418. }
  419. fn invert_from_other(base: &mut Delta, other: &Delta, operation: &Operation, start: usize, end: usize) {
  420. tracing::trace!("invert op: {} [{}:{}]", operation, start, end);
  421. let other_ops = DeltaIter::from_interval(other, Interval::new(start, end)).ops();
  422. other_ops.into_iter().for_each(|other_op| match operation {
  423. Operation::Delete(n) => {
  424. tracing::trace!("invert delete: {} by add {}", n, other_op);
  425. base.add(other_op);
  426. },
  427. Operation::Retain(_retain) => {
  428. tracing::trace!(
  429. "invert attributes: {:?}, {:?}",
  430. operation.get_attributes(),
  431. other_op.get_attributes()
  432. );
  433. let inverted_attrs = operation.get_attributes().invert(&other_op.get_attributes());
  434. base.retain(other_op.len(), inverted_attrs);
  435. },
  436. Operation::Insert(_) => {
  437. log::error!("Impossible to here. Insert operation should be treated as delete")
  438. },
  439. });
  440. }
  441. fn transform_op_attribute(left: &Option<Operation>, right: &Option<Operation>) -> Attributes {
  442. if left.is_none() {
  443. if right.is_none() {
  444. return Attributes::default();
  445. }
  446. return right.as_ref().unwrap().get_attributes();
  447. }
  448. let left = left.as_ref().unwrap().get_attributes();
  449. let right = right.as_ref().unwrap().get_attributes();
  450. // TODO: It's ok to unwrap?
  451. left.transform(&right).unwrap().0
  452. }