-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathloro.pyi
2247 lines (1815 loc) · 63.8 KB
/
loro.pyi
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import typing
LoroValue = typing.Union[
None,
bool,
float,
int,
bytes,
str,
typing.List["LoroValue"],
typing.Dict[str, "LoroValue"],
ContainerID,
]
Container = typing.Union[
LoroList, LoroMap, LoroMovableList, LoroText, LoroTree, LoroCounter, LoroUnknown
]
ContainerId = typing.Union[str, ContainerID]
class AbsolutePosition:
pos: int
side: Side
class Awareness:
all_states: dict[int, PeerInfo]
peer: int
def __new__(cls, peer: int, timeout: int): ...
def encode(self, peers: typing.Sequence[int]) -> bytes: ...
def encode_all(self) -> bytes: ...
def apply(self, encoded_peers_info: bytes) -> AwarenessPeerUpdate: ...
@property
def local_state(self) -> typing.Optional[LoroValue]: ...
@local_state.setter
def local_state(self, value: LoroValue) -> None: ...
def remove_outdated(self) -> list[int]: ...
class AwarenessPeerUpdate:
updated: list[int]
added: list[int]
class ChangeMeta:
lamport: int
id: ID
timestamp: int
message: typing.Optional[str]
deps: Frontiers
len: int
class Configure: ...
class ContainerDiff:
r"""
A diff of a container.
"""
target: ContainerID
path: list[PathItem]
is_unknown: bool
diff: Diff
class CounterSpan:
r"""
This struct supports reverse repr: `from` can be less than `to`.
We need this because it'll make merging deletions easier.
But we should use it behavior conservatively.
If it is not necessary to be reverse, it should not.
"""
start: int
end: int
def __new__(cls, start: int, end: int): ...
class Cursor:
id: typing.Optional[ID]
side: Side
container: ContainerID
class DiffEvent:
triggered_by: EventTriggerKind
origin: str
current_target: typing.Optional[ContainerID]
events: list[ContainerDiff]
class Frontiers:
def __new__(
cls,
): ...
@classmethod
def from_id(cls, id: ID) -> Frontiers: ...
@classmethod
def from_ids(cls, ids: typing.Sequence[ID]) -> Frontiers: ...
def encode(self) -> bytes: ...
@classmethod
def decode(cls, bytes: bytes) -> Frontiers: ...
class ID:
peer: int
counter: int
def __new__(cls, peer: int, counter: int): ...
class IdSpan:
r"""
This struct supports reverse repr: [CounterSpan]'s from can be less than to. But we should use it conservatively.
We need this because it'll make merging deletions easier.
"""
peer: int
counter: CounterSpan
def __new__(cls, peer: int, counter: CounterSpan): ...
class ImportBlobMetadata:
partial_start_vv: VersionVector
partial_end_vv: VersionVector
start_timestamp: int
start_frontiers: Frontiers
end_timestamp: int
change_num: int
mode: EncodedBlobMode
class ImportStatus:
success: VersionRange
pending: typing.Optional[VersionRange]
class LoroCounter:
id: ContainerID
value: float
def __new__(
cls,
): ...
def increment(self, value: typing.Any) -> None:
r"""
Increment the counter by the given value.
"""
...
def decrement(self, value: typing.Any) -> None:
r"""
Decrement the counter by the given value.
"""
...
class LoroDoc:
config: Configure
is_detached_editing_enabled: bool
oplog_vv: VersionVector
state_vv: VersionVector
shallow_since_vv: VersionVector
shallow_since_frontiers: Frontiers
len_ops: int
len_changes: int
oplog_frontiers: Frontiers
state_frontiers: Frontiers
has_history_cache: bool
def __new__(
cls,
): ...
def fork(self) -> LoroDoc:
r"""
Duplicate the document with a different PeerID
The time complexity and space complexity of this operation are both O(n),
When called in detached mode, it will fork at the current state frontiers.
It will have the same effect as `fork_at(&self.state_frontiers())`.
"""
...
def fork_at(self, frontiers: Frontiers) -> LoroDoc:
r"""
Fork the document at the given frontiers.
The created doc will only contain the history before the specified frontiers.
"""
...
def get_change(self, id: ID) -> typing.Optional[ChangeMeta]:
r"""
Get `Change` at the given id.
`Change` is a grouped continuous operations that share the same id, timestamp, commit message.
- The id of the `Change` is the id of its first op.
- The second op's id is `{ peer: change.id.peer, counter: change.id.counter + 1 }`
The same applies on `Lamport`:
- The lamport of the `Change` is the lamport of its first op.
- The second op's lamport is `change.lamport + 1`
The length of the `Change` is how many operations it contains
"""
...
@classmethod
def decode_import_blob_meta(
cls, bytes: bytes, check_checksum: bool
) -> ImportBlobMetadata:
r"""
Decodes the metadata for an imported blob from the provided bytes.
"""
...
def set_record_timestamp(self, record: bool) -> None:
r"""
Set whether to record the timestamp of each change. Default is `false`.
If enabled, the Unix timestamp will be recorded for each change automatically.
You can set each timestamp manually when committing a change.
NOTE: Timestamps are forced to be in ascending order.
If you commit a new change with a timestamp that is less than the existing one,
the largest existing timestamp will be used instead.
"""
...
def set_detached_editing(self, enable: bool) -> None:
r"""
Enables editing in detached mode, which is disabled by default.
The doc enter detached mode after calling `detach` or checking out a non-latest version.
# Important Notes:
- This mode uses a different PeerID for each checkout.
- Ensure no concurrent operations share the same PeerID if set manually.
- Importing does not affect the document's state or version; changes are
recorded in the [OpLog] only. Call `checkout` to apply changes.
"""
...
def set_change_merge_interval(self, interval: int) -> None:
r"""
Set the interval of mergeable changes, in seconds.
If two continuous local changes are within the interval, they will be merged into one change.
The default value is 1000 seconds.
"""
...
def config_text_style(self, text_style: StyleConfigMap) -> None:
r"""
Set the rich text format configuration of the document.
You need to config it if you use rich text `mark` method.
Specifically, you need to config the `expand` property of each style.
Expand is used to specify the behavior of expanding when new text is inserted at the
beginning or end of the style.
"""
...
def attach(self) -> None:
r"""
Attach the document state to the latest known version.
> The document becomes detached during a `checkout` operation.
> Being `detached` implies that the `DocState` is not synchronized with the latest version of the `OpLog`.
> In a detached state, the document is not editable, and any `import` operations will be
> recorded in the `OpLog` without being applied to the `DocState`.
"""
...
def checkout(self, frontiers: Frontiers) -> None:
r"""
Checkout the `DocState` to a specific version.
The document becomes detached during a `checkout` operation.
Being `detached` implies that the `DocState` is not synchronized with the latest version of the `OpLog`.
In a detached state, the document is not editable, and any `import` operations will be
recorded in the `OpLog` without being applied to the `DocState`.
You should call `attach` to attach the `DocState` to the latest version of `OpLog`.
"""
...
def checkout_to_latest(self) -> None:
r"""
Checkout the `DocState` to the latest version.
> The document becomes detached during a `checkout` operation.
> Being `detached` implies that the `DocState` is not synchronized with the latest version of the `OpLog`.
> In a detached state, the document is not editable, and any `import` operations will be
> recorded in the `OpLog` without being applied to the `DocState`.
This has the same effect as `attach`.
"""
...
def cmp_with_frontiers(self, other: Frontiers) -> Ordering:
r"""
Compare the frontiers with the current OpLog's version.
If `other` contains any version that's not contained in the current OpLog, return [Ordering::Less].
"""
...
def cmp_frontiers(self, a: Frontiers, b: Frontiers) -> typing.Optional[Ordering]:
r"""
Compare two frontiers.
If the frontiers are not included in the document, return [`FrontiersNotIncluded`].
"""
...
def detach(self) -> None:
r"""
Force the document enter the detached mode.
In this mode, when you importing new updates, the [loro_internal::DocState] will not be changed.
Learn more at https://loro.dev/docs/advanced/doc_state_and_oplog#attacheddetached-status
"""
...
def import_batch(self, bytes: typing.Sequence[bytes]) -> ImportStatus: ...
def get_movable_list(self, obj: ContainerId) -> LoroMovableList:
r"""
Get a [LoroMovableList] by container id.
If the provided id is string, it will be converted into a root container id with the name of the string.
"""
...
def get_list(self, obj: ContainerId) -> LoroList:
r"""
Get a [LoroList] by container id.
If the provided id is string, it will be converted into a root container id with the name of the string.
"""
...
def get_map(self, obj: ContainerId) -> LoroMap:
r"""
Get a [LoroMap] by container id.
If the provided id is string, it will be converted into a root container id with the name of the string.
"""
...
def get_text(self, obj: ContainerId) -> LoroText:
r"""
Get a [LoroText] by container id.
If the provided id is string, it will be converted into a root container id with the name of the string.
"""
...
def get_tree(self, obj: ContainerId) -> LoroTree:
r"""
Get a [LoroTree] by container id.
If the provided id is string, it will be converted into a root container id with the name of the string.
"""
...
def get_counter(self, obj: typing.Any) -> LoroCounter:
r"""
Get a [LoroCounter] by container id.
If the provided id is string, it will be converted into a root container id with the name of the string.
"""
...
def commit(self) -> None:
r"""
Commit the cumulative auto commit transaction.
There is a transaction behind every operation.
The events will be emitted after a transaction is committed. A transaction is committed when:
- `doc.commit()` is called.
- `doc.export(mode)` is called.
- `doc.import(data)` is called.
- `doc.checkout(version)` is called.
"""
...
def commit_with(
self,
origin: typing.Optional[str] = ...,
timestamp: typing.Optional[int] = ...,
immediate_renew: typing.Optional[bool] = ...,
commit_msg: typing.Optional[str] = ...,
) -> None:
r"""
Commit the cumulative auto commit transaction with custom configure.
There is a transaction behind every operation.
It will automatically commit when users invoke export or import.
The event will be sent after a transaction is committed
"""
...
def set_next_commit_message(self, msg: str) -> None:
r"""
Set commit message for the current uncommitted changes
"""
...
def is_detached(self) -> bool:
r"""
Whether the document is in detached mode, where the [loro_internal::DocState] is not
synchronized with the latest version of the [loro_internal::OpLog].
"""
...
def import_(self, bytes: bytes) -> ImportStatus:
r"""
Import updates/snapshot exported by [`LoroDoc::export_snapshot`] or [`LoroDoc::export_from`].
"""
...
def import_with(self, bytes: bytes, origin: str) -> ImportStatus:
r"""
Import updates/snapshot exported by [`LoroDoc::export_snapshot`] or [`LoroDoc::export_from`].
It marks the import with a custom `origin` string. It can be used to track the import source
in the generated events.
"""
...
def import_json_updates(self, json: str) -> ImportStatus:
r"""
Import the json schema updates.
only supports backward compatibility but not forward compatibility.
"""
...
def export_json_updates(
self, start_vv: VersionVector, end_vv: VersionVector
) -> str:
r"""
Export the current state with json-string format of the document.
"""
...
def frontiers_to_vv(self, frontiers: Frontiers) -> typing.Optional[VersionVector]:
r"""
Convert `Frontiers` into `VersionVector`
"""
...
def vv_to_frontiers(self, vv: VersionVector) -> Frontiers:
r"""
Convert `VersionVector` into `Frontiers`
"""
...
def get_value(self) -> LoroValue:
r"""
Get the shallow value of the document.
"""
...
def get_deep_value(self) -> LoroValue:
r"""
Get the entire state of the current DocState
"""
...
def get_deep_value_with_id(self) -> LoroValue:
r"""
Get the entire state of the current DocState with container id
"""
...
@property
def peer_id(self) -> int: ...
@peer_id.setter
def peer_id(self, peer: int) -> None:
r"""
Change the PeerID
NOTE: You need to make sure there is no chance two peer have the same PeerID.
If it happens, the document will be corrupted.
"""
...
def subscribe(
self, container_id: ContainerID, callback: typing.Callable[[DiffEvent], None]
) -> Subscription:
r"""
Subscribe the events of a container.
The callback will be invoked after a transaction that change the container.
Returns a subscription that can be used to unsubscribe.
The events will be emitted after a transaction is committed. A transaction is committed when:
- `doc.commit()` is called.
- `doc.export(mode)` is called.
- `doc.import(data)` is called.
- `doc.checkout(version)` is called.
# Example
```
# use loro::LoroDoc;
# use std::sync::{atomic::AtomicBool, Arc};
# use loro::{event::DiffEvent, LoroResult, TextDelta};
#
let doc = LoroDoc::new();
let text = doc.get_text("text");
let ran = Arc::new(AtomicBool::new(false));
let ran2 = ran.clone();
let sub = doc.subscribe(
&text.id(),
Arc::new(move |event| {
assert!(event.triggered_by.is_local());
for event in event.events {
let delta = event.diff.as_text().unwrap();
let d = TextDelta::Insert {
insert: "123".into(),
attributes: Default::default(),
};
assert_eq!(delta, &vec![d]);
ran2.store(true, std::sync::atomic::Ordering::Relaxed);
}
}),
);
text.insert(0, "123").unwrap();
doc.commit();
assert!(ran.load(std::sync::atomic::Ordering::Relaxed));
// unsubscribe
sub.unsubscribe();
```
"""
...
def subscribe_root(
self, callback: typing.Callable[[DiffEvent], None]
) -> Subscription:
r"""
Subscribe all the events.
The callback will be invoked when any part of the [loro_internal::DocState] is changed.
Returns a subscription that can be used to unsubscribe.
The events will be emitted after a transaction is committed. A transaction is committed when:
- `doc.commit()` is called.
- `doc.export(mode)` is called.
- `doc.import(data)` is called.
- `doc.checkout(version)` is called.
"""
...
def subscribe_local_update(
self, callback: typing.Callable[[bytes], bool]
) -> Subscription:
r"""
Subscribe the local update of the document.
"""
...
def subscribe_peer_id_change(
self, callback: typing.Callable[[ID], bool]
) -> Subscription:
r"""
Subscribe the peer id change of the document.
"""
...
def get_by_path(
self, path: typing.Sequence[Index]
) -> typing.Optional[ValueOrContainer]:
r"""
Get the handler by the path.
"""
...
def get_by_str_path(self, path: str) -> typing.Optional[ValueOrContainer]:
r"""
Get the handler by the string path.
"""
...
def get_cursor_pos(self, cursor: Cursor) -> PosQueryResult:
r"""
Get the absolute position of the given cursor.
# Example
```
# use loro::{LoroDoc, ToJson};
let doc = LoroDoc::new();
let text = &doc.get_text("text");
text.insert(0, "01234").unwrap();
let pos = text.get_cursor(5, Default::default()).unwrap();
assert_eq!(doc.get_cursor_pos(&pos).unwrap().current.pos, 5);
text.insert(0, "01234").unwrap();
assert_eq!(doc.get_cursor_pos(&pos).unwrap().current.pos, 10);
text.delete(0, 10).unwrap();
assert_eq!(doc.get_cursor_pos(&pos).unwrap().current.pos, 0);
text.insert(0, "01234").unwrap();
assert_eq!(doc.get_cursor_pos(&pos).unwrap().current.pos, 5);
```
"""
...
def free_history_cache(self) -> None:
r"""
Free the history cache that is used for making checkout faster.
If you use checkout that switching to an old/concurrent version, the history cache will be built.
You can free it by calling this method.
"""
...
def free_diff_calculator(self) -> None:
r"""
Free the cached diff calculator that is used for checkout.
"""
...
def compact_change_store(self) -> None:
r"""
Encoded all ops and history cache to bytes and store them in the kv store.
This will free up the memory that used by parsed ops
"""
...
def export(self, mode: ExportMode) -> bytes:
r"""
Export the document in the given mode.
"""
...
def get_path_to_container(
self, id: ContainerID
) -> typing.Optional[list[tuple[ContainerID, Index]]]:
r"""
Get the path from the root to the container
"""
...
def jsonpath(self, path: str) -> list[ValueOrContainer]:
r"""
Evaluate a JSONPath expression on the document and return matching values or handlers.
This method allows querying the document structure using JSONPath syntax.
It returns a vector of `ValueOrHandler` which can represent either primitive values
or container handlers, depending on what the JSONPath expression matches.
# Arguments
* `path` - A string slice containing the JSONPath expression to evaluate.
# Returns
A `Result` containing either:
- `Ok(Vec<ValueOrHandler>)`: A vector of matching values or handlers.
- `Err(String)`: An error message if the JSONPath expression is invalid or evaluation fails.
# Example
```
# use loro::{LoroDoc, ToJson};
let doc = LoroDoc::new();
let map = doc.get_map("users");
map.insert("alice", 30).unwrap();
map.insert("bob", 25).unwrap();
let result = doc.jsonpath("$.users.alice").unwrap();
assert_eq!(result.len(), 1);
assert_eq!(result[0].as_value().unwrap().to_json_value(), serde_json::json!(30));
```
"""
...
def get_pending_txn_len(self) -> int:
r"""
Get the number of operations in the pending transaction.
The pending transaction is the one that is not committed yet. It will be committed
after calling `doc.commit()`, `doc.export(mode)` or `doc.checkout(version)`.
"""
...
def travel_change_ancestors(
self, ids: typing.Sequence[ID], cb: typing.Callable[[ChangeMeta], bool]
) -> None:
r"""
Traverses the ancestors of the Change containing the given ID, including itself.
This method visits all ancestors in causal order, from the latest to the oldest,
based on their Lamport timestamps.
# Arguments
* `ids` - The IDs of the Change to start the traversal from.
* `cb` - A callback function that is called for each ancestor. It can return `True` to stop the traversal.
"""
...
def is_shallow(self) -> bool:
r"""
Check if the doc contains the full history.
"""
...
def get_changed_containers_in(self, id: ID, len: int) -> set[ContainerID]:
r"""
Gets container IDs modified in the given ID range.
**NOTE:** This method will implicitly commit.
This method can be used in conjunction with `doc.travel_change_ancestors()` to traverse
the history and identify all changes that affected specific containers.
# Arguments
* `id` - The starting ID of the change range
* `len` - The length of the change range to check
"""
...
def revert_to(self, version: Frontiers) -> None:
r"""
Revert the current document state back to the target version
This will generate a series of local operations that can revert the
current doc to the target version. It will calculate the diff between the current
state and the target state, and apply the diff to the current state.
"""
...
def apply_diff(self, diff: DiffBatch) -> None:
r"""
Apply a diff to the current document state.
This will apply the diff to the current state.
"""
...
def diff(self, a: Frontiers, b: Frontiers) -> DiffBatch:
r"""
Calculate the diff between two versions
"""
...
class LoroList:
is_attached: bool
id: ContainerID
def __new__(
cls,
): ...
def insert(self, pos: int, v: LoroValue) -> None:
r"""
Insert a value at the given position.
"""
...
def delete(self, pos: int, len: int) -> None:
r"""
Delete values at the given position.
"""
...
def get(self, index: int) -> typing.Optional[ValueOrContainer]:
r"""
Get the value at the given position.
"""
...
def get_deep_value(self) -> LoroValue:
r"""
Get the deep value of the container.
"""
...
def get_value(self) -> LoroValue:
r"""
Get the shallow value of the container.
This does not convert the state of sub-containers; instead, it represents them as [LoroValue::Container].
"""
...
def pop(self) -> typing.Optional[LoroValue]:
r"""
Pop the last element of the list.
"""
...
def push(self, v: LoroValue) -> None:
r"""
Push a value to the list.
"""
...
def push_container(self, child: Container) -> Container:
r"""
Push a container to the list.
"""
...
def for_each(self, f: typing.Callable[[ValueOrContainer], None]) -> None:
r"""
Iterate over the elements of the list.
"""
...
def __len__(self) -> int:
r"""
Get the length of the list.
"""
...
def is_empty(self) -> bool:
r"""
Whether the list is empty.
"""
...
def insert_container(self, pos: int, child: Container) -> Container:
r"""
Insert a container with the given type at the given index.
# Example
```
# use loro::{LoroDoc, ContainerType, LoroText, ToJson};
# use serde_json::json;
let doc = LoroDoc::new();
let list = doc.get_list("m");
let text = list.insert_container(0, LoroText::new()).unwrap();
text.insert(0, "12");
text.insert(0, "0");
assert_eq!(doc.get_deep_value().to_json_value(), json!({"m": ["012"]}));
```
"""
...
def get_cursor(self, pos: int, side: Side) -> typing.Optional[Cursor]:
r"""
Get the cursor at the given position.
Using "index" to denote cursor positions can be unstable, as positions may
shift with document edits. To reliably represent a position or range within
a document, it is more effective to leverage the unique ID of each item/character
in a List CRDT or Text CRDT.
Loro optimizes State metadata by not storing the IDs of deleted elements. This
approach complicates tracking cursors since they rely on these IDs. The solution
recalculates position by replaying relevant history to update stable positions
accurately. To minimize the performance impact of history replay, the system
updates cursor info to reference only the IDs of currently present elements,
thereby reducing the need for replay.
# Example
```
use loro::LoroDoc;
use loro_internal::cursor::Side;
let doc = LoroDoc::new();
let list = doc.get_list("list");
list.insert(0, 0).unwrap();
let cursor = list.get_cursor(0, Side::Middle).unwrap();
assert_eq!(doc.get_cursor_pos(&cursor).unwrap().current.pos, 0);
list.insert(0, 0).unwrap();
assert_eq!(doc.get_cursor_pos(&cursor).unwrap().current.pos, 1);
list.insert(0, 0).unwrap();
list.insert(0, 0).unwrap();
assert_eq!(doc.get_cursor_pos(&cursor).unwrap().current.pos, 3);
list.insert(4, 0).unwrap();
assert_eq!(doc.get_cursor_pos(&cursor).unwrap().current.pos, 3);
```
"""
...
def to_vec(self) -> list[LoroValue]:
r"""
Converts the LoroList to a Vec of LoroValue.
This method unwraps the internal Arc and clones the data if necessary,
returning a Vec containing all the elements of the LoroList as LoroValue.
# Returns
A Vec<LoroValue> containing all elements of the LoroList.
# Example
```
use loro::{LoroDoc, LoroValue};
let doc = LoroDoc::new();
let list = doc.get_list("my_list");
list.insert(0, 1).unwrap();
list.insert(1, "hello").unwrap();
list.insert(2, true).unwrap();
let vec = list.to_vec();
```
"""
...
def clear(self) -> None:
r"""
Delete all elements in the list.
"""
...
def get_id_at(self, pos: int) -> typing.Optional[ID]:
r"""
Get the ID of the list item at the given position.
"""
...
def doc(self) -> typing.Optional[LoroDoc]:
r"""
Get the LoroDoc of the container.
"""
...
class LoroMap:
is_attached: bool
id: ContainerID
def __new__(
cls,
): ...
def delete(self, key: str) -> None:
r"""
Delete a key-value pair from the map.
"""
...
def insert(self, key: str, value: LoroValue) -> None:
r"""
Insert a key-value pair into the map.
"""
...
def __len__(self) -> int:
r"""
Get the length of the map.
"""
...
def is_empty(self) -> bool:
r"""
Whether the map is empty.
"""
...
def get(self, key: str) -> typing.Optional[ValueOrContainer]:
r"""
Get the value of the map with the given key.
"""
...
def insert_container(self, key: str, child: Container) -> Container:
r"""
Insert a container with the given type at the given key.
# Example
```
# use loro::{LoroDoc, LoroText, ContainerType, ToJson};
# use serde_json::json;
let doc = LoroDoc::new();
let map = doc.get_map("m");
let text = map.insert_container("t", LoroText::new()).unwrap();
text.insert(0, "12");
text.insert(0, "0");
assert_eq!(doc.get_deep_value().to_json_value(), json!({"m": {"t": "012"}}));
```
"""
...
def get_value(self) -> LoroValue:
r"""
Get the shallow value of the map.
It will not convert the state of sub-containers, but represent them as [LoroValue::Container].
"""
...
def get_deep_value(self) -> LoroValue:
r"""
Get the deep value of the map.
It will convert the state of sub-containers into a nested JSON value.
"""
...
def get_or_create_container(self, key: str, child: Container) -> Container:
r"""
Get or create a container with the given key.
"""
...