forge
Explore
Log in

Don't you dare go Hollow

project_note

Clone
★ 0

0 watching0 forksRust3.6 MiBc49f5e7Tahinli1 month ago2 commits

encoding.rs658 lines, 21.8 KiBHistoryRawDownload
1pub(crate) mod arena;
2pub(crate) mod fast_snapshot;
3pub(crate) mod json_schema;
4mod outdated_encode_reordered;
5mod shallow_snapshot;
6pub(crate) mod value;
7pub(crate) mod value_register;
8pub(crate) use outdated_encode_reordered::{
9 decode_op, encode_op, get_op_prop, DecodedBlockBuffers, EncodedDeleteStartId,
10 IterableEncodedDeleteStartId,
11};
12use outdated_encode_reordered::{import_changes_to_oplog, ImportChangesResult};
13pub(crate) use value::OwnedValue;
14
15use crate::change::Change;
16use crate::oplog::ImportedValues;
17use crate::version::{Frontiers, VersionRange};
18use crate::LoroDoc;
19use crate::{oplog::OpLog, LoroError, VersionVector};
20use loro_common::{IdSpan, InternalString, LoroEncodeError, LoroResult, ID};
21use num_traits::{FromPrimitive, ToPrimitive};
22use std::borrow::Cow;
23
24/// The mode of the export.
25///
26/// Loro CRDT internally consists of two parts: document history and current document state.
27/// The export modes offer various options to meet different requirements.
28/// These modes do not include remote changes waiting for missing dependencies.
29/// Persist those separately with [`LoroDoc::export_pending_updates`].
30///
31/// - CRDT property: Documents maintain consistent states when they receive the same set of updates.
32/// - In real-time collaboration, peers typically only need to synchronize updates
33/// (operations/history) to achieve consistency.
34///
35/// ## Update Export
36///
37/// - Exports only the history part, containing multiple operations.
38/// - Suitable for real-time collaboration scenarios where peers only need to synchronize updates.
39///
40/// ## Snapshot Export
41///
42/// ### Default Snapshot
43///
44/// - Includes complete history and current full state.
45///
46/// ### Shallow Snapshot
47///
48/// - Contains the complete current state.
49/// - Retains partial history starting from a specified version.
50///
51/// ### State-only Snapshot
52///
53/// - Exports the state of the target version.
54/// - Includes a minimal set of operation history.
55#[non_exhaustive]
56#[derive(Debug, Clone)]
57pub enum ExportMode<'a> {
58 /// It contains the full history and the current state of the document.
59 Snapshot,
60 /// It contains the history since the `from` version vector.
61 Updates { from: Cow<'a, VersionVector> },
62 /// This mode exports the history in the specified range.
63 UpdatesInRange { spans: Cow<'a, [IdSpan]> },
64 /// The shallow snapshot only contains the history since the target frontiers
65 ShallowSnapshot(Cow<'a, Frontiers>),
66 /// The state only snapshot exports the state of the target version
67 /// with a minimal set of history (a few ops).
68 ///
69 /// It's a shallow snapshot with depth=1 at the target version.
70 /// If the target version is None, it will use the latest version as the target version.
71 StateOnly(Option<Cow<'a, Frontiers>>),
72 /// The snapshot at the specified frontiers. It contains the full history
73 /// till the target frontiers and the state at the target frontiers.
74 SnapshotAt { version: Cow<'a, Frontiers> },
75}
76
77impl<'a> ExportMode<'a> {
78 /// It contains the full history and the current state of the document.
79 pub fn snapshot() -> Self {
80 ExportMode::Snapshot
81 }
82
83 /// It contains the history since the `from` version vector.
84 pub fn updates(from: &'a VersionVector) -> Self {
85 ExportMode::Updates {
86 from: Cow::Borrowed(from),
87 }
88 }
89
90 /// It contains the history since the `from` version vector.
91 pub fn updates_owned(from: VersionVector) -> Self {
92 ExportMode::Updates {
93 from: Cow::Owned(from),
94 }
95 }
96
97 /// It contains all the history of the document.
98 pub fn all_updates() -> Self {
99 ExportMode::Updates {
100 from: Cow::Owned(Default::default()),
101 }
102 }
103
104 /// This mode exports the history in the specified range.
105 pub fn updates_in_range(spans: impl Into<Cow<'a, [IdSpan]>>) -> Self {
106 ExportMode::UpdatesInRange {
107 spans: spans.into(),
108 }
109 }
110
111 /// The shallow snapshot only contains the history since the target frontiers.
112 pub fn shallow_snapshot(frontiers: &'a Frontiers) -> Self {
113 ExportMode::ShallowSnapshot(Cow::Borrowed(frontiers))
114 }
115
116 /// The shallow snapshot only contains the history since the target frontiers.
117 pub fn shallow_snapshot_owned(frontiers: Frontiers) -> Self {
118 ExportMode::ShallowSnapshot(Cow::Owned(frontiers))
119 }
120
121 /// The shallow snapshot only contains the history since the target frontiers.
122 pub fn shallow_snapshot_since(id: ID) -> Self {
123 let frontiers = Frontiers::from_id(id);
124 ExportMode::ShallowSnapshot(Cow::Owned(frontiers))
125 }
126
127 /// The state only snapshot exports the state of the target version
128 /// with a minimal set of history (a few ops).
129 ///
130 /// It's a shallow snapshot with depth=1 at the target version.
131 /// If the target version is None, it will use the latest version as the target version.
132 pub fn state_only(frontiers: Option<&'a Frontiers>) -> Self {
133 ExportMode::StateOnly(frontiers.map(Cow::Borrowed))
134 }
135
136 /// The snapshot at the specified frontiers. It contains the full history
137 /// till the target frontiers and the state at the target frontiers.
138 pub fn snapshot_at(frontiers: &'a Frontiers) -> Self {
139 ExportMode::SnapshotAt {
140 version: Cow::Borrowed(frontiers),
141 }
142 }
143
144 /// This mode exports the history within the specified version vector.
145 pub fn updates_till(vv: &VersionVector) -> ExportMode<'static> {
146 let mut spans = Vec::with_capacity(vv.len());
147 for (peer, counter) in vv.iter() {
148 if *counter > 0 {
149 spans.push(IdSpan::new(*peer, 0, *counter));
150 }
151 }
152
153 ExportMode::UpdatesInRange {
154 spans: Cow::Owned(spans),
155 }
156 }
157}
158
159const MAGIC_BYTES: [u8; 4] = *b"loro";
160
161#[derive(Clone, Copy, Debug, PartialEq, Eq)]
162pub(crate) enum EncodeMode {
163 // This is a config option, it won't be used in encoding.
164 Auto = 255,
165 OutdatedRle = 1,
166 OutdatedSnapshot = 2,
167 FastSnapshot = 3,
168 FastUpdates = 4,
169}
170
171impl num_traits::FromPrimitive for EncodeMode {
172 #[allow(trivial_numeric_casts)]
173 #[inline]
174 fn from_i64(n: i64) -> Option<Self> {
175 match n {
176 n if n == EncodeMode::Auto as i64 => Some(EncodeMode::Auto),
177 n if n == EncodeMode::OutdatedRle as i64 => Some(EncodeMode::OutdatedRle),
178 n if n == EncodeMode::OutdatedSnapshot as i64 => Some(EncodeMode::OutdatedSnapshot),
179 n if n == EncodeMode::FastSnapshot as i64 => Some(EncodeMode::FastSnapshot),
180 n if n == EncodeMode::FastUpdates as i64 => Some(EncodeMode::FastUpdates),
181 _ => None,
182 }
183 }
184 #[inline]
185 fn from_u64(n: u64) -> Option<Self> {
186 Self::from_i64(n as i64)
187 }
188}
189
190impl num_traits::ToPrimitive for EncodeMode {
191 #[inline]
192 #[allow(trivial_numeric_casts)]
193 fn to_i64(&self) -> Option<i64> {
194 Some(match *self {
195 EncodeMode::Auto => EncodeMode::Auto as i64,
196 EncodeMode::OutdatedRle => EncodeMode::OutdatedRle as i64,
197 EncodeMode::OutdatedSnapshot => EncodeMode::OutdatedSnapshot as i64,
198 EncodeMode::FastSnapshot => EncodeMode::FastSnapshot as i64,
199 EncodeMode::FastUpdates => EncodeMode::FastUpdates as i64,
200 })
201 }
202 #[inline]
203 fn to_u64(&self) -> Option<u64> {
204 self.to_i64().map(|x| x as u64)
205 }
206}
207
208impl EncodeMode {
209 pub fn to_bytes(self) -> [u8; 2] {
210 let value = self.to_u16().unwrap();
211 value.to_be_bytes()
212 }
213
214 pub fn is_snapshot(self) -> bool {
215 matches!(
216 self,
217 EncodeMode::OutdatedSnapshot | EncodeMode::FastSnapshot
218 )
219 }
220}
221
222impl TryFrom<[u8; 2]> for EncodeMode {
223 type Error = LoroError;
224
225 fn try_from(value: [u8; 2]) -> Result<Self, Self::Error> {
226 let value = u16::from_be_bytes(value);
227 Self::from_u16(value).ok_or(LoroError::IncompatibleFutureEncodingError(value as usize))
228 }
229}
230
231#[derive(Debug, Clone, PartialEq, Eq, Default)]
232pub struct ImportStatus {
233 pub success: VersionRange,
234 pub pending: Option<VersionRange>,
235}
236
237pub(crate) fn decode_oplog(
238 oplog: &mut OpLog,
239 parsed: ParsedHeaderAndBody,
240 values: ImportedValues,
241) -> Result<ImportStatus, LoroError> {
242 let changes = decode_oplog_changes(oplog, parsed, values)?;
243 // Outdated decoders do not go through `import_changes_and_apply`. Compare
244 // here so a restored outdated import still honors the caller's mode.
245 let changes = oplog.check_and_trim_known_part_of_changes(changes, values)?;
246 let result = apply_decoded_changes_to_oplog(oplog, changes)?;
247 if result.has_deps_before_shallow_root {
248 return Err(LoroError::ImportUpdatesThatDependsOnOutdatedVersion);
249 }
250
251 Ok(result.status)
252}
253
254pub(crate) fn decode_oplog_changes(
255 oplog: &mut OpLog,
256 parsed: ParsedHeaderAndBody,
257 values: ImportedValues,
258) -> Result<Vec<Change>, LoroError> {
259 let ParsedHeaderAndBody { mode, body, .. } = parsed;
260 match mode {
261 EncodeMode::OutdatedRle | EncodeMode::OutdatedSnapshot => {
262 Err(LoroError::ImportUnsupportedEncodingMode)
263 }
264 EncodeMode::FastSnapshot => fast_snapshot::decode_oplog(oplog, body, values),
265 EncodeMode::FastUpdates => fast_snapshot::decode_updates(oplog, body.to_vec().into()),
266 EncodeMode::Auto => unreachable!(),
267 }
268}
269
270pub(crate) struct ApplyDecodedChangesResult {
271 pub status: ImportStatus,
272 pub has_deps_before_shallow_root: bool,
273}
274
275pub(crate) fn apply_decoded_changes_to_oplog(
276 oplog: &mut OpLog,
277 changes: Vec<Change>,
278) -> LoroResult<ApplyDecodedChangesResult> {
279 let ImportChangesResult {
280 mut imported,
281 latest_ids,
282 pending_changes,
283 changes_that_have_deps_before_shallow_root,
284 } = import_changes_to_oplog(changes, oplog)?;
285
286 // TODO: PERF: should we use hashmap to filter latest_ids with the same peer first?
287 oplog.try_apply_pending(latest_ids, Some(&mut imported));
288 // Applying previously parked pending ops can unlock deps of `pending_changes`.
289 // Those are applied here (and counted in `imported`); only still-blocked ones
290 // remain in the returned pending range.
291 let pending =
292 oplog.import_unknown_lamport_pending_changes(pending_changes, Some(&mut imported));
293 Ok(ApplyDecodedChangesResult {
294 status: ImportStatus {
295 success: imported,
296 pending: (!pending.is_empty()).then_some(pending),
297 },
298 has_deps_before_shallow_root: !changes_that_have_deps_before_shallow_root.is_empty(),
299 })
300}
301
302pub(crate) struct ParsedHeaderAndBody<'a> {
303 pub checksum: [u8; 16],
304 pub checksum_body: &'a [u8],
305 pub mode: EncodeMode,
306 pub body: &'a [u8],
307}
308
309const XXH_SEED: u32 = u32::from_le_bytes(*b"LORO");
310impl ParsedHeaderAndBody<'_> {
311 /// Return if the checksum is correct.
312 fn check_checksum(&self) -> LoroResult<()> {
313 match self.mode {
314 EncodeMode::OutdatedRle | EncodeMode::OutdatedSnapshot => {
315 if md5::compute(self.checksum_body).0 != self.checksum {
316 return Err(LoroError::DecodeChecksumMismatchError);
317 }
318 }
319 EncodeMode::FastSnapshot | EncodeMode::FastUpdates => {
320 let mut expected_bytes = [0; 4];
321 expected_bytes.copy_from_slice(&self.checksum[12..16]);
322 let expected = u32::from_le_bytes(expected_bytes);
323 if xxhash_rust::xxh32::xxh32(self.checksum_body, XXH_SEED) != expected {
324 return Err(LoroError::DecodeChecksumMismatchError);
325 }
326 }
327 EncodeMode::Auto => {
328 return Err(LoroError::DecodeError(
329 "Invalid import mode `Auto` in encoded blob"
330 .to_string()
331 .into_boxed_str(),
332 ));
333 }
334 }
335
336 Ok(())
337 }
338}
339
340const MIN_HEADER_SIZE: usize = 22;
341pub(crate) fn parse_header_and_body(
342 bytes: &[u8],
343 check_checksum: bool,
344) -> Result<ParsedHeaderAndBody<'_>, LoroError> {
345 let reader = &bytes;
346 if bytes.len() < MIN_HEADER_SIZE {
347 return Err(LoroError::DecodeError("Invalid import data".into()));
348 }
349
350 let (magic_bytes, reader) = reader.split_at(4);
351 if magic_bytes != MAGIC_BYTES {
352 return Err(LoroError::DecodeError("Invalid magic bytes".into()));
353 }
354
355 let (checksum, reader) = reader.split_at(16);
356 let checksum_body = reader;
357 let (mode_bytes, reader) = reader.split_at(2);
358 let mode: EncodeMode = [mode_bytes[0], mode_bytes[1]].try_into()?;
359 if mode == EncodeMode::Auto {
360 return Err(LoroError::DecodeError(
361 "Invalid import mode `Auto` in encoded blob"
362 .to_string()
363 .into_boxed_str(),
364 ));
365 }
366 let mut checksum_arr = [0; 16];
367 checksum_arr.copy_from_slice(checksum);
368
369 let ans = ParsedHeaderAndBody {
370 mode,
371 checksum_body,
372 checksum: checksum_arr,
373 body: reader,
374 };
375
376 if check_checksum {
377 ans.check_checksum()?;
378 }
379 Ok(ans)
380}
381
382pub(crate) fn export_fast_snapshot(doc: &LoroDoc) -> Result<Vec<u8>, LoroEncodeError> {
383 let snapshot = fast_snapshot::encode_snapshot_inner(doc)?;
384 let expected_len = snapshot
385 .encoded_len()
386 .and_then(|len| MIN_HEADER_SIZE.checked_add(len))
387 .ok_or_else(|| LoroEncodeError::internal("snapshot length overflow"))?;
388 let encoded = encode_with_capacity(EncodeMode::FastSnapshot, expected_len, &mut |ans| {
389 fast_snapshot::_encode_snapshot(&snapshot, ans);
390 Ok(())
391 })?;
392 debug_assert_eq!(encoded.len(), expected_len);
393 Ok(encoded)
394}
395
396pub(crate) fn export_snapshot_at(
397 doc: &LoroDoc,
398 frontiers: &Frontiers,
399) -> Result<Vec<u8>, LoroEncodeError> {
400 check_target_version_reachable(doc, frontiers)?;
401 encode_with(EncodeMode::FastSnapshot, &mut |ans| {
402 shallow_snapshot::encode_snapshot_at(doc, frontiers, ans)
403 })
404}
405
406pub(crate) fn export_fast_updates(doc: &LoroDoc, vv: &VersionVector) -> Vec<u8> {
407 encode_with(EncodeMode::FastUpdates, &mut |ans| {
408 fast_snapshot::encode_updates(doc, vv, ans);
409 Ok(())
410 })
411 .unwrap()
412}
413
414pub(crate) fn export_pending_updates(oplog: &OpLog) -> Result<Option<Vec<u8>>, LoroEncodeError> {
415 let changes = oplog.pending_changes.export_changes(oplog.vv())?;
416 if changes.is_empty() {
417 return Ok(None);
418 }
419
420 encode_with(EncodeMode::FastUpdates, &mut |ans| {
421 // A singleton block needs neither continuous history nor a DAG-resolved
422 // Lamport. Never insert these incomplete changes into a ChangeStore.
423 for change in &changes {
424 let bytes =
425 crate::oplog::encode_change_block(std::slice::from_ref(change), &oplog.arena);
426 leb128::write::unsigned(ans, bytes.len() as u64).unwrap();
427 ans.extend_from_slice(&bytes);
428 }
429 Ok(())
430 })
431 .map(Some)
432}
433
434pub(crate) fn export_fast_updates_in_range(oplog: &OpLog, spans: &[IdSpan]) -> Vec<u8> {
435 encode_with(EncodeMode::FastUpdates, &mut |ans| {
436 fast_snapshot::encode_updates_in_range(oplog, spans, ans);
437 Ok(())
438 })
439 .unwrap()
440}
441
442pub(crate) fn export_shallow_snapshot(
443 doc: &LoroDoc,
444 f: &Frontiers,
445) -> Result<Vec<u8>, LoroEncodeError> {
446 check_target_version_reachable(doc, f)?;
447 encode_with(EncodeMode::FastSnapshot, &mut |ans| {
448 shallow_snapshot::export_shallow_snapshot(doc, f, ans)?;
449 Ok(())
450 })
451}
452
453fn check_target_version_reachable(doc: &LoroDoc, f: &Frontiers) -> Result<(), LoroEncodeError> {
454 let oplog = doc.oplog.lock();
455 if !oplog.dag.can_export_shallow_snapshot_on(f) {
456 return Err(LoroEncodeError::FrontiersNotFound(format!("{f:?}")));
457 }
458
459 Ok(())
460}
461
462pub(crate) fn export_state_only_snapshot(
463 doc: &LoroDoc,
464 f: &Frontiers,
465) -> Result<Vec<u8>, LoroEncodeError> {
466 check_target_version_reachable(doc, f)?;
467 encode_with(EncodeMode::FastSnapshot, &mut |ans| {
468 shallow_snapshot::export_state_only_snapshot(doc, f, ans)?;
469 Ok(())
470 })
471}
472
473pub(crate) fn encode_with(
474 mode: EncodeMode,
475 f: &mut dyn FnMut(&mut Vec<u8>) -> Result<(), LoroEncodeError>,
476) -> Result<Vec<u8>, LoroEncodeError> {
477 encode_with_capacity(mode, MIN_HEADER_SIZE, f)
478}
479
480fn encode_with_capacity(
481 mode: EncodeMode,
482 capacity: usize,
483 f: &mut dyn FnMut(&mut Vec<u8>) -> Result<(), LoroEncodeError>,
484) -> Result<Vec<u8>, LoroEncodeError> {
485 // HEADER
486 let mut ans = Vec::with_capacity(capacity);
487 ans.extend(MAGIC_BYTES);
488 let checksum = [0; 16];
489 ans.extend(checksum);
490 ans.extend(mode.to_bytes());
491
492 // BODY
493 f(&mut ans)?;
494
495 // CHECKSUM in HEADER
496 let checksum_body = &ans[20..];
497 let checksum = xxhash_rust::xxh32::xxh32(checksum_body, XXH_SEED);
498 ans[16..20].copy_from_slice(&checksum.to_le_bytes());
499 Ok(ans)
500}
501
502pub(crate) fn decode_snapshot(
503 doc: &LoroDoc,
504 mode: EncodeMode,
505 body: &[u8],
506 origin: InternalString,
507) -> Result<ImportStatus, LoroError> {
508 match mode {
509 EncodeMode::OutdatedSnapshot => {
510 return Err(LoroError::ImportUnsupportedEncodingMode);
511 }
512 EncodeMode::FastSnapshot => {
513 fast_snapshot::decode_snapshot(doc, body.to_vec().into(), origin)?
514 }
515 _ => {
516 return Err(LoroError::DecodeError(
517 format!("Invalid snapshot encoding mode: {mode:?}").into_boxed_str(),
518 ));
519 }
520 };
521 Ok(ImportStatus {
522 success: VersionRange::from_vv(&doc.oplog_vv()),
523 pending: None,
524 })
525}
526
527#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
528pub enum EncodedBlobMode {
529 Snapshot,
530 OutdatedSnapshot,
531 ShallowSnapshot,
532 OutdatedRle,
533 Updates,
534}
535
536impl std::fmt::Display for EncodedBlobMode {
537 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
538 f.write_str(match self {
539 EncodedBlobMode::OutdatedRle => "outdated-update",
540 EncodedBlobMode::OutdatedSnapshot => "outdated-snapshot",
541 EncodedBlobMode::Snapshot => "snapshot",
542 EncodedBlobMode::ShallowSnapshot => "shallow-snapshot",
543 EncodedBlobMode::Updates => "update",
544 })
545 }
546}
547
548impl EncodedBlobMode {
549 pub fn is_snapshot(&self) -> bool {
550 matches!(
551 self,
552 EncodedBlobMode::Snapshot
553 | EncodedBlobMode::ShallowSnapshot
554 | EncodedBlobMode::OutdatedSnapshot
555 )
556 }
557}
558
559#[derive(Debug, Clone)]
560pub struct ImportBlobMetadata {
561 /// The partial start version vector.
562 ///
563 /// Import blob includes all the ops from `partial_start_vv` to `partial_end_vv`.
564 /// However, it does not constitute a complete version vector, as it only contains counters
565 /// from peers included within the import blob.
566 pub partial_start_vv: VersionVector,
567 /// The partial end version vector.
568 ///
569 /// Import blob includes all the ops from `partial_start_vv` to `partial_end_vv`.
570 /// However, it does not constitute a complete version vector, as it only contains counters
571 /// from peers included within the import blob.
572 pub partial_end_vv: VersionVector,
573 pub start_timestamp: i64,
574 pub start_frontiers: Frontiers,
575 pub end_timestamp: i64,
576 pub change_num: u32,
577 pub mode: EncodedBlobMode,
578}
579
580impl LoroDoc {
581 /// Decodes the metadata for an imported blob from the provided bytes.
582 pub fn decode_import_blob_meta(
583 blob: &[u8],
584 check_checksum: bool,
585 ) -> LoroResult<ImportBlobMetadata> {
586 let parsed = parse_header_and_body(blob, check_checksum)?;
587 match parsed.mode {
588 EncodeMode::Auto => unreachable!(),
589 EncodeMode::OutdatedRle | EncodeMode::OutdatedSnapshot => {
590 Err(LoroError::ImportUnsupportedEncodingMode)
591 }
592 EncodeMode::FastSnapshot => fast_snapshot::decode_snapshot_blob_meta(parsed),
593 EncodeMode::FastUpdates => fast_snapshot::decode_updates_blob_meta(parsed),
594 }
595 }
596}
597
598#[cfg(test)]
599mod test {
600 use super::*;
601 use loro_common::{loro_value, ContainerID, ContainerType, LoroValue, ID};
602
603 #[test]
604 fn fast_snapshot_envelope_has_exact_length_and_valid_checksum() {
605 let doc = LoroDoc::new_auto_commit();
606 doc.get_map("root").insert("key", "value").unwrap();
607 let encoded = doc.export(ExportMode::Snapshot).unwrap();
608 assert_eq!(&encoded[..4], &MAGIC_BYTES);
609 assert_eq!(&encoded[20..22], &EncodeMode::FastSnapshot.to_bytes());
610 let parsed = parse_header_and_body(&encoded, true).unwrap();
611 assert_eq!(parsed.mode, EncodeMode::FastSnapshot);
612 assert_eq!(encoded.len(), MIN_HEADER_SIZE + parsed.body.len());
613
614 let mut corrupted = encoded;
615 *corrupted.last_mut().unwrap() ^= 1;
616 assert!(matches!(
617 parse_header_and_body(&corrupted, true),
618 Err(LoroError::DecodeChecksumMismatchError)
619 ));
620 }
621
622 #[test]
623 fn test_value_encode_size() {
624 fn assert_size(value: LoroValue, max_size: usize) {
625 let size = postcard::to_allocvec(&value).unwrap().len();
626 assert!(
627 size <= max_size,
628 "value: {:?}, size: {}, max_size: {}",
629 value,
630 size,
631 max_size
632 );
633 }
634
635 assert_size(LoroValue::Null, 1);
636 assert_size(LoroValue::I64(1), 2);
637 assert_size(LoroValue::Double(1.), 9);
638 assert_size(LoroValue::Bool(true), 2);
639 assert_size(LoroValue::String("123".to_string().into()), 5);
640 assert_size(LoroValue::Binary(vec![1, 2, 3].into()), 5);
641 assert_size(
642 loro_value!({
643 "a": 1,
644 "b": 2,
645 }),
646 10,
647 );
648 assert_size(loro_value!([1, 2, 3]), 8);
649 assert_size(
650 LoroValue::Container(ContainerID::new_normal(ID::new(1, 1), ContainerType::Map)),
651 5,
652 );
653 assert_size(
654 LoroValue::Container(ContainerID::new_root("a", ContainerType::Map)),
655 5,
656 );
657 }
658}