forge
Explore
Log in

Don't you dare go Hollow

project_note

Clone
★ 0

0 watching0 forksRust3.6 MiBc49f5e7Tahinli1 month ago2 commits

map_state.rs721 lines, 23.8 KiBHistoryRawDownload
1use std::{collections::BTreeMap, sync::Weak};
2
3use loro_common::{ContainerID, IdLp, LoroResult, PeerID};
4use rustc_hash::FxHashMap;
5use smallvec::SmallVec;
6
7use crate::{
8 configure::Configure,
9 container::{idx::ContainerIdx, map::MapSet},
10 delta::{MapValue, ResolvedMapDelta, ResolvedMapValue},
11 diff_calc::DiffMode,
12 event::{Diff, Index, InternalDiff},
13 handler::ValueOrHandler,
14 op::{Op, RawOp, RawOpContent},
15 InternalString, LoroDocInner, LoroValue,
16};
17
18use super::{ApplyLocalOpReturn, ContainerState, DiffApplyContext};
19
20const TINY_MAP_MAX: usize = 4;
21
22/// Apply the mergeable marker → `Container` boundary translation when a parent cid is known.
23///
24/// `MapState` is used both with and without a registered parent cid (e.g. during decode), so the
25/// translation no-ops when the parent is missing — markers stay as their stored `Binary` form.
26fn translate_with_parent(
27 parent_id: Option<&ContainerID>,
28 key: &InternalString,
29 value: LoroValue,
30) -> LoroValue {
31 match parent_id {
32 Some(parent) => loro_common::translate_mergeable_marker_value(parent, key.as_ref(), value),
33 None => value,
34 }
35}
36
37#[derive(Debug, Clone)]
38enum MapEntries {
39 SortedTiny(SmallVec<[(InternalString, MapValue); 1]>),
40 Tree(BTreeMap<InternalString, MapValue>),
41}
42
43impl Default for MapEntries {
44 fn default() -> Self {
45 Self::SortedTiny(SmallVec::new())
46 }
47}
48
49enum MapEntriesIter<'a> {
50 SortedTiny(std::slice::Iter<'a, (InternalString, MapValue)>),
51 Tree(std::collections::btree_map::Iter<'a, InternalString, MapValue>),
52}
53
54impl<'a> Iterator for MapEntriesIter<'a> {
55 type Item = (&'a InternalString, &'a MapValue);
56
57 fn next(&mut self) -> Option<Self::Item> {
58 match self {
59 Self::SortedTiny(iter) => iter.next().map(|(key, value)| (key, value)),
60 Self::Tree(iter) => iter.next(),
61 }
62 }
63}
64
65impl MapEntries {
66 fn debug_assert_sorted_tiny(entries: &[(InternalString, MapValue)]) {
67 debug_assert!(entries.windows(2).all(|pair| {
68 let left = &pair[0].0;
69 let right = &pair[1].0;
70 left < right
71 }));
72 }
73
74 fn is_empty(&self) -> bool {
75 match self {
76 Self::SortedTiny(entries) => entries.is_empty(),
77 Self::Tree(map) => map.is_empty(),
78 }
79 }
80
81 fn get(&self, key: &InternalString) -> Option<&MapValue> {
82 match self {
83 Self::SortedTiny(entries) => {
84 Self::debug_assert_sorted_tiny(entries);
85 entries
86 .binary_search_by(|(entry_key, _)| entry_key.cmp(key))
87 .ok()
88 .map(|index| &entries[index].1)
89 }
90 Self::Tree(map) => map.get(key),
91 }
92 }
93
94 fn insert(&mut self, key: InternalString, value: MapValue) -> Option<MapValue> {
95 match self {
96 Self::SortedTiny(entries) => {
97 Self::debug_assert_sorted_tiny(entries);
98 match entries.binary_search_by(|(entry_key, _)| entry_key.cmp(&key)) {
99 Ok(index) => return Some(std::mem::replace(&mut entries[index].1, value)),
100 Err(index) if entries.len() < TINY_MAP_MAX => {
101 entries.insert(index, (key, value));
102 Self::debug_assert_sorted_tiny(entries);
103 return None;
104 }
105 Err(_) => {}
106 }
107
108 let mut map = BTreeMap::new();
109 for (key, value) in entries.drain(..) {
110 map.insert(key, value);
111 }
112 let result = map.insert(key, value);
113 *self = Self::Tree(map);
114 result
115 }
116 Self::Tree(map) => map.insert(key, value),
117 }
118 }
119
120 fn remove(&mut self, key: &InternalString) -> Option<MapValue> {
121 match self {
122 Self::SortedTiny(entries) => {
123 Self::debug_assert_sorted_tiny(entries);
124 entries
125 .binary_search_by(|(entry_key, _)| entry_key.cmp(key))
126 .ok()
127 .map(|index| entries.remove(index).1)
128 }
129 Self::Tree(map) => {
130 let result = map.remove(key);
131 if result.is_some() && map.len() <= TINY_MAP_MAX {
132 let entries = std::mem::take(map).into_iter().collect();
133 *self = Self::SortedTiny(entries);
134 }
135 result
136 }
137 }
138 }
139
140 fn iter(&self) -> MapEntriesIter<'_> {
141 match self {
142 Self::SortedTiny(entries) => {
143 Self::debug_assert_sorted_tiny(entries);
144 MapEntriesIter::SortedTiny(entries.iter())
145 }
146 Self::Tree(map) => MapEntriesIter::Tree(map.iter()),
147 }
148 }
149}
150
151#[derive(Debug, Clone)]
152enum ChildContainers {
153 Tiny(SmallVec<[(ContainerID, InternalString); 1]>),
154 Map(FxHashMap<ContainerID, InternalString>),
155}
156
157impl Default for ChildContainers {
158 fn default() -> Self {
159 Self::Tiny(SmallVec::new())
160 }
161}
162
163impl ChildContainers {
164 fn get(&self, id: &ContainerID) -> Option<&InternalString> {
165 match self {
166 Self::Tiny(entries) => entries
167 .iter()
168 .find_map(|(entry_id, key)| (entry_id == id).then_some(key)),
169 Self::Map(map) => map.get(id),
170 }
171 }
172
173 fn contains_key(&self, id: &ContainerID) -> bool {
174 self.get(id).is_some()
175 }
176
177 fn insert(&mut self, id: ContainerID, key: InternalString) -> Option<InternalString> {
178 match self {
179 Self::Tiny(entries) => {
180 if let Some((_, old_key)) = entries.iter_mut().find(|(entry_id, _)| entry_id == &id)
181 {
182 return Some(std::mem::replace(old_key, key));
183 }
184
185 if entries.len() < TINY_MAP_MAX {
186 entries.push((id, key));
187 return None;
188 }
189
190 let mut map = FxHashMap::default();
191 for (id, key) in entries.drain(..) {
192 map.insert(id, key);
193 }
194 let result = map.insert(id, key);
195 *self = Self::Map(map);
196 result
197 }
198 Self::Map(map) => map.insert(id, key),
199 }
200 }
201
202 fn remove(&mut self, id: &ContainerID) -> Option<InternalString> {
203 match self {
204 Self::Tiny(entries) => entries
205 .iter()
206 .position(|(entry_id, _)| entry_id == id)
207 .map(|index| entries.swap_remove(index).1),
208 Self::Map(map) => {
209 let result = map.remove(id);
210 if result.is_some() && map.len() <= TINY_MAP_MAX {
211 let entries = std::mem::take(map).into_iter().collect();
212 *self = Self::Tiny(entries);
213 }
214 result
215 }
216 }
217 }
218}
219
220#[derive(Debug, Clone)]
221pub struct MapState {
222 idx: ContainerIdx,
223 map: MapEntries,
224 /// Parent-edge index for regular child containers (`MapValue::Container`). Mergeable child
225 /// edges are resolved by `DocState` from their deterministic cid and this map's marker
226 /// value, not stored here.
227 child_containers: ChildContainers,
228 size: usize,
229}
230
231impl ContainerState for MapState {
232 fn container_idx(&self) -> ContainerIdx {
233 self.idx
234 }
235
236 fn is_state_empty(&self) -> bool {
237 self.map.is_empty()
238 }
239
240 fn apply_diff_and_convert(
241 &mut self,
242 diff: InternalDiff,
243 DiffApplyContext { doc, mode }: DiffApplyContext,
244 ) -> Diff {
245 let InternalDiff::Map(delta) = diff else {
246 unreachable!()
247 };
248 let doc = &doc.upgrade().unwrap();
249 // The parent cid is the binding side of a mergeable child marker. Cached here so we
250 // translate marker values into Container values once per delta apply instead of per entry.
251 let parent_id = doc.arena.idx_to_id(self.idx);
252 let force = matches!(mode, DiffMode::Checkout | DiffMode::Linear);
253 let mut resolved_delta = ResolvedMapDelta::new();
254 for (key, value) in delta.updated.into_iter() {
255 let Some(value) = value else {
256 // uncreate op
257 assert_eq!(mode, DiffMode::Checkout);
258 self.remove(&key);
259 resolved_delta = resolved_delta.with_entry(key, ResolvedMapValue::new_unset());
260 continue;
261 };
262
263 let mut changed = false;
264 if force {
265 let prev = self.insert(key.clone(), value.clone());
266 // A checkout diff carries every key whose winning op changed,
267 // including ones whose value did not (see `MapDiffCalculator`):
268 // those only refresh the lamport/peer and report no change.
269 changed = mode != DiffMode::Checkout
270 || !matches!(prev, Some(prev) if prev.value == value.value);
271 } else {
272 match self.map.get(&key) {
273 Some(old_value) if old_value > &value => {}
274 _ => {
275 self.insert(key.clone(), value.clone());
276 changed = true;
277 }
278 }
279 }
280
281 if changed {
282 resolved_delta = resolved_delta.with_entry(
283 key.clone(),
284 ResolvedMapValue {
285 idlp: IdLp::new(value.peer, value.lamp),
286 value: value
287 .value
288 .map(|v| translate_with_parent(parent_id.as_ref(), &key, v))
289 .map(|v| ValueOrHandler::from_value(v, doc)),
290 },
291 )
292 }
293 }
294
295 Diff::Map(resolved_delta)
296 }
297
298 fn apply_diff(&mut self, diff: InternalDiff, ctx: DiffApplyContext) -> LoroResult<()> {
299 let _ = self.apply_diff_and_convert(diff, ctx);
300 Ok(())
301 }
302
303 fn apply_local_op(&mut self, op: &RawOp, _: &Op) -> LoroResult<ApplyLocalOpReturn> {
304 let mut ans: ApplyLocalOpReturn = Default::default();
305 match &op.content {
306 RawOpContent::Map(MapSet { key, value }) => {
307 let prev = self.insert(
308 key.clone(),
309 MapValue {
310 lamp: op.lamport,
311 peer: op.id.peer,
312 value: value.clone(),
313 },
314 );
315
316 if let Some(MapValue {
317 value: Some(LoroValue::Container(c)),
318 ..
319 }) = prev
320 {
321 ans.deleted_containers.push(c);
322 }
323 }
324 _ => unreachable!(),
325 }
326
327 Ok(ans)
328 }
329
330 #[doc = " Convert a state to a diff that when apply this diff on a empty state,"]
331 #[doc = " the state will be the same as this state."]
332 fn to_diff(&mut self, doc: &Weak<LoroDocInner>) -> Diff {
333 let doc_strong = doc.upgrade().unwrap();
334 let parent_id = doc_strong.arena.idx_to_id(self.idx);
335 // Build resolved values directly instead of going through
336 // `ResolvedMapValue::from_map_value`: that path forced a full `MapValue` clone per entry
337 // just to overwrite `.value` with the translated form. Cloning only the inner
338 // `Option<LoroValue>` is enough and saves an alloc per entry on every state-to-diff.
339 Diff::Map(ResolvedMapDelta {
340 updated: self
341 .map
342 .iter()
343 .map(|(k, v)| {
344 let value = v
345 .value
346 .clone()
347 .map(|val| translate_with_parent(parent_id.as_ref(), k, val))
348 .map(|val| ValueOrHandler::from_value(val, &doc_strong));
349 (
350 k.clone(),
351 ResolvedMapValue {
352 idlp: IdLp::new(v.peer, v.lamp),
353 value,
354 },
355 )
356 })
357 .collect::<FxHashMap<_, _>>(),
358 })
359 }
360
361 fn get_value(&mut self) -> LoroValue {
362 let ans = self.to_map();
363 LoroValue::Map(ans.into())
364 }
365
366 fn get_child_index(&self, id: &ContainerID) -> Option<Index> {
367 self.child_containers.get(id).map(|x| Index::Key(x.clone()))
368 }
369
370 fn contains_child(&self, id: &ContainerID) -> bool {
371 self.child_containers.contains_key(id)
372 }
373
374 fn get_child_containers(&self) -> Vec<ContainerID> {
375 let mut ans = Vec::new();
376 for (_, value) in self.map.iter() {
377 if let Some(LoroValue::Container(x)) = &value.value {
378 ans.push(x.clone());
379 }
380 }
381 ans
382 }
383
384 fn fork(&self, _config: &Configure) -> Self {
385 self.clone()
386 }
387}
388
389impl MapState {
390 pub fn new(idx: ContainerIdx) -> Self {
391 Self {
392 idx,
393 map: Default::default(),
394 child_containers: Default::default(),
395 size: 0,
396 }
397 }
398
399 pub fn insert(&mut self, key: InternalString, value: MapValue) -> Option<MapValue> {
400 let value_yes = value.value.is_some();
401 let new_child = match &value.value {
402 Some(LoroValue::Container(id)) => {
403 self.child_containers.insert(id.clone(), key.clone());
404 Some(id.clone())
405 }
406 _ => None,
407 };
408
409 let result = self.map.insert(key.clone(), value);
410 if let Some(Some(LoroValue::Container(c))) = result.as_ref().map(|x| &x.value) {
411 // Re-inserting the same child (e.g. a metadata-only checkout update)
412 // must keep its parent edge.
413 if new_child.as_ref() != Some(c) {
414 self.child_containers.remove(c);
415 }
416 }
417
418 match (&result, value_yes) {
419 (Some(x), true) if x.value.is_none() => {
420 self.size += 1;
421 }
422 (None, true) => {
423 self.size += 1;
424 }
425 (Some(x), false) if x.value.is_some() => {
426 self.size -= 1;
427 }
428 _ => {}
429 };
430
431 result
432 }
433
434 pub fn remove(&mut self, key: &InternalString) {
435 let result = self.map.remove(key);
436 if let Some(x) = result {
437 if x.value.is_some() {
438 self.size -= 1;
439 }
440 if let Some(LoroValue::Container(id)) = x.value {
441 self.child_containers.remove(&id);
442 }
443 };
444 }
445
446 pub fn iter(&self) -> impl Iterator<Item = (&InternalString, &MapValue)> {
447 self.map.iter()
448 }
449
450 fn to_map(&self) -> FxHashMap<String, LoroValue> {
451 let mut ans = FxHashMap::with_capacity_and_hasher(self.len(), Default::default());
452 for (key, value) in self.map.iter() {
453 if value.value.is_none() {
454 continue;
455 }
456
457 ans.insert(key.to_string(), value.value.as_ref().cloned().unwrap());
458 }
459
460 ans
461 }
462
463 pub fn get(&self, k: &str) -> Option<&LoroValue> {
464 match self.map.get(&k.into()) {
465 Some(value) => match &value.value {
466 Some(v) => Some(v),
467 None => None,
468 },
469 None => None,
470 }
471 }
472
473 pub fn len(&self) -> usize {
474 self.size
475 }
476
477 pub fn get_last_edit_peer(&self, key: &str) -> Option<PeerID> {
478 self.map.get(&key.into()).map(|v| v.peer)
479 }
480}
481
482mod snapshot {
483
484 use std::collections::BTreeMap;
485
486 use loro_common::{InternalString, LoroValue};
487 use rustc_hash::FxHashSet;
488 use serde_columnar::Itertools;
489
490 use crate::{
491 delta::MapValue,
492 encoding::value_register::ValueRegister,
493 state::{
494 decode_peer_from_table, decode_peer_table, read_state_leb_u64, state_decode_error,
495 ContainerCreationContext, ContainerState, FastStateSnapshot,
496 },
497 };
498
499 use super::MapState;
500
501 impl FastStateSnapshot for MapState {
502 fn encode_snapshot_fast<W: std::io::prelude::Write>(&mut self, mut w: W) {
503 // 1. LoroValue
504 // 2. Vec<String> keys_with_none_value
505 // 3. leb128 peer_num + peers (in u64)
506 // 3. Groups of (leb128 peer_idx, leb128 lamport), each has a respective map entry
507 // from either 1 or 2 when they all sorted by the key strings
508 let value = self.get_value().into_map().unwrap();
509 postcard::to_io(&*value, &mut w).unwrap();
510
511 let keys_with_none_value = self
512 .map
513 .iter()
514 .filter_map(|(k, v)| if v.value.is_some() { None } else { Some(k) })
515 .collect_vec();
516 postcard::to_io(&keys_with_none_value, &mut w).unwrap();
517 let mut peer_register = ValueRegister::new();
518 for (_, v) in self.map.iter() {
519 peer_register.register(&v.peer);
520 }
521
522 leb128::write::unsigned(&mut w, peer_register.vec().len() as u64).unwrap();
523 for p in peer_register.vec() {
524 w.write_all(&p.to_le_bytes()).unwrap();
525 }
526 let mut keys: Vec<&InternalString> = self.map.iter().map(|(key, _)| key).collect();
527 keys.sort_unstable();
528 for key in keys.into_iter() {
529 let value = self.map.get(key).unwrap();
530 let peer_idx = peer_register.register(&value.peer);
531 leb128::write::unsigned(&mut w, peer_idx as u64).unwrap();
532 leb128::write::unsigned(&mut w, value.lamp as u64).unwrap();
533 }
534 }
535
536 fn decode_value(bytes: &[u8]) -> loro_common::LoroResult<(loro_common::LoroValue, &[u8])> {
537 crate::state::value_decode::decode_collection(bytes, true)
538 }
539
540 fn decode_snapshot_fast(
541 idx: crate::container::idx::ContainerIdx,
542 (value, bytes): (loro_common::LoroValue, &[u8]),
543 _ctx: ContainerCreationContext,
544 ) -> loro_common::LoroResult<Self>
545 where
546 Self: Sized,
547 {
548 let value = value.into_map().unwrap();
549 // keys_with_none_value
550 let (keys_with_none_value, mut bytes) =
551 postcard::take_from_bytes::<Vec<InternalString>>(bytes).map_err(|_| {
552 loro_common::LoroError::DecodeError(
553 "Decode map keys_with_none_value failed"
554 .to_string()
555 .into_boxed_str(),
556 )
557 })?;
558 let keys_with_none_value: FxHashSet<_> = keys_with_none_value.into_iter().collect();
559
560 // peers
561 let peers = decode_peer_table(&mut bytes, "Decode map state failed")?;
562
563 //
564 let mut ans = MapState::new(idx);
565 let mut keys: Vec<_> = value.keys().map(|x| x.as_str().into()).collect();
566 keys.extend(keys_with_none_value.iter().cloned());
567 keys.sort_unstable();
568
569 for key in keys {
570 let peer_idx =
571 usize::try_from(read_state_leb_u64(&mut bytes, "Decode map state failed")?)
572 .map_err(|_| {
573 state_decode_error("Decode map state failed: peer index overflow")
574 })?;
575 let lamp =
576 u32::try_from(read_state_leb_u64(&mut bytes, "Decode map state failed")?)
577 .map_err(|_| {
578 state_decode_error("Decode map state failed: lamport overflow")
579 })?;
580 let peer = decode_peer_from_table(&peers, peer_idx, "Decode map state failed")?;
581
582 if keys_with_none_value.contains(&key) {
583 ans.insert(
584 key,
585 MapValue {
586 value: None,
587 lamp,
588 peer,
589 },
590 );
591 } else {
592 let value = value.get(&*key).unwrap();
593 ans.insert(
594 key,
595 MapValue {
596 value: Some(value.clone()),
597 lamp,
598 peer,
599 },
600 );
601 }
602 }
603
604 if !bytes.is_empty() {
605 return Err(loro_common::LoroError::DecodeError(
606 "Decode map state failed".to_string().into_boxed_str(),
607 ));
608 }
609
610 Ok(ans)
611 }
612 }
613
614 impl MapState {
615 pub(crate) fn decode_value_as_btree_map(
616 bytes: &[u8],
617 ) -> loro_common::LoroResult<(BTreeMap<String, LoroValue>, &[u8])> {
618 crate::state::value_decode::decode_btree_map(bytes)
619 }
620 }
621
622 #[cfg(test)]
623 mod map_snapshot_test {
624 use loro_common::LoroValue;
625
626 use crate::container::idx::ContainerIdx;
627
628 use super::*;
629
630 #[test]
631 fn map_fast_snapshot() {
632 let mut map = MapState::new(ContainerIdx::from_index_and_type(
633 0,
634 loro_common::ContainerType::Map,
635 ));
636 map.insert(
637 "1".into(),
638 MapValue {
639 value: None,
640 lamp: 1,
641 peer: 1,
642 },
643 );
644 map.insert(
645 "2".into(),
646 MapValue {
647 value: Some(LoroValue::I64(0)),
648 lamp: 2,
649 peer: 2,
650 },
651 );
652 map.insert(
653 "3".into(),
654 MapValue {
655 value: Some(LoroValue::Double(1.0)),
656 lamp: 3,
657 peer: 3,
658 },
659 );
660
661 let mut bytes = Vec::new();
662 map.encode_snapshot_fast(&mut bytes);
663 assert!(bytes.len() <= 50);
664
665 let (value, bytes) = MapState::decode_value(&bytes).unwrap();
666 {
667 let m = value.clone().into_map().unwrap();
668 assert_eq!(m.len(), 2);
669 assert_eq!(m.get("2").unwrap(), &LoroValue::I64(0));
670 assert_eq!(m.get("3").unwrap(), &LoroValue::Double(1.0));
671 }
672
673 let new_map = MapState::decode_snapshot_fast(
674 ContainerIdx::from_index_and_type(0, loro_common::ContainerType::Map),
675 (value, bytes),
676 ContainerCreationContext {
677 configure: &Default::default(),
678 peer: 0,
679 },
680 )
681 .unwrap();
682 let v = new_map.map.get(&"2".into()).unwrap();
683 assert_eq!(
684 v,
685 &MapValue {
686 value: Some(LoroValue::I64(0)),
687 lamp: 2,
688 peer: 2,
689 }
690 );
691 let v = new_map.map.get(&"1".into()).unwrap();
692 assert_eq!(
693 v,
694 &MapValue {
695 value: None,
696 lamp: 1,
697 peer: 1,
698 }
699 );
700 }
701
702 #[test]
703 fn map_fast_snapshot_rejects_corrupt_state_metadata() {
704 let idx = ContainerIdx::from_index_and_type(0, loro_common::ContainerType::Map);
705 let ctx = ContainerCreationContext {
706 configure: &Default::default(),
707 peer: 0,
708 };
709 let value = LoroValue::from(std::collections::HashMap::from([(
710 "key".to_string(),
711 LoroValue::I64(1),
712 )]));
713
714 let mut empty = MapState::new(idx);
715 let mut bytes = Vec::new();
716 empty.encode_snapshot_fast(&mut bytes);
717 let (_, state_bytes) = MapState::decode_value(&bytes).unwrap();
718 assert!(MapState::decode_snapshot_fast(idx, (value, state_bytes), ctx).is_err());
719 }
720 }
721}