| 1 | use enum_as_inner::EnumAsInner; |
| 2 | use itertools::Itertools; |
| 3 | use loro_delta::{array_vec::ArrayVec, delta_trait::DeltaAttr, DeltaItem, DeltaRope}; |
| 4 | use rustc_hash::FxHashMap; |
| 5 | use serde::{Deserialize, Serialize}; |
| 6 | use smallvec::SmallVec; |
| 7 | |
| 8 | use crate::{ |
| 9 | container::richtext::richtext_state::RichtextStateChunk, |
| 10 | delta::{Delta, MapDelta, Meta, MovableListInnerDelta, ResolvedMapDelta, TreeDelta, TreeDiff}, |
| 11 | diff_calc::DiffMode, |
| 12 | handler::ValueOrHandler, |
| 13 | op::SliceWithId, |
| 14 | utils::string_slice::StringSlice, |
| 15 | InternalString, |
| 16 | }; |
| 17 | |
| 18 | use std::{borrow::Cow, hash::Hash}; |
| 19 | |
| 20 | use loro_common::{ContainerID, LoroValue, TreeID}; |
| 21 | |
| 22 | use crate::{container::idx::ContainerIdx, version::Frontiers}; |
| 23 | |
| 24 | #[derive(Debug, Clone)] |
| 25 | pub struct ContainerDiff { |
| 26 | pub id: ContainerID, |
| 27 | pub path: Vec<(ContainerID, Index)>, |
| 28 | pub(crate) idx: ContainerIdx, |
| 29 | pub is_unknown: bool, |
| 30 | pub diff: Diff, |
| 31 | |
| 32 | pub(crate) kept: Option<KeptChange>, |
| 33 | } |
| 34 | |
| 35 | impl ContainerDiff { |
| 36 | |
| 37 | |
| 38 | pub(crate) fn change(&self) -> Option<&Diff> { |
| 39 | match &self.kept { |
| 40 | None => Some(&self.diff), |
| 41 | Some(KeptChange::Unchanged) => None, |
| 42 | Some(KeptChange::Changed(d)) => Some(d), |
| 43 | } |
| 44 | } |
| 45 | } |
| 46 | |
| 47 | |
| 48 | |
| 49 | |
| 50 | |
| 51 | |
| 52 | #[derive(Debug, Clone)] |
| 53 | pub(crate) enum KeptChange { |
| 54 | Unchanged, |
| 55 | Changed(Diff), |
| 56 | } |
| 57 | |
| 58 | impl KeptChange { |
| 59 | pub(crate) fn from_diff(diff: Diff) -> Self { |
| 60 | if diff.is_empty() { |
| 61 | KeptChange::Unchanged |
| 62 | } else { |
| 63 | KeptChange::Changed(diff) |
| 64 | } |
| 65 | } |
| 66 | |
| 67 | |
| 68 | pub(crate) fn then(self, next: KeptChange) -> Self { |
| 69 | match (self, next) { |
| 70 | (KeptChange::Unchanged, x) | (x, KeptChange::Unchanged) => x, |
| 71 | (KeptChange::Changed(a), KeptChange::Changed(b)) => { |
| 72 | KeptChange::Changed(a.compose(b).unwrap()) |
| 73 | } |
| 74 | } |
| 75 | } |
| 76 | } |
| 77 | |
| 78 | |
| 79 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] |
| 80 | pub enum EventTriggerKind { |
| 81 | |
| 82 | Local, |
| 83 | |
| 84 | Import, |
| 85 | |
| 86 | Checkout, |
| 87 | } |
| 88 | |
| 89 | impl std::fmt::Display for EventTriggerKind { |
| 90 | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { |
| 91 | match self { |
| 92 | EventTriggerKind::Local => write!(f, "local"), |
| 93 | EventTriggerKind::Import => write!(f, "import"), |
| 94 | EventTriggerKind::Checkout => write!(f, "checkout"), |
| 95 | } |
| 96 | } |
| 97 | } |
| 98 | |
| 99 | impl EventTriggerKind { |
| 100 | #[inline] |
| 101 | pub fn is_local(&self) -> bool { |
| 102 | matches!(self, EventTriggerKind::Local) |
| 103 | } |
| 104 | |
| 105 | #[inline] |
| 106 | pub fn is_import(&self) -> bool { |
| 107 | matches!(self, EventTriggerKind::Import) |
| 108 | } |
| 109 | |
| 110 | #[inline] |
| 111 | pub fn is_checkout(&self) -> bool { |
| 112 | matches!(self, EventTriggerKind::Checkout) |
| 113 | } |
| 114 | } |
| 115 | |
| 116 | #[derive(Debug, Clone)] |
| 117 | pub struct DiffEvent<'a> { |
| 118 | |
| 119 | pub current_target: Option<ContainerID>, |
| 120 | |
| 121 | pub events: &'a [&'a ContainerDiff], |
| 122 | pub event_meta: &'a DocDiff, |
| 123 | } |
| 124 | |
| 125 | |
| 126 | |
| 127 | |
| 128 | |
| 129 | |
| 130 | #[derive(Debug, Clone)] |
| 131 | pub struct DocDiff { |
| 132 | pub from: Frontiers, |
| 133 | pub to: Frontiers, |
| 134 | pub origin: InternalString, |
| 135 | pub by: EventTriggerKind, |
| 136 | pub diff: Vec<ContainerDiff>, |
| 137 | } |
| 138 | |
| 139 | #[derive(Debug, Clone)] |
| 140 | pub(crate) struct InternalContainerDiff { |
| 141 | pub(crate) idx: ContainerIdx, |
| 142 | |
| 143 | pub(crate) bring_back: bool, |
| 144 | pub(crate) diff: DiffVariant, |
| 145 | |
| 146 | pub(crate) diff_mode: DiffMode, |
| 147 | |
| 148 | pub(crate) kept: Option<KeptChange>, |
| 149 | } |
| 150 | |
| 151 | #[derive(Default, Debug, Clone, EnumAsInner)] |
| 152 | pub(crate) enum DiffVariant { |
| 153 | #[default] |
| 154 | None, |
| 155 | Internal(InternalDiff), |
| 156 | External(Diff), |
| 157 | } |
| 158 | |
| 159 | |
| 160 | |
| 161 | |
| 162 | |
| 163 | |
| 164 | |
| 165 | #[derive(Debug, Clone)] |
| 166 | pub(crate) struct InternalDocDiff<'a> { |
| 167 | pub(crate) origin: InternalString, |
| 168 | pub(crate) by: EventTriggerKind, |
| 169 | |
| 170 | pub(crate) diff: Cow<'a, [InternalContainerDiff]>, |
| 171 | pub(crate) new_version: Cow<'a, Frontiers>, |
| 172 | } |
| 173 | |
| 174 | impl InternalDocDiff<'_> { |
| 175 | pub fn into_owned(self) -> InternalDocDiff<'static> { |
| 176 | InternalDocDiff { |
| 177 | origin: self.origin, |
| 178 | by: self.by, |
| 179 | diff: Cow::Owned((*self.diff).to_owned()), |
| 180 | new_version: Cow::Owned((*self.new_version).to_owned()), |
| 181 | } |
| 182 | } |
| 183 | |
| 184 | pub fn can_merge(&self, other: &Self) -> bool { |
| 185 | self.by == other.by |
| 186 | } |
| 187 | } |
| 188 | |
| 189 | pub type Path = SmallVec<[Index; 4]>; |
| 190 | |
| 191 | #[derive(Clone, PartialEq, Eq, Serialize, Deserialize, enum_as_inner::EnumAsInner)] |
| 192 | pub enum Index { |
| 193 | Key(InternalString), |
| 194 | Seq(usize), |
| 195 | Node(TreeID), |
| 196 | } |
| 197 | |
| 198 | impl std::fmt::Debug for Index { |
| 199 | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { |
| 200 | match self { |
| 201 | Self::Key(arg0) => write!(f, "Index::Key(\"{}\")", arg0), |
| 202 | Self::Seq(arg0) => write!(f, "Index::Seq({})", arg0), |
| 203 | Self::Node(arg0) => write!(f, "Index::Node({})", arg0), |
| 204 | } |
| 205 | } |
| 206 | } |
| 207 | |
| 208 | impl std::fmt::Display for Index { |
| 209 | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { |
| 210 | match self { |
| 211 | Index::Key(key) => write!(f, "{}", key), |
| 212 | Index::Seq(s) => write!(f, "{}", s), |
| 213 | Index::Node(id) => write!(f, "{}@{}", id.peer, id.counter), |
| 214 | } |
| 215 | } |
| 216 | } |
| 217 | |
| 218 | impl From<usize> for Index { |
| 219 | fn from(s: usize) -> Self { |
| 220 | Index::Seq(s) |
| 221 | } |
| 222 | } |
| 223 | |
| 224 | impl TryFrom<&str> for Index { |
| 225 | type Error = &'static str; |
| 226 | fn try_from(s: &str) -> Result<Self, &'static str> { |
| 227 | if s.is_empty() { |
| 228 | return Ok(Index::Key(InternalString::default())); |
| 229 | } |
| 230 | |
| 231 | let c = s.chars().next().unwrap(); |
| 232 | if c.is_ascii_digit() { |
| 233 | if let Ok(seq) = s.parse::<usize>() { |
| 234 | Ok(Index::Seq(seq)) |
| 235 | } else if let Ok(id) = s.try_into() { |
| 236 | Ok(Index::Node(id)) |
| 237 | } else { |
| 238 | Ok(Index::Key(InternalString::from(s))) |
| 239 | } |
| 240 | } else { |
| 241 | Ok(Index::Key(InternalString::from(s))) |
| 242 | } |
| 243 | } |
| 244 | } |
| 245 | |
| 246 | impl DiffVariant { |
| 247 | pub fn compose(self, other: Self) -> Result<Self, Self> { |
| 248 | match (self, other) { |
| 249 | (DiffVariant::Internal(a), DiffVariant::Internal(b)) => { |
| 250 | Ok(DiffVariant::Internal(a.compose(b)?)) |
| 251 | } |
| 252 | (DiffVariant::External(a), DiffVariant::External(b)) => { |
| 253 | Ok(DiffVariant::External(a.compose(b)?)) |
| 254 | } |
| 255 | (a, _) => Err(a), |
| 256 | } |
| 257 | } |
| 258 | |
| 259 | pub fn is_empty(&self) -> bool { |
| 260 | match self { |
| 261 | DiffVariant::Internal(diff) => diff.is_empty(), |
| 262 | DiffVariant::External(diff) => diff.is_empty(), |
| 263 | DiffVariant::None => true, |
| 264 | } |
| 265 | } |
| 266 | } |
| 267 | |
| 268 | #[non_exhaustive] |
| 269 | #[derive(Clone, Debug, EnumAsInner)] |
| 270 | pub(crate) enum InternalDiff { |
| 271 | ListRaw(Delta<SliceWithId>), |
| 272 | |
| 273 | RichtextRaw(DeltaRope<RichtextStateChunk, ()>), |
| 274 | Map(MapDelta), |
| 275 | Tree(TreeDelta), |
| 276 | MovableList(MovableListInnerDelta), |
| 277 | #[cfg(feature = "counter")] |
| 278 | Counter(f64), |
| 279 | Unknown, |
| 280 | } |
| 281 | |
| 282 | impl From<InternalDiff> for DiffVariant { |
| 283 | fn from(diff: InternalDiff) -> Self { |
| 284 | DiffVariant::Internal(diff) |
| 285 | } |
| 286 | } |
| 287 | |
| 288 | #[derive(Debug, Default, Clone, Copy, PartialEq, Eq)] |
| 289 | pub struct ListDeltaMeta { |
| 290 | |
| 291 | |
| 292 | |
| 293 | |
| 294 | |
| 295 | |
| 296 | |
| 297 | pub from_move: bool, |
| 298 | } |
| 299 | |
| 300 | impl Meta for ListDeltaMeta { |
| 301 | fn is_empty(&self) -> bool { |
| 302 | !self.from_move |
| 303 | } |
| 304 | |
| 305 | fn compose( |
| 306 | &mut self, |
| 307 | other: &Self, |
| 308 | type_pair: (crate::delta::DeltaType, crate::delta::DeltaType), |
| 309 | ) { |
| 310 | |
| 311 | |
| 312 | if let (crate::delta::DeltaType::Insert, crate::delta::DeltaType::Insert) = type_pair { |
| 313 | unreachable!() |
| 314 | } |
| 315 | |
| 316 | self.from_move = self.from_move || other.from_move; |
| 317 | } |
| 318 | |
| 319 | fn is_mergeable(&self, other: &Self) -> bool { |
| 320 | self.from_move == other.from_move |
| 321 | } |
| 322 | |
| 323 | fn merge(&mut self, _other: &Self) {} |
| 324 | } |
| 325 | |
| 326 | impl DeltaAttr for ListDeltaMeta { |
| 327 | fn compose(&mut self, other: &Self) { |
| 328 | self.from_move = self.from_move || other.from_move; |
| 329 | } |
| 330 | |
| 331 | fn attr_is_empty(&self) -> bool { |
| 332 | !self.from_move |
| 333 | } |
| 334 | } |
| 335 | |
| 336 | pub type ListDiffInsertItem = ArrayVec<ValueOrHandler, 8>; |
| 337 | pub type ListDiffItem = DeltaItem<ListDiffInsertItem, ListDeltaMeta>; |
| 338 | pub type ListDiff = DeltaRope<ListDiffInsertItem, ListDeltaMeta>; |
| 339 | |
| 340 | #[derive(Default, Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] |
| 341 | pub struct TextMeta(pub FxHashMap<String, LoroValue>); |
| 342 | |
| 343 | impl From<TextMeta> for FxHashMap<String, LoroValue> { |
| 344 | fn from(value: TextMeta) -> Self { |
| 345 | value.0 |
| 346 | } |
| 347 | } |
| 348 | |
| 349 | impl From<FxHashMap<String, LoroValue>> for TextMeta { |
| 350 | fn from(value: FxHashMap<String, LoroValue>) -> Self { |
| 351 | TextMeta(value) |
| 352 | } |
| 353 | } |
| 354 | |
| 355 | pub type TextDiffItem = DeltaItem<StringSlice, TextMeta>; |
| 356 | pub type TextDiff = DeltaRope<StringSlice, TextMeta>; |
| 357 | |
| 358 | impl DeltaAttr for TextMeta { |
| 359 | fn compose(&mut self, other: &Self) { |
| 360 | for (key, value) in other.0.iter() { |
| 361 | self.0.insert(key.clone(), value.clone()); |
| 362 | } |
| 363 | } |
| 364 | |
| 365 | fn attr_is_empty(&self) -> bool { |
| 366 | self.0.is_empty() |
| 367 | } |
| 368 | } |
| 369 | |
| 370 | |
| 371 | |
| 372 | |
| 373 | |
| 374 | |
| 375 | |
| 376 | |
| 377 | |
| 378 | |
| 379 | #[non_exhaustive] |
| 380 | #[derive(Clone, Debug, EnumAsInner)] |
| 381 | pub enum Diff { |
| 382 | List(ListDiff), |
| 383 | |
| 384 | |
| 385 | Text(TextDiff), |
| 386 | Map(ResolvedMapDelta), |
| 387 | Tree(TreeDiff), |
| 388 | #[cfg(feature = "counter")] |
| 389 | Counter(f64), |
| 390 | Unknown, |
| 391 | } |
| 392 | |
| 393 | impl From<Diff> for DiffVariant { |
| 394 | fn from(diff: Diff) -> Self { |
| 395 | DiffVariant::External(diff) |
| 396 | } |
| 397 | } |
| 398 | |
| 399 | impl InternalDiff { |
| 400 | pub(crate) fn is_empty(&self) -> bool { |
| 401 | match self { |
| 402 | InternalDiff::ListRaw(s) => s.is_empty(), |
| 403 | InternalDiff::RichtextRaw(t) => t.is_empty(), |
| 404 | InternalDiff::Map(m) => m.updated.is_empty(), |
| 405 | InternalDiff::Tree(t) => t.is_empty(), |
| 406 | InternalDiff::MovableList(t) => t.is_empty(), |
| 407 | |
| 408 | #[cfg(feature = "counter")] |
| 409 | InternalDiff::Counter(c) => *c == 0.0, |
| 410 | InternalDiff::Unknown => true, |
| 411 | } |
| 412 | } |
| 413 | |
| 414 | pub(crate) fn compose(self, diff: InternalDiff) -> Result<Self, Self> { |
| 415 | |
| 416 | match (self, diff) { |
| 417 | (InternalDiff::ListRaw(a), InternalDiff::ListRaw(b)) => { |
| 418 | Ok(InternalDiff::ListRaw(a.compose(b))) |
| 419 | } |
| 420 | (InternalDiff::RichtextRaw(mut a), InternalDiff::RichtextRaw(b)) => { |
| 421 | a.compose(&b); |
| 422 | Ok(InternalDiff::RichtextRaw(a)) |
| 423 | } |
| 424 | (InternalDiff::Map(a), InternalDiff::Map(b)) => Ok(InternalDiff::Map(a.compose(b))), |
| 425 | (InternalDiff::Tree(a), InternalDiff::Tree(b)) => Ok(InternalDiff::Tree(a.compose(b))), |
| 426 | (a, _) => Err(a), |
| 427 | } |
| 428 | } |
| 429 | } |
| 430 | |
| 431 | impl Diff { |
| 432 | pub fn compose_ref(&mut self, diff: &Diff) { |
| 433 | match (self, diff) { |
| 434 | (Diff::List(a), Diff::List(b)) => { |
| 435 | a.compose(b); |
| 436 | } |
| 437 | (Diff::Text(a), Diff::Text(b)) => { |
| 438 | a.compose(b); |
| 439 | } |
| 440 | (Diff::Map(a), Diff::Map(b)) => { |
| 441 | |
| 442 | |
| 443 | *a = std::mem::take(a).compose(b.clone()); |
| 444 | } |
| 445 | (Diff::Tree(a), Diff::Tree(b)) => { |
| 446 | *a = std::mem::take(a).compose(b.clone()); |
| 447 | } |
| 448 | #[cfg(feature = "counter")] |
| 449 | (Diff::Counter(a), Diff::Counter(b)) => *a += b, |
| 450 | |
| 451 | (Diff::Unknown, Diff::Unknown) => {} |
| 452 | (_, _) => unreachable!(), |
| 453 | } |
| 454 | } |
| 455 | |
| 456 | pub fn compose(self, diff: Diff) -> Result<Self, Self> { |
| 457 | |
| 458 | match (self, diff) { |
| 459 | (Diff::List(mut a), Diff::List(b)) => { |
| 460 | a.compose(&b); |
| 461 | Ok(Diff::List(a)) |
| 462 | } |
| 463 | (Diff::Text(mut a), Diff::Text(b)) => { |
| 464 | a.compose(&b); |
| 465 | Ok(Diff::Text(a)) |
| 466 | } |
| 467 | (Diff::Map(a), Diff::Map(b)) => Ok(Diff::Map(a.compose(b))), |
| 468 | |
| 469 | (Diff::Tree(a), Diff::Tree(b)) => Ok(Diff::Tree(a.compose(b))), |
| 470 | #[cfg(feature = "counter")] |
| 471 | (Diff::Counter(a), Diff::Counter(b)) => Ok(Diff::Counter(a + b)), |
| 472 | (a, _) => Err(a), |
| 473 | } |
| 474 | } |
| 475 | |
| 476 | |
| 477 | pub fn transform(&mut self, other: &Self, left_prior: bool) { |
| 478 | match (self, other) { |
| 479 | (Diff::List(a), Diff::List(b)) => a.transform_(b, left_prior), |
| 480 | (Diff::Text(a), Diff::Text(b)) => a.transform_(b, left_prior), |
| 481 | (Diff::Map(a), Diff::Map(b)) => a.transform(b, left_prior), |
| 482 | (Diff::Tree(a), Diff::Tree(b)) => a.transform(b, left_prior), |
| 483 | #[cfg(feature = "counter")] |
| 484 | (Diff::Counter(_a), Diff::Counter(_b)) => { |
| 485 | |
| 486 | } |
| 487 | _ => {} |
| 488 | } |
| 489 | } |
| 490 | |
| 491 | pub fn is_empty(&self) -> bool { |
| 492 | match self { |
| 493 | Diff::List(s) => s.is_empty(), |
| 494 | Diff::Text(t) => t.is_empty(), |
| 495 | Diff::Map(m) => m.updated.is_empty(), |
| 496 | Diff::Tree(t) => t.diff.is_empty(), |
| 497 | |
| 498 | #[cfg(feature = "counter")] |
| 499 | Diff::Counter(c) => *c == 0.0, |
| 500 | Diff::Unknown => true, |
| 501 | } |
| 502 | } |
| 503 | |
| 504 | #[allow(unused)] |
| 505 | pub(crate) fn concat(self, diff: Diff) -> Diff { |
| 506 | match (self, diff) { |
| 507 | (Diff::List(mut a), Diff::List(b)) => { |
| 508 | a.compose(&b); |
| 509 | Diff::List(a) |
| 510 | } |
| 511 | (Diff::Text(mut a), Diff::Text(b)) => { |
| 512 | a.compose(&b); |
| 513 | Diff::Text(a) |
| 514 | } |
| 515 | (Diff::Map(a), Diff::Map(b)) => { |
| 516 | let mut a = a; |
| 517 | for (k, v) in b.updated { |
| 518 | a = a.with_entry(k, v); |
| 519 | } |
| 520 | Diff::Map(a) |
| 521 | } |
| 522 | |
| 523 | (Diff::Tree(a), Diff::Tree(b)) => Diff::Tree(a.extend(b.diff)), |
| 524 | #[cfg(feature = "counter")] |
| 525 | (Diff::Counter(a), Diff::Counter(b)) => Diff::Counter(a + b), |
| 526 | _ => unreachable!(), |
| 527 | } |
| 528 | } |
| 529 | |
| 530 | |
| 531 | pub(crate) fn transform_cursor(&self, pos: usize, left_prior: bool) -> usize { |
| 532 | match self { |
| 533 | Diff::List(list) => list.transform_pos(pos, left_prior), |
| 534 | Diff::Text(text) => text.transform_pos(pos, left_prior), |
| 535 | _ => pos, |
| 536 | } |
| 537 | } |
| 538 | } |
| 539 | |
| 540 | pub fn str_to_path(s: &str) -> Option<Vec<Index>> { |
| 541 | s.split('/').map(|x| x.try_into()).try_collect().ok() |
| 542 | } |
| 543 | |
| 544 | pub fn path_to_str(path: &[Index]) -> String { |
| 545 | path.iter().map(|x| x.to_string()).join("/") |
| 546 | } |
| 547 | |
| 548 | #[cfg(test)] |
| 549 | mod test { |
| 550 | use std::sync::Arc; |
| 551 | |
| 552 | use itertools::Itertools; |
| 553 | use loro_common::LoroValue; |
| 554 | |
| 555 | use crate::{cursor::PosType, ApplyDiff, LoroDoc}; |
| 556 | |
| 557 | #[test] |
| 558 | fn test_text_event() { |
| 559 | let loro = LoroDoc::new(); |
| 560 | let _g = loro.subscribe_root(Arc::new(|event| { |
| 561 | let mut value = LoroValue::String(Default::default()); |
| 562 | value.apply_diff(&event.events.iter().map(|x| x.diff.clone()).collect_vec()); |
| 563 | assert_eq!(value, "h223ello".into()); |
| 564 | })); |
| 565 | let mut txn = loro.txn().unwrap(); |
| 566 | let text = loro.get_text("id"); |
| 567 | text.insert_with_txn(&mut txn, 0, "hello", PosType::Unicode) |
| 568 | .unwrap(); |
| 569 | text.insert_with_txn(&mut txn, 1, "223", PosType::Unicode) |
| 570 | .unwrap(); |
| 571 | txn.commit().unwrap(); |
| 572 | } |
| 573 | } |