ops.rs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668
  1. use crate::core::delta::operation::{
  2. DeltaOperation, EmptyAttributes, OperationAttributes, OperationTransform,
  3. };
  4. use crate::core::delta::{OperationIterator, MAX_IV_LEN};
  5. use crate::core::interval::Interval;
  6. use crate::core::ot_str::OTString;
  7. use crate::core::DeltaOperationBuilder;
  8. use crate::errors::{ErrorBuilder, OTError, OTErrorCode};
  9. use bytes::Bytes;
  10. use serde::de::DeserializeOwned;
  11. use std::{
  12. cmp::{min, Ordering},
  13. fmt,
  14. iter::FromIterator,
  15. str,
  16. str::FromStr,
  17. };
  18. pub type DeltaBuilder = DeltaOperationBuilder<EmptyAttributes>;
  19. /// A [Delta] contains list of operations that consists of 'Retain', 'Delete' and 'Insert' operation.
  20. /// Check out the [Operation] for more details. It describes the document as a sequence of
  21. /// operations.
  22. ///
  23. /// You could check [this](https://appflowy.gitbook.io/docs/essential-documentation/contribute-to-appflowy/architecture/backend/delta) out for more information.
  24. ///
  25. /// If the [T] supports 'serde', that will enable delta to serialize to JSON or deserialize from
  26. /// a JSON string.
  27. ///
  28. #[derive(Clone, Debug, PartialEq, Eq)]
  29. pub struct DeltaOperations<Attribute: OperationAttributes> {
  30. pub ops: Vec<DeltaOperation<Attribute>>,
  31. /// 'Delete' and 'Retain' operation will update the [utf16_base_len]
  32. /// Transforming the other delta, it requires the utf16_base_len must be equal.
  33. pub utf16_base_len: usize,
  34. /// Represents the current len of the delta.
  35. /// 'Insert' and 'Retain' operation will update the [utf16_target_len]
  36. pub utf16_target_len: usize,
  37. }
  38. impl<T> Default for DeltaOperations<T>
  39. where
  40. T: OperationAttributes,
  41. {
  42. fn default() -> Self {
  43. Self {
  44. ops: Vec::new(),
  45. utf16_base_len: 0,
  46. utf16_target_len: 0,
  47. }
  48. }
  49. }
  50. impl<T> fmt::Display for DeltaOperations<T>
  51. where
  52. T: OperationAttributes,
  53. {
  54. fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
  55. // f.write_str(&serde_json::to_string(self).unwrap_or("".to_owned()))?;
  56. f.write_str("[ ")?;
  57. for op in &self.ops {
  58. f.write_fmt(format_args!("{} ", op))?;
  59. }
  60. f.write_str("]")?;
  61. Ok(())
  62. }
  63. }
  64. impl<T> FromIterator<DeltaOperation<T>> for DeltaOperations<T>
  65. where
  66. T: OperationAttributes,
  67. {
  68. fn from_iter<I: IntoIterator<Item = DeltaOperation<T>>>(ops: I) -> Self {
  69. let mut operations = DeltaOperations::default();
  70. for op in ops {
  71. operations.add(op);
  72. }
  73. operations
  74. }
  75. }
  76. impl<T> DeltaOperations<T>
  77. where
  78. T: OperationAttributes,
  79. {
  80. pub fn new() -> Self {
  81. Self::default()
  82. }
  83. #[inline]
  84. pub fn with_capacity(capacity: usize) -> Self {
  85. Self {
  86. ops: Vec::with_capacity(capacity),
  87. utf16_base_len: 0,
  88. utf16_target_len: 0,
  89. }
  90. }
  91. /// Adding an operation. It will be added in sequence.
  92. pub fn add(&mut self, op: DeltaOperation<T>) {
  93. match op {
  94. DeltaOperation::Delete(i) => self.delete(i),
  95. DeltaOperation::Insert(i) => self.insert(&i.s, i.attributes),
  96. DeltaOperation::Retain(r) => self.retain(r.n, r.attributes),
  97. }
  98. }
  99. /// Creating a [Delete] operation with len [n]
  100. pub fn delete(&mut self, n: usize) {
  101. if n == 0 {
  102. return;
  103. }
  104. self.utf16_base_len += n;
  105. if let Some(DeltaOperation::Delete(n_last)) = self.ops.last_mut() {
  106. *n_last += n;
  107. } else {
  108. self.ops.push(DeltaOperation::delete(n));
  109. }
  110. }
  111. /// Creating a [Insert] operation with string, [s].
  112. pub fn insert(&mut self, s: &str, attributes: T) {
  113. let s: OTString = s.into();
  114. if s.is_empty() {
  115. return;
  116. }
  117. self.utf16_target_len += s.utf16_len();
  118. let new_last = match self.ops.as_mut_slice() {
  119. [.., DeltaOperation::<T>::Insert(insert)] => {
  120. //
  121. insert.merge_or_new_op(&s, attributes)
  122. },
  123. [.., DeltaOperation::<T>::Insert(pre_insert), DeltaOperation::Delete(_)] => {
  124. //
  125. pre_insert.merge_or_new_op(&s, attributes)
  126. },
  127. [.., op_last @ DeltaOperation::<T>::Delete(_)] => {
  128. let new_last = op_last.clone();
  129. *op_last = DeltaOperation::<T>::insert_with_attributes(&s, attributes);
  130. Some(new_last)
  131. },
  132. _ => Some(DeltaOperation::<T>::insert_with_attributes(&s, attributes)),
  133. };
  134. match new_last {
  135. None => {},
  136. Some(new_last) => self.ops.push(new_last),
  137. }
  138. }
  139. /// Creating a [Retain] operation with len, [n].
  140. pub fn retain(&mut self, n: usize, attributes: T) {
  141. if n == 0 {
  142. return;
  143. }
  144. self.utf16_base_len += n;
  145. self.utf16_target_len += n;
  146. if let Some(DeltaOperation::<T>::Retain(retain)) = self.ops.last_mut() {
  147. if let Some(new_op) = retain.merge_or_new(n, attributes) {
  148. self.ops.push(new_op);
  149. }
  150. } else {
  151. self
  152. .ops
  153. .push(DeltaOperation::<T>::retain_with_attributes(n, attributes));
  154. }
  155. }
  156. /// Return the a new string described by this delta. The new string will contains the input string.
  157. /// The length of the [applied_str] must be equal to the the [utf16_base_len].
  158. ///
  159. /// # Arguments
  160. ///
  161. /// * `applied_str`: A string represents the utf16_base_len content. it will be consumed by the [retain]
  162. /// or [delete] operations.
  163. ///
  164. ///
  165. /// # Examples
  166. ///
  167. /// ```
  168. /// use lib_ot::core::DeltaBuilder;
  169. /// let s = "hello";
  170. /// let delta_a = DeltaBuilder::new().insert(s).build();
  171. /// let delta_b = DeltaBuilder::new()
  172. /// .retain(s.len())
  173. /// .insert(", AppFlowy")
  174. /// .build();
  175. ///
  176. /// let after_a = delta_a.content().unwrap();
  177. /// let after_b = delta_b.apply(&after_a).unwrap();
  178. /// assert_eq!("hello, AppFlowy", &after_b);
  179. /// ```
  180. pub fn apply(&self, applied_str: &str) -> Result<String, OTError> {
  181. let applied_str: OTString = applied_str.into();
  182. if applied_str.utf16_len() != self.utf16_base_len {
  183. return Err(
  184. ErrorBuilder::new(OTErrorCode::IncompatibleLength)
  185. .msg(format!(
  186. "Expected: {}, but received: {}",
  187. self.utf16_base_len,
  188. applied_str.utf16_len()
  189. ))
  190. .build(),
  191. );
  192. }
  193. let mut new_s = String::new();
  194. let code_point_iter = &mut applied_str.utf16_iter();
  195. for op in &self.ops {
  196. match &op {
  197. DeltaOperation::Retain(retain) => {
  198. for c in code_point_iter.take(retain.n) {
  199. new_s.push_str(str::from_utf8(c.0).unwrap_or(""));
  200. }
  201. },
  202. DeltaOperation::Delete(delete) => {
  203. for _ in 0..*delete {
  204. code_point_iter.next();
  205. }
  206. },
  207. DeltaOperation::Insert(insert) => {
  208. new_s += &insert.s;
  209. },
  210. }
  211. }
  212. Ok(new_s)
  213. }
  214. pub fn inverted(&self) -> Self {
  215. self.invert_str("")
  216. }
  217. /// Computes the inverse [Delta]. The inverse of an operation is the
  218. /// operation that reverts the effects of the operation
  219. /// # Arguments
  220. ///
  221. /// * `inverted_s`: A string represents the utf16_base_len content. The len of [inverted_s]
  222. /// must equal to the [utf16_base_len], it will be consumed by the [retain] or [delete] operations.
  223. ///
  224. /// If the delta's operations just contain a insert operation. The inverted_s must be empty string.
  225. ///
  226. /// # Examples
  227. ///
  228. /// ```
  229. /// use lib_ot::core::DeltaBuilder;
  230. /// let s = "hello world";
  231. /// let delta = DeltaBuilder::new().insert(s).build();
  232. /// let invert_delta = delta.invert_str(s);
  233. /// assert_eq!(delta.utf16_base_len, invert_delta.utf16_target_len);
  234. /// assert_eq!(delta.utf16_target_len, invert_delta.utf16_base_len);
  235. ///
  236. /// assert_eq!(invert_delta.apply(s).unwrap(), "")
  237. ///
  238. /// ```
  239. ///
  240. pub fn invert_str(&self, inverted_s: &str) -> Self {
  241. let mut inverted = DeltaOperations::default();
  242. let inverted_s: OTString = inverted_s.into();
  243. let code_point_iter = &mut inverted_s.utf16_iter();
  244. for op in &self.ops {
  245. match &op {
  246. DeltaOperation::Retain(retain) => {
  247. inverted.retain(retain.n, T::default());
  248. for _ in 0..retain.n {
  249. code_point_iter.next();
  250. }
  251. },
  252. DeltaOperation::Insert(insert) => {
  253. inverted.delete(insert.utf16_size());
  254. },
  255. DeltaOperation::Delete(delete) => {
  256. let bytes = code_point_iter
  257. .take(*delete)
  258. .flat_map(|a| str::from_utf8(a.0).ok())
  259. .collect::<String>();
  260. inverted.insert(&bytes, op.get_attributes());
  261. },
  262. }
  263. }
  264. inverted
  265. }
  266. /// Return true if the delta doesn't contain any [Insert] or [Delete] operations.
  267. pub fn is_noop(&self) -> bool {
  268. matches!(self.ops.as_slice(), [] | [DeltaOperation::Retain(_)])
  269. }
  270. pub fn is_empty(&self) -> bool {
  271. self.ops.is_empty()
  272. }
  273. pub fn extend(&mut self, other: Self) {
  274. other.ops.into_iter().for_each(|op| self.add(op));
  275. }
  276. /// Get the content that the [Delta] represents.
  277. pub fn content(&self) -> Result<String, OTError> {
  278. self.apply("")
  279. }
  280. }
  281. impl<T> OperationTransform for DeltaOperations<T>
  282. where
  283. T: OperationAttributes,
  284. {
  285. fn compose(&self, other: &Self) -> Result<Self, OTError>
  286. where
  287. Self: Sized,
  288. {
  289. let mut new_delta = DeltaOperations::default();
  290. let mut iter = OperationIterator::new(self);
  291. let mut other_iter = OperationIterator::new(other);
  292. while iter.has_next() || other_iter.has_next() {
  293. if other_iter.is_next_insert() {
  294. new_delta.add(other_iter.next_op().unwrap());
  295. continue;
  296. }
  297. if iter.is_next_delete() {
  298. new_delta.add(iter.next_op().unwrap());
  299. continue;
  300. }
  301. let length = min(
  302. iter.next_op_len().unwrap_or(MAX_IV_LEN),
  303. other_iter.next_op_len().unwrap_or(MAX_IV_LEN),
  304. );
  305. let op = iter
  306. .next_op_with_len(length)
  307. .unwrap_or_else(|| DeltaOperation::retain(length));
  308. let other_op = other_iter
  309. .next_op_with_len(length)
  310. .unwrap_or_else(|| DeltaOperation::retain(length));
  311. // debug_assert_eq!(op.len(), other_op.len(), "Composing delta failed,");
  312. match (&op, &other_op) {
  313. (DeltaOperation::Retain(retain), DeltaOperation::Retain(other_retain)) => {
  314. let composed_attrs = retain.attributes.compose(&other_retain.attributes)?;
  315. new_delta.add(DeltaOperation::retain_with_attributes(
  316. retain.n,
  317. composed_attrs,
  318. ))
  319. },
  320. (DeltaOperation::Insert(insert), DeltaOperation::Retain(other_retain)) => {
  321. let mut composed_attrs = insert.attributes.compose(&other_retain.attributes)?;
  322. composed_attrs.remove();
  323. new_delta.add(DeltaOperation::insert_with_attributes(
  324. op.get_data(),
  325. composed_attrs,
  326. ))
  327. },
  328. (DeltaOperation::Retain(_), DeltaOperation::Delete(_)) => {
  329. new_delta.add(other_op);
  330. },
  331. (a, b) => {
  332. debug_assert!(a.is_insert());
  333. debug_assert!(b.is_delete());
  334. continue;
  335. },
  336. }
  337. }
  338. Ok(new_delta)
  339. }
  340. fn transform(&self, other: &Self) -> Result<(Self, Self), OTError>
  341. where
  342. Self: Sized,
  343. {
  344. if self.utf16_base_len != other.utf16_base_len {
  345. return Err(
  346. ErrorBuilder::new(OTErrorCode::IncompatibleLength)
  347. .msg(format!(
  348. "cur base length: {}, other base length: {}",
  349. self.utf16_base_len, other.utf16_base_len
  350. ))
  351. .build(),
  352. );
  353. }
  354. let mut a_prime = DeltaOperations::default();
  355. let mut b_prime = DeltaOperations::default();
  356. let mut ops1 = self.ops.iter().cloned();
  357. let mut ops2 = other.ops.iter().cloned();
  358. let mut next_op1 = ops1.next();
  359. let mut next_op2 = ops2.next();
  360. loop {
  361. match (&next_op1, &next_op2) {
  362. (None, None) => break,
  363. (Some(DeltaOperation::Insert(insert)), _) => {
  364. // let composed_attrs = transform_attributes(&next_op1, &next_op2, true);
  365. a_prime.insert(&insert.s, insert.attributes.clone());
  366. b_prime.retain(insert.utf16_size(), insert.attributes.clone());
  367. next_op1 = ops1.next();
  368. },
  369. (_, Some(DeltaOperation::Insert(o_insert))) => {
  370. let composed_attrs = transform_op_attribute(&next_op1, &next_op2)?;
  371. a_prime.retain(o_insert.utf16_size(), composed_attrs.clone());
  372. b_prime.insert(&o_insert.s, composed_attrs);
  373. next_op2 = ops2.next();
  374. },
  375. (None, _) => {
  376. return Err(ErrorBuilder::new(OTErrorCode::IncompatibleLength).build());
  377. },
  378. (_, None) => {
  379. return Err(ErrorBuilder::new(OTErrorCode::IncompatibleLength).build());
  380. },
  381. (Some(DeltaOperation::Retain(retain)), Some(DeltaOperation::Retain(o_retain))) => {
  382. let composed_attrs = transform_op_attribute(&next_op1, &next_op2)?;
  383. match retain.cmp(o_retain) {
  384. Ordering::Less => {
  385. a_prime.retain(retain.n, composed_attrs.clone());
  386. b_prime.retain(retain.n, composed_attrs.clone());
  387. next_op2 = Some(DeltaOperation::retain(o_retain.n - retain.n));
  388. next_op1 = ops1.next();
  389. },
  390. Ordering::Equal => {
  391. a_prime.retain(retain.n, composed_attrs.clone());
  392. b_prime.retain(retain.n, composed_attrs.clone());
  393. next_op1 = ops1.next();
  394. next_op2 = ops2.next();
  395. },
  396. Ordering::Greater => {
  397. a_prime.retain(o_retain.n, composed_attrs.clone());
  398. b_prime.retain(o_retain.n, composed_attrs.clone());
  399. next_op1 = Some(DeltaOperation::retain(retain.n - o_retain.n));
  400. next_op2 = ops2.next();
  401. },
  402. };
  403. },
  404. (Some(DeltaOperation::Delete(i)), Some(DeltaOperation::Delete(j))) => match i.cmp(j) {
  405. Ordering::Less => {
  406. next_op2 = Some(DeltaOperation::delete(*j - *i));
  407. next_op1 = ops1.next();
  408. },
  409. Ordering::Equal => {
  410. next_op1 = ops1.next();
  411. next_op2 = ops2.next();
  412. },
  413. Ordering::Greater => {
  414. next_op1 = Some(DeltaOperation::delete(*i - *j));
  415. next_op2 = ops2.next();
  416. },
  417. },
  418. (Some(DeltaOperation::Delete(i)), Some(DeltaOperation::Retain(o_retain))) => {
  419. match i.cmp(o_retain) {
  420. Ordering::Less => {
  421. a_prime.delete(*i);
  422. next_op2 = Some(DeltaOperation::retain(o_retain.n - *i));
  423. next_op1 = ops1.next();
  424. },
  425. Ordering::Equal => {
  426. a_prime.delete(*i);
  427. next_op1 = ops1.next();
  428. next_op2 = ops2.next();
  429. },
  430. Ordering::Greater => {
  431. a_prime.delete(o_retain.n);
  432. next_op1 = Some(DeltaOperation::delete(*i - o_retain.n));
  433. next_op2 = ops2.next();
  434. },
  435. };
  436. },
  437. (Some(DeltaOperation::Retain(retain)), Some(DeltaOperation::Delete(j))) => {
  438. match retain.cmp(j) {
  439. Ordering::Less => {
  440. b_prime.delete(retain.n);
  441. next_op2 = Some(DeltaOperation::delete(*j - retain.n));
  442. next_op1 = ops1.next();
  443. },
  444. Ordering::Equal => {
  445. b_prime.delete(retain.n);
  446. next_op1 = ops1.next();
  447. next_op2 = ops2.next();
  448. },
  449. Ordering::Greater => {
  450. b_prime.delete(*j);
  451. next_op1 = Some(DeltaOperation::retain(retain.n - *j));
  452. next_op2 = ops2.next();
  453. },
  454. };
  455. },
  456. }
  457. }
  458. Ok((a_prime, b_prime))
  459. }
  460. fn invert(&self, other: &Self) -> Self {
  461. let mut inverted = DeltaOperations::default();
  462. let mut index = 0;
  463. for op in &self.ops {
  464. let len: usize = op.len();
  465. match op {
  466. DeltaOperation::Delete(n) => {
  467. invert_other(&mut inverted, other, op, index, index + *n);
  468. index += len;
  469. },
  470. DeltaOperation::Retain(_) => {
  471. match op.has_attribute() {
  472. true => invert_other(&mut inverted, other, op, index, index + len),
  473. false => {
  474. // tracing::trace!("invert retain: {} by retain {} {}", op, len,
  475. // op.get_attributes());
  476. inverted.retain(len, op.get_attributes())
  477. },
  478. }
  479. index += len;
  480. },
  481. DeltaOperation::Insert(_) => {
  482. // tracing::trace!("invert insert: {} by delete {}", op, len);
  483. inverted.delete(len);
  484. },
  485. }
  486. }
  487. inverted
  488. }
  489. }
  490. /// Removes trailing retain operation with empty attributes, if present.
  491. pub fn trim<T>(delta: &mut DeltaOperations<T>)
  492. where
  493. T: OperationAttributes,
  494. {
  495. if let Some(last) = delta.ops.last() {
  496. if last.is_retain() && last.is_plain() {
  497. delta.ops.pop();
  498. }
  499. }
  500. }
  501. fn invert_other<T: OperationAttributes>(
  502. base: &mut DeltaOperations<T>,
  503. other: &DeltaOperations<T>,
  504. operation: &DeltaOperation<T>,
  505. start: usize,
  506. end: usize,
  507. ) {
  508. tracing::trace!("invert op: {} [{}:{}]", operation, start, end);
  509. let other_ops = OperationIterator::from_interval(other, Interval::new(start, end)).ops();
  510. other_ops.into_iter().for_each(|other_op| match operation {
  511. DeltaOperation::Delete(_n) => {
  512. // tracing::trace!("invert delete: {} by add {}", n, other_op);
  513. base.add(other_op);
  514. },
  515. DeltaOperation::Retain(_retain) => {
  516. tracing::trace!(
  517. "invert attributes: {:?}, {:?}",
  518. operation.get_attributes(),
  519. other_op.get_attributes()
  520. );
  521. let inverted_attrs = operation
  522. .get_attributes()
  523. .invert(&other_op.get_attributes());
  524. base.retain(other_op.len(), inverted_attrs);
  525. },
  526. DeltaOperation::Insert(_) => {
  527. log::error!("Impossible to here. Insert operation should be treated as delete")
  528. },
  529. });
  530. }
  531. fn transform_op_attribute<T: OperationAttributes>(
  532. left: &Option<DeltaOperation<T>>,
  533. right: &Option<DeltaOperation<T>>,
  534. ) -> Result<T, OTError> {
  535. if left.is_none() {
  536. if right.is_none() {
  537. return Ok(T::default());
  538. }
  539. return Ok(right.as_ref().unwrap().get_attributes());
  540. }
  541. let left = left.as_ref().unwrap().get_attributes();
  542. let right = right.as_ref().unwrap().get_attributes();
  543. // TODO: replace with anyhow and this error.
  544. Ok(left.transform(&right)?.0)
  545. }
  546. impl<T> DeltaOperations<T>
  547. where
  548. T: OperationAttributes + DeserializeOwned,
  549. {
  550. /// # Examples
  551. ///
  552. /// ```
  553. /// use lib_ot::core::DeltaOperationBuilder;
  554. /// use lib_ot::text_delta::{DeltaTextOperations};
  555. /// let json = r#"[
  556. /// {"retain":7,"attributes":{"bold":null}}
  557. /// ]"#;
  558. /// let delta = DeltaTextOperations::from_json(json).unwrap();
  559. /// assert_eq!(delta.json_str(), r#"[{"retain":7,"attributes":{"bold":null}}]"#);
  560. /// ```
  561. pub fn from_json(json: &str) -> Result<Self, OTError> {
  562. let delta = serde_json::from_str(json).map_err(|e| {
  563. tracing::trace!("Deserialize failed: {:?}", e);
  564. tracing::trace!("{:?}", json);
  565. e
  566. })?;
  567. Ok(delta)
  568. }
  569. /// Deserialize the bytes into [Delta]. It requires the bytes is in utf8 format.
  570. pub fn from_bytes<B: AsRef<[u8]>>(bytes: B) -> Result<Self, OTError> {
  571. let json = str::from_utf8(bytes.as_ref())?.to_owned();
  572. let val = Self::from_json(&json)?;
  573. Ok(val)
  574. }
  575. }
  576. impl<T> DeltaOperations<T>
  577. where
  578. T: OperationAttributes + serde::Serialize,
  579. {
  580. /// Serialize the [Delta] into a String in JSON format
  581. pub fn json_str(&self) -> String {
  582. serde_json::to_string(self).unwrap_or_else(|_| "".to_owned())
  583. }
  584. /// Serial the [Delta] into a String in Bytes format
  585. pub fn json_bytes(&self) -> Bytes {
  586. let json = self.json_str();
  587. Bytes::from(json.into_bytes())
  588. }
  589. }
  590. impl<T> FromStr for DeltaOperations<T>
  591. where
  592. T: OperationAttributes,
  593. {
  594. type Err = ();
  595. fn from_str(s: &str) -> Result<DeltaOperations<T>, Self::Err> {
  596. let mut delta = DeltaOperations::with_capacity(1);
  597. delta.add(DeltaOperation::Insert(s.into()));
  598. Ok(delta)
  599. }
  600. }
  601. impl<T> std::convert::TryFrom<Vec<u8>> for DeltaOperations<T>
  602. where
  603. T: OperationAttributes + DeserializeOwned,
  604. {
  605. type Error = OTError;
  606. fn try_from(bytes: Vec<u8>) -> Result<Self, Self::Error> {
  607. DeltaOperations::from_bytes(bytes)
  608. }
  609. }
  610. impl<T> std::convert::TryFrom<Bytes> for DeltaOperations<T>
  611. where
  612. T: OperationAttributes + DeserializeOwned,
  613. {
  614. type Error = OTError;
  615. fn try_from(bytes: Bytes) -> Result<Self, Self::Error> {
  616. DeltaOperations::from_bytes(&bytes)
  617. }
  618. }