operation.rs 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259
  1. use crate::core::{Attribute, Attributes, Interval, OpBuilder};
  2. use bytecount::num_chars;
  3. use serde::__private::Formatter;
  4. use std::{
  5. cmp::min,
  6. fmt,
  7. ops::{Deref, DerefMut},
  8. str::Chars,
  9. };
  10. #[derive(Debug, Clone, PartialEq)]
  11. pub enum Operation {
  12. Delete(usize),
  13. Retain(Retain),
  14. Insert(Insert),
  15. }
  16. impl Operation {
  17. pub fn get_data(&self) -> &str {
  18. match self {
  19. Operation::Delete(_) => "",
  20. Operation::Retain(_) => "",
  21. Operation::Insert(insert) => &insert.s,
  22. }
  23. }
  24. pub fn get_attributes(&self) -> Attributes {
  25. match self {
  26. Operation::Delete(_) => Attributes::default(),
  27. Operation::Retain(retain) => retain.attributes.clone(),
  28. Operation::Insert(insert) => insert.attributes.clone(),
  29. }
  30. }
  31. pub fn set_attributes(&mut self, attributes: Attributes) {
  32. match self {
  33. Operation::Delete(_) => log::error!("Delete should not contains attributes"),
  34. Operation::Retain(retain) => retain.attributes = attributes,
  35. Operation::Insert(insert) => insert.attributes = attributes,
  36. }
  37. }
  38. pub fn has_attribute(&self) -> bool { !self.get_attributes().is_empty() }
  39. pub fn contain_attribute(&self, attribute: &Attribute) -> bool { self.get_attributes().contains_key(&attribute.key) }
  40. pub fn len(&self) -> usize {
  41. match self {
  42. Operation::Delete(n) => *n,
  43. Operation::Retain(r) => r.n,
  44. Operation::Insert(i) => i.num_chars(),
  45. }
  46. }
  47. pub fn is_empty(&self) -> bool { self.len() == 0 }
  48. #[allow(dead_code)]
  49. pub fn split(&self, index: usize) -> (Option<Operation>, Option<Operation>) {
  50. debug_assert!(index < self.len());
  51. let left;
  52. let right;
  53. match self {
  54. Operation::Delete(n) => {
  55. left = Some(OpBuilder::delete(index).build());
  56. right = Some(OpBuilder::delete(*n - index).build());
  57. },
  58. Operation::Retain(retain) => {
  59. left = Some(OpBuilder::delete(index).build());
  60. right = Some(OpBuilder::delete(retain.n - index).build());
  61. },
  62. Operation::Insert(insert) => {
  63. let attributes = self.get_attributes();
  64. left = Some(OpBuilder::insert(&insert.s[0..index]).attributes(attributes.clone()).build());
  65. right = Some(
  66. OpBuilder::insert(&insert.s[index..insert.num_chars()])
  67. .attributes(attributes)
  68. .build(),
  69. );
  70. },
  71. }
  72. (left, right)
  73. }
  74. pub fn shrink(&self, interval: Interval) -> Option<Operation> {
  75. let op = match self {
  76. Operation::Delete(n) => OpBuilder::delete(min(*n, interval.size())).build(),
  77. Operation::Retain(retain) => OpBuilder::retain(min(retain.n, interval.size()))
  78. .attributes(retain.attributes.clone())
  79. .build(),
  80. Operation::Insert(insert) => {
  81. if interval.start > insert.num_chars() {
  82. OpBuilder::insert("").build()
  83. } else {
  84. let chars = insert.chars().skip(interval.start);
  85. let s = &chars.take(min(interval.size(), insert.num_chars())).collect::<String>();
  86. OpBuilder::insert(s).attributes(insert.attributes.clone()).build()
  87. }
  88. },
  89. };
  90. match op.is_empty() {
  91. true => None,
  92. false => Some(op),
  93. }
  94. }
  95. pub fn is_delete(&self) -> bool {
  96. if let Operation::Delete(_) = self {
  97. return true;
  98. }
  99. false
  100. }
  101. pub fn is_insert(&self) -> bool {
  102. if let Operation::Insert(_) = self {
  103. return true;
  104. }
  105. false
  106. }
  107. pub fn is_retain(&self) -> bool {
  108. if let Operation::Retain(_) = self {
  109. return true;
  110. }
  111. false
  112. }
  113. }
  114. impl fmt::Display for Operation {
  115. fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
  116. f.write_str("{")?;
  117. match self {
  118. Operation::Delete(n) => {
  119. f.write_fmt(format_args!("delete: {}", n))?;
  120. },
  121. Operation::Retain(r) => {
  122. f.write_fmt(format_args!("{}", r))?;
  123. },
  124. Operation::Insert(i) => {
  125. f.write_fmt(format_args!("{}", i))?;
  126. },
  127. }
  128. f.write_str("}")?;
  129. Ok(())
  130. }
  131. }
  132. #[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
  133. pub struct Retain {
  134. #[serde(rename(serialize = "retain", deserialize = "retain"))]
  135. pub n: usize,
  136. #[serde(skip_serializing_if = "is_empty")]
  137. pub attributes: Attributes,
  138. }
  139. impl fmt::Display for Retain {
  140. fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
  141. if self.attributes.is_empty() {
  142. f.write_fmt(format_args!("retain: {}", self.n))
  143. } else {
  144. f.write_fmt(format_args!("retain: {}, attributes: {}", self.n, self.attributes))
  145. }
  146. }
  147. }
  148. impl Retain {
  149. pub fn merge_or_new(&mut self, n: usize, attributes: Attributes) -> Option<Operation> {
  150. log::trace!("merge_retain_or_new_op: len: {:?}, l: {} - r: {}", n, self.attributes, attributes);
  151. if self.attributes == attributes {
  152. self.n += n;
  153. None
  154. } else {
  155. Some(OpBuilder::retain(n).attributes(attributes).build())
  156. }
  157. }
  158. pub fn is_plain(&self) -> bool { self.attributes.is_empty() }
  159. }
  160. impl std::convert::From<usize> for Retain {
  161. fn from(n: usize) -> Self {
  162. Retain {
  163. n,
  164. attributes: Attributes::default(),
  165. }
  166. }
  167. }
  168. impl Deref for Retain {
  169. type Target = usize;
  170. fn deref(&self) -> &Self::Target { &self.n }
  171. }
  172. impl DerefMut for Retain {
  173. fn deref_mut(&mut self) -> &mut Self::Target { &mut self.n }
  174. }
  175. #[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
  176. pub struct Insert {
  177. #[serde(rename(serialize = "insert", deserialize = "insert"))]
  178. pub s: String,
  179. #[serde(skip_serializing_if = "is_empty")]
  180. pub attributes: Attributes,
  181. }
  182. impl fmt::Display for Insert {
  183. fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
  184. let mut s = self.s.clone();
  185. if s.ends_with("\n") {
  186. s.pop();
  187. if s.is_empty() {
  188. s = "new_line".to_owned();
  189. }
  190. }
  191. if self.attributes.is_empty() {
  192. f.write_fmt(format_args!("insert: {}", s))
  193. } else {
  194. f.write_fmt(format_args!("insert: {}, attributes: {}", s, self.attributes))
  195. }
  196. }
  197. }
  198. impl Insert {
  199. pub fn as_bytes(&self) -> &[u8] { self.s.as_bytes() }
  200. pub fn chars(&self) -> Chars<'_> { self.s.chars() }
  201. pub fn num_chars(&self) -> usize { num_chars(self.s.as_bytes()) as _ }
  202. pub fn merge_or_new_op(&mut self, s: &str, attributes: Attributes) -> Option<Operation> {
  203. if self.attributes == attributes {
  204. self.s += s;
  205. None
  206. } else {
  207. Some(OpBuilder::insert(s).attributes(attributes).build())
  208. }
  209. }
  210. }
  211. impl std::convert::From<String> for Insert {
  212. fn from(s: String) -> Self {
  213. Insert {
  214. s,
  215. attributes: Attributes::default(),
  216. }
  217. }
  218. }
  219. impl std::convert::From<&str> for Insert {
  220. fn from(s: &str) -> Self { Insert::from(s.to_owned()) }
  221. }
  222. fn is_empty(attributes: &Attributes) -> bool { attributes.is_empty() }