/
lib.rs
5017 lines (4517 loc) · 173 KB
/
lib.rs
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
use lib0::any::Any;
use lib0::error::Error;
use std::collections::HashMap;
use std::ffi::{c_char, c_void, CStr, CString};
use std::mem::{forget, ManuallyDrop, MaybeUninit};
use std::ops::Deref;
use std::ptr::{null, null_mut};
use std::sync::Arc;
use yrs::block::{ClientID, ItemContent, Prelim, Unused};
use yrs::types::array::ArrayEvent;
use yrs::types::array::ArrayIter as NativeArrayIter;
use yrs::types::map::MapEvent;
use yrs::types::map::MapIter as NativeMapIter;
use yrs::types::text::{Diff, TextEvent, YChange};
use yrs::types::xml::{Attributes as NativeAttributes, XmlNode};
use yrs::types::xml::{TreeWalker as NativeTreeWalker, XmlFragment};
use yrs::types::xml::{XmlEvent, XmlTextEvent};
use yrs::types::{
Attrs, BranchPtr, Change, Delta, EntryChange, Event, PathSegment, TypeRef, Value,
TYPE_REFS_ARRAY, TYPE_REFS_DOC, TYPE_REFS_MAP, TYPE_REFS_TEXT, TYPE_REFS_XML_ELEMENT,
TYPE_REFS_XML_FRAGMENT, TYPE_REFS_XML_TEXT,
};
use yrs::undo::EventKind;
use yrs::updates::decoder::{Decode, DecoderV1};
use yrs::updates::encoder::{Encode, Encoder, EncoderV1, EncoderV2};
use yrs::{
uuid_v4, Array, ArrayRef, Assoc, DeleteSet, GetString, Map, MapRef, Observable, OffsetKind,
Options, Origin, ReadTxn, Snapshot, StateVector, StickyIndex, Store, SubdocsEvent,
SubdocsEventIter, SubscriptionId, Text, TextRef, Transact, TransactionCleanupEvent,
UndoManager, Update, Xml, XmlElementPrelim, XmlElementRef, XmlFragmentRef, XmlTextPrelim,
XmlTextRef,
};
/// Flag used by `YInput` and `YOutput` to tag boolean values.
pub const Y_JSON_BOOL: i8 = -8;
/// Flag used by `YInput` and `YOutput` to tag floating point numbers.
pub const Y_JSON_NUM: i8 = -7;
/// Flag used by `YInput` and `YOutput` to tag 64-bit integer numbers.
pub const Y_JSON_INT: i8 = -6;
/// Flag used by `YInput` and `YOutput` to tag strings.
pub const Y_JSON_STR: i8 = -5;
/// Flag used by `YInput` and `YOutput` to tag binary content.
pub const Y_JSON_BUF: i8 = -4;
/// Flag used by `YInput` and `YOutput` to tag embedded JSON-like arrays of values,
/// which themselves are `YInput` and `YOutput` instances respectively.
pub const Y_JSON_ARR: i8 = -3;
/// Flag used by `YInput` and `YOutput` to tag embedded JSON-like maps of key-value pairs,
/// where keys are strings and v
pub const Y_JSON_MAP: i8 = -2;
/// Flag used by `YInput` and `YOutput` to tag JSON-like null values.
pub const Y_JSON_NULL: i8 = -1;
/// Flag used by `YInput` and `YOutput` to tag JSON-like undefined values.
pub const Y_JSON_UNDEF: i8 = 0;
/// Flag used by `YInput` and `YOutput` to tag content, which is an `YArray` shared type.
pub const Y_ARRAY: i8 = 1;
/// Flag used by `YInput` and `YOutput` to tag content, which is an `YMap` shared type.
pub const Y_MAP: i8 = 2;
/// Flag used by `YInput` and `YOutput` to tag content, which is an `YText` shared type.
pub const Y_TEXT: i8 = 3;
/// Flag used by `YInput` and `YOutput` to tag content, which is an `YXmlElement` shared type.
pub const Y_XML_ELEM: i8 = 4;
/// Flag used by `YInput` and `YOutput` to tag content, which is an `YXmlText` shared type.
pub const Y_XML_TEXT: i8 = 5;
/// Flag used by `YInput` and `YOutput` to tag content, which is an `YXmlFragment` shared type.
pub const Y_XML_FRAG: i8 = 6;
/// Flag used by `YInput` and `YOutput` to tag content, which is an `YDoc` shared type.
pub const Y_DOC: i8 = 7;
/// Flag used to mark a truthy boolean numbers.
pub const Y_TRUE: u8 = 1;
/// Flag used to mark a falsy boolean numbers.
pub const Y_FALSE: u8 = 0;
/// Flag used by `YOptions` to determine, that text operations offsets and length will be counted by
/// the byte number of UTF8-encoded string.
pub const Y_OFFSET_BYTES: u8 = 0;
/// Flag used by `YOptions` to determine, that text operations offsets and length will be counted by
/// UTF-16 chars of encoded string.
pub const Y_OFFSET_UTF16: u8 = 1;
/// Flag used by `YOptions` to determine, that text operations offsets and length will be counted by
/// by UTF-32 chars of encoded string.
pub const Y_OFFSET_UTF32: u8 = 2;
/* pub types below are used by cbindgen for c header generation */
/// A Yrs document type. Documents are most important units of collaborative resources management.
/// All shared collections live within a scope of their corresponding documents. All updates are
/// generated on per document basis (rather than individual shared type). All operations on shared
/// collections happen via `YTransaction`, which lifetime is also bound to a document.
///
/// Document manages so called root types, which are top-level shared types definitions (as opposed
/// to recursively nested types).
pub type Doc = yrs::Doc;
/// A common shared data type. All Yrs instances can be refered to using this data type (use
/// `ytype_kind` function if a specific type needs to be determined). Branch pointers are passed
/// over type-specific functions like `ytext_insert`, `yarray_insert` or `ymap_insert` to perform
/// a specific shared type operations.
///
/// Using write methods of different shared types (eg. `ytext_insert` and `yarray_insert`) over
/// the same branch may result in undefined behavior.
pub type Branch = yrs::types::Branch;
/// Iterator structure used by shared array data type.
#[repr(transparent)]
pub struct ArrayIter(NativeArrayIter<&'static Transaction, Transaction>);
/// Iterator structure used by shared map data type. Map iterators are unordered - there's no
/// specific order in which map entries will be returned during consecutive iterator calls.
#[repr(transparent)]
pub struct MapIter(NativeMapIter<'static, &'static Transaction, Transaction>);
/// Iterator structure used by XML nodes (elements and text) to iterate over node's attributes.
/// Attribute iterators are unordered - there's no specific order in which map entries will be
/// returned during consecutive iterator calls.
#[repr(transparent)]
pub struct Attributes(NativeAttributes<'static, &'static Transaction, Transaction>);
/// Iterator used to traverse over the complex nested tree structure of a XML node. XML node
/// iterator walks only over `YXmlElement` and `YXmlText` nodes. It does so in ordered manner (using
/// the order in which children are ordered within their parent nodes) and using **depth-first**
/// traverse.
#[repr(transparent)]
pub struct TreeWalker(NativeTreeWalker<'static, &'static Transaction, Transaction>);
/// Transaction is one of the core types in Yrs. All operations that need to touch or
/// modify a document's contents (a.k.a. block store), need to be executed in scope of a
/// transaction.
#[repr(transparent)]
pub struct Transaction(TransactionInner);
enum TransactionInner {
ReadOnly(yrs::Transaction<'static>),
ReadWrite(yrs::TransactionMut<'static>),
}
impl Transaction {
fn read_only(txn: yrs::Transaction) -> Self {
Transaction(TransactionInner::ReadOnly(unsafe {
std::mem::transmute(txn)
}))
}
fn read_write(txn: yrs::TransactionMut) -> Self {
Transaction(TransactionInner::ReadWrite(unsafe {
std::mem::transmute(txn)
}))
}
fn is_writeable(&self) -> bool {
match &self.0 {
TransactionInner::ReadOnly(_) => false,
TransactionInner::ReadWrite(_) => true,
}
}
fn as_mut(&mut self) -> Option<&mut yrs::TransactionMut<'static>> {
match &mut self.0 {
TransactionInner::ReadOnly(_) => None,
TransactionInner::ReadWrite(txn) => Some(txn),
}
}
}
impl ReadTxn for Transaction {
fn store(&self) -> &Store {
match &self.0 {
TransactionInner::ReadOnly(txn) => txn.store(),
TransactionInner::ReadWrite(txn) => txn.store(),
}
}
}
/// A structure representing single key-value entry of a map output (used by either
/// embedded JSON-like maps or YMaps).
#[repr(C)]
pub struct YMapEntry {
/// Null-terminated string representing an entry's key component. Encoded as UTF-8.
pub key: *const c_char,
/// A `YOutput` value representing containing variadic content that can be stored withing map's
/// entry.
pub value: YOutput,
}
impl YMapEntry {
fn new(key: &str, value: Value) -> Self {
let value = YOutput::from(value);
YMapEntry {
key: CString::new(key).unwrap().into_raw(),
value,
}
}
}
impl Drop for YMapEntry {
fn drop(&mut self) {
unsafe {
drop(CString::from_raw(self.key as *mut c_char));
//self.value.drop();
}
}
}
/// A structure representing single attribute of an either `YXmlElement` or `YXmlText` instance.
/// It consists of attribute name and string, both of which are null-terminated UTF-8 strings.
#[repr(C)]
pub struct YXmlAttr {
pub name: *const c_char,
pub value: *const c_char,
}
impl Drop for YXmlAttr {
fn drop(&mut self) {
unsafe {
drop(CString::from_raw(self.name as *mut _));
drop(CString::from_raw(self.value as *mut _));
}
}
}
/// Configuration object used by `YDoc`.
#[repr(C)]
pub struct YOptions {
/// Globally unique 53-bit integer assigned to corresponding document replica as its identifier.
///
/// If two clients share the same `id` and will perform any updates, it will result in
/// unrecoverable document state corruption. The same thing may happen if the client restored
/// document state from snapshot, that didn't contain all of that clients updates that were sent
/// to other peers.
pub id: u64,
/// A NULL-able globally unique Uuid v4 compatible null-terminated string identifier
/// of this document. If passed as NULL, a random Uuid will be generated instead.
pub guid: *const c_char,
/// A NULL-able, UTF-8 encoded, null-terminated string of a collection that this document
/// belongs to. It's used only by providers.
pub collection_id: *const c_char,
/// Encoding used by text editing operations on this document. It's used to compute
/// `YText`/`YXmlText` insertion offsets and text lengths. Either:
///
/// - `Y_ENCODING_BYTES`
/// - `Y_ENCODING_UTF16`
/// - `Y_ENCODING_UTF32`
pub encoding: u8,
/// Boolean flag used to determine if deleted blocks should be garbage collected or not
/// during the transaction commits. Setting this value to 0 means GC will be performed.
pub skip_gc: u8,
/// Boolean flag used to determine if subdocument should be loaded automatically.
/// If this is a subdocument, remote peers will load the document as well automatically.
pub auto_load: u8,
/// Boolean flag used to determine whether the document should be synced by the provider now.
pub should_load: u8,
}
impl Into<Options> for YOptions {
fn into(self) -> Options {
let encoding = match self.encoding {
Y_OFFSET_BYTES => OffsetKind::Bytes,
Y_OFFSET_UTF16 => OffsetKind::Utf16,
Y_OFFSET_UTF32 => OffsetKind::Utf32,
_ => panic!("Unrecognized YOptions.encoding type"),
};
let guid = if self.guid.is_null() {
uuid_v4(&mut rand::thread_rng())
} else {
let c_str = unsafe { CStr::from_ptr(self.guid) };
let str = c_str.to_str().unwrap();
str.into()
};
let collection_id = if self.collection_id.is_null() {
None
} else {
let c_str = unsafe { CStr::from_ptr(self.collection_id) };
let str = c_str.to_str().unwrap().to_string();
Some(str)
};
Options {
client_id: self.id as ClientID,
guid,
collection_id,
skip_gc: if self.skip_gc == 0 { false } else { true },
auto_load: if self.auto_load == 0 { false } else { true },
should_load: if self.should_load == 0 { false } else { true },
offset_kind: encoding,
}
}
}
impl From<Options> for YOptions {
fn from(o: Options) -> Self {
YOptions {
id: o.client_id,
guid: CString::new(o.guid.as_ref()).unwrap().into_raw(),
collection_id: if let Some(collection_id) = o.collection_id {
CString::new(collection_id).unwrap().into_raw()
} else {
null_mut()
},
encoding: match o.offset_kind {
OffsetKind::Bytes => Y_OFFSET_BYTES,
OffsetKind::Utf16 => Y_OFFSET_UTF16,
OffsetKind::Utf32 => Y_OFFSET_UTF32,
},
skip_gc: if o.skip_gc { 1 } else { 0 },
auto_load: if o.auto_load { 1 } else { 0 },
should_load: if o.should_load { 1 } else { 0 },
}
}
}
/// Returns default ceonfiguration for `YOptions`.
#[no_mangle]
pub unsafe extern "C" fn yoptions() -> YOptions {
Options::default().into()
}
/// Releases all memory-allocated resources bound to given document.
#[no_mangle]
pub unsafe extern "C" fn ydoc_destroy(value: *mut Doc) {
if !value.is_null() {
drop(Box::from_raw(value));
}
}
/// Frees all memory-allocated resources bound to a given [YMapEntry].
#[no_mangle]
pub unsafe extern "C" fn ymap_entry_destroy(value: *mut YMapEntry) {
if !value.is_null() {
drop(Box::from_raw(value));
}
}
/// Frees all memory-allocated resources bound to a given [YXmlAttr].
#[no_mangle]
pub unsafe extern "C" fn yxmlattr_destroy(attr: *mut YXmlAttr) {
if !attr.is_null() {
drop(Box::from_raw(attr));
}
}
/// Frees all memory-allocated resources bound to a given UTF-8 null-terminated string returned from
/// Yrs document API. Yrs strings don't use libc malloc, so calling `free()` on them will fault.
#[no_mangle]
pub unsafe extern "C" fn ystring_destroy(str: *mut c_char) {
if !str.is_null() {
drop(CString::from_raw(str));
}
}
/// Frees all memory-allocated resources bound to a given binary returned from Yrs document API.
/// Unlike strings binaries are not null-terminated and can contain null characters inside,
/// therefore a size of memory to be released must be explicitly provided.
/// Yrs binaries don't use libc malloc, so calling `free()` on them will fault.
#[no_mangle]
pub unsafe extern "C" fn ybinary_destroy(ptr: *mut c_char, len: u32) {
if !ptr.is_null() {
drop(Vec::from_raw_parts(ptr, len as usize, len as usize));
}
}
/// Creates a new [Doc] instance with a randomized unique client identifier.
///
/// Use [ydoc_destroy] in order to release created [Doc] resources.
#[no_mangle]
pub extern "C" fn ydoc_new() -> *mut Doc {
Box::into_raw(Box::new(Doc::new()))
}
/// Creates a shallow clone of a provided `doc` - it's realized by increasing the ref-count
/// value of the document. In result both input and output documents point to the same instance.
///
/// Documents created this way can be destroyed via [ydoc_destroy] - keep in mind, that the memory
/// will still be persisted until all strong references are dropped.
#[no_mangle]
pub unsafe extern "C" fn ydoc_clone(doc: *mut Doc) -> *mut Doc {
let doc = doc.as_mut().unwrap();
Box::into_raw(Box::new(doc.clone()))
}
/// Creates a new [Doc] instance with a specified `options`.
///
/// Use [ydoc_destroy] in order to release created [Doc] resources.
#[no_mangle]
pub extern "C" fn ydoc_new_with_options(options: YOptions) -> *mut Doc {
Box::into_raw(Box::new(Doc::with_options(options.into())))
}
/// Returns a unique client identifier of this [Doc] instance.
#[no_mangle]
pub unsafe extern "C" fn ydoc_id(doc: *mut Doc) -> u64 {
let doc = doc.as_ref().unwrap();
doc.client_id()
}
/// Returns a unique document identifier of this [Doc] instance.
#[no_mangle]
pub unsafe extern "C" fn ydoc_guid(doc: *mut Doc) -> *mut c_char {
let doc = doc.as_ref().unwrap();
let uid = &doc.options().guid;
CString::new(uid.as_ref()).unwrap().into_raw()
}
/// Returns a collection identifier of this [Doc] instance.
/// If none was defined, a `NULL` will be returned.
#[no_mangle]
pub unsafe extern "C" fn ydoc_collection_id(doc: *mut Doc) -> *mut c_char {
let doc = doc.as_ref().unwrap();
if let Some(cid) = doc.options().collection_id.as_ref() {
CString::new(cid.as_str()).unwrap().into_raw()
} else {
null_mut()
}
}
/// Returns status of should_load flag of this [Doc] instance, informing parent [Doc] if this
/// document instance requested a data load.
#[no_mangle]
pub unsafe extern "C" fn ydoc_should_load(doc: *mut Doc) -> u8 {
let doc = doc.as_ref().unwrap();
doc.options().should_load as u8
}
/// Returns status of auto_load flag of this [Doc] instance. Auto loaded sub-documents automatically
/// send a load request to their parent documents.
#[no_mangle]
pub unsafe extern "C" fn ydoc_auto_load(doc: *mut Doc) -> u8 {
let doc = doc.as_ref().unwrap();
doc.options().auto_load as u8
}
#[no_mangle]
pub unsafe extern "C" fn ydoc_observe_updates_v1(
doc: *mut Doc,
state: *mut c_void,
cb: extern "C" fn(*mut c_void, u32, *const c_char),
) -> u32 {
let doc = doc.as_ref().unwrap();
let observer = doc
.observe_update_v1(move |_, e| {
let bytes = &e.update;
let len = bytes.len() as u32;
cb(state, len, bytes.as_ptr() as *const c_char)
})
.unwrap();
let subscription_id: u32 = observer.into();
subscription_id
}
#[no_mangle]
pub unsafe extern "C" fn ydoc_observe_updates_v2(
doc: *mut Doc,
state: *mut c_void,
cb: extern "C" fn(*mut c_void, u32, *const c_char),
) -> u32 {
let doc = doc.as_ref().unwrap();
let observer = doc
.observe_update_v2(move |_, e| {
let bytes = &e.update;
let len = bytes.len() as u32;
cb(state, len, bytes.as_ptr() as *const c_char)
})
.unwrap();
let subscription_id: u32 = observer.into();
subscription_id
}
#[no_mangle]
pub unsafe extern "C" fn ydoc_unobserve_updates_v1(doc: *mut Doc, subscription_id: u32) {
let doc = doc.as_ref().unwrap();
doc.unobserve_update_v1(subscription_id as SubscriptionId);
}
#[no_mangle]
pub unsafe extern "C" fn ydoc_unobserve_updates_v2(doc: *mut Doc, subscription_id: u32) {
let doc = doc.as_ref().unwrap();
doc.unobserve_update_v2(subscription_id as SubscriptionId);
}
#[no_mangle]
pub unsafe extern "C" fn ydoc_observe_after_transaction(
doc: *mut Doc,
state: *mut c_void,
cb: extern "C" fn(*mut c_void, *mut YAfterTransactionEvent),
) -> u32 {
let doc = doc.as_ref().unwrap();
let observer = doc
.observe_transaction_cleanup(move |_, e| {
let mut event = YAfterTransactionEvent::new(e);
cb(state, (&mut event) as *mut _);
})
.unwrap();
let subscription_id: u32 = observer.into();
subscription_id
}
#[no_mangle]
pub unsafe extern "C" fn ydoc_unobserve_after_transaction(doc: *mut Doc, subscription_id: u32) {
let doc = doc.as_ref().unwrap();
doc.unobserve_transaction_cleanup(subscription_id as SubscriptionId);
}
#[no_mangle]
pub unsafe extern "C" fn ydoc_observe_subdocs(
doc: *mut Doc,
state: *mut c_void,
cb: extern "C" fn(*mut c_void, *mut YSubdocsEvent),
) -> u32 {
let doc = doc.as_mut().unwrap();
let observer = doc
.observe_subdocs(move |_, e| {
let mut event = YSubdocsEvent::new(e);
cb(state, (&mut event) as *mut _);
})
.unwrap();
let subscription_id: u32 = observer.into();
subscription_id
}
#[no_mangle]
pub unsafe extern "C" fn ydoc_unobserve_subdocs(doc: *mut Doc, subscription_id: u32) {
let doc = doc.as_ref().unwrap();
doc.unobserve_subdocs(subscription_id as SubscriptionId);
}
#[no_mangle]
pub unsafe extern "C" fn ydoc_observe_clear(
doc: *mut Doc,
state: *mut c_void,
cb: extern "C" fn(*mut c_void, *mut Doc),
) -> u32 {
let doc = doc.as_mut().unwrap();
let observer = doc
.observe_destroy(move |_, e| cb(state, e as *const Doc as *mut _))
.unwrap();
let subscription_id: u32 = observer.into();
subscription_id
}
#[no_mangle]
pub unsafe extern "C" fn ydoc_unobserve_clear(doc: *mut Doc, subscription_id: u32) {
let doc = doc.as_ref().unwrap();
doc.unobserve_destroy(subscription_id as SubscriptionId);
}
/// Manually send a load request to a parent document of this subdoc.
#[no_mangle]
pub unsafe extern "C" fn ydoc_load(doc: *mut Doc, parent_txn: *mut Transaction) {
let doc = doc.as_ref().unwrap();
let txn = parent_txn.as_mut().unwrap();
if let Some(txn) = txn.as_mut() {
doc.load(txn)
} else {
panic!("ydoc_load: passed read-only parent transaction, where read-write one was expected")
}
}
/// Destroys current document, sending a 'destroy' event and clearing up all the event callbacks
/// registered.
#[no_mangle]
pub unsafe extern "C" fn ydoc_clear(doc: *mut Doc, parent_txn: *mut Transaction) {
let doc = doc.as_mut().unwrap();
let txn = parent_txn.as_mut().unwrap();
if let Some(txn) = txn.as_mut() {
doc.destroy(txn)
} else {
panic!("ydoc_clear: passed read-only parent transaction, where read-write one was expected")
}
}
/// Starts a new read-only transaction on a given document. All other operations happen in context
/// of a transaction. Yrs transactions do not follow ACID rules. Once a set of operations is
/// complete, a transaction can be finished using `ytransaction_commit` function.
///
/// Returns `NULL` if read-only transaction couldn't be created, i.e. when another read-write
/// transaction is already opened.
#[no_mangle]
pub unsafe extern "C" fn ydoc_read_transaction(doc: *mut Doc) -> *mut Transaction {
assert!(!doc.is_null());
let doc = doc.as_mut().unwrap();
if let Ok(txn) = doc.try_transact() {
Box::into_raw(Box::new(Transaction::read_only(txn)))
} else {
null_mut()
}
}
/// Starts a new read-write transaction on a given document. All other operations happen in context
/// of a transaction. Yrs transactions do not follow ACID rules. Once a set of operations is
/// complete, a transaction can be finished using `ytransaction_commit` function.
///
/// `origin_len` and `origin` are optional parameters to specify a byte sequence used to mark
/// the origin of this transaction (eg. you may decide to give different origins for transaction
/// applying remote updates). These can be used by event handlers or `UndoManager` to perform
/// specific actions. If origin should not be set, call `ydoc_write_transaction(doc, 0, NULL)`.
///
/// Returns `NULL` if read-write transaction couldn't be created, i.e. when another transaction is
/// already opened.
#[no_mangle]
pub unsafe extern "C" fn ydoc_write_transaction(
doc: *mut Doc,
origin_len: u32,
origin: *const c_char,
) -> *mut Transaction {
assert!(!doc.is_null());
let doc = doc.as_mut().unwrap();
if origin_len == 0 {
if let Ok(txn) = doc.try_transact_mut() {
Box::into_raw(Box::new(Transaction::read_write(txn)))
} else {
null_mut()
}
} else {
let origin = std::slice::from_raw_parts(origin as *const u8, origin_len as usize);
if let Ok(txn) = doc.try_transact_mut_with(origin) {
Box::into_raw(Box::new(Transaction::read_write(txn)))
} else {
null_mut()
}
}
}
/// Starts a new read-write transaction on a given branches document. All other operations happen in
/// context of a transaction. Yrs transactions do not follow ACID rules. Once a set of operations is
/// complete, a transaction can be finished using `ytransaction_commit` function.
///
/// Returns `NULL` if read-write transaction couldn't be created, i.e. when another transaction is
/// already opened.
#[no_mangle]
pub unsafe extern "C" fn ybranch_write_transaction(branch: *mut Branch) -> *mut Transaction {
assert!(!branch.is_null());
let branch = branch.as_mut().unwrap();
if let Ok(txn) = branch.try_transact_mut() {
Box::into_raw(Box::new(Transaction::read_write(txn)))
} else {
null_mut()
}
}
/// Starts a new read-only transaction on a given branches document. All other operations happen in
/// context of a transaction. Yrs transactions do not follow ACID rules. Once a set of operations is
/// complete, a transaction can be finished using `ytransaction_commit` function.
///
/// Returns `NULL` if read-only transaction couldn't be created, i.e. when another read-write
/// transaction is already opened.
#[no_mangle]
pub unsafe extern "C" fn ybranch_read_transaction(branch: *mut Branch) -> *mut Transaction {
assert!(!branch.is_null());
let doc = branch.as_mut().unwrap();
if let Ok(txn) = doc.try_transact() {
Box::into_raw(Box::new(Transaction::read_only(txn)))
} else {
null_mut()
}
}
/// Returns a list of subdocs existing within current document.
#[no_mangle]
pub unsafe extern "C" fn ytransaction_subdocs(
txn: *mut Transaction,
len: *mut u32,
) -> *mut *mut Doc {
let txn = txn.as_ref().unwrap();
let subdocs: Vec<_> = txn
.subdocs()
.map(|doc| doc as *const Doc as *mut Doc)
.collect();
let out = subdocs.into_boxed_slice();
*len = out.len() as u32;
Box::into_raw(out) as *mut _
}
/// Commit and dispose provided read-write transaction. This operation releases allocated resources,
/// triggers update events and performs a storage compression over all operations executed in scope
/// of a current transaction.
#[no_mangle]
pub unsafe extern "C" fn ytransaction_commit(txn: *mut Transaction) {
assert!(!txn.is_null());
drop(Box::from_raw(txn)); // transaction is auto-committed when dropped
}
/// Returns `1` if current transaction is of read-write type.
/// Returns `0` if transaction is read-only.
#[no_mangle]
pub unsafe extern "C" fn ytransaction_writeable(txn: *mut Transaction) -> u8 {
assert!(!txn.is_null());
if txn.as_ref().unwrap().is_writeable() {
1
} else {
0
}
}
/// Gets a reference to shared data type instance at the document root-level,
/// identified by its `name`, which must be a null-terminated UTF-8 compatible string.
///
/// Returns `NULL` if no such structure was defined in the document before.
#[no_mangle]
pub unsafe extern "C" fn ytype_get(txn: *mut Transaction, name: *const c_char) -> *mut Branch {
assert!(!txn.is_null());
assert!(!name.is_null());
let name = CStr::from_ptr(name).to_str().unwrap();
//NOTE: we're retrieving this as a text, but ultimatelly it doesn't matter as we don't define
// nor redefine the underlying branch type
if let Some(txt) = txn.as_mut().unwrap().get_text(name) {
txt.into_raw_branch()
} else {
null_mut()
}
}
/// Gets or creates a new shared `YText` data type instance as a root-level type of a given document.
/// This structure can later be accessed using its `name`, which must be a null-terminated UTF-8
/// compatible string.
#[no_mangle]
pub unsafe extern "C" fn ytext(doc: *mut Doc, name: *const c_char) -> *mut Branch {
assert!(!doc.is_null());
assert!(!name.is_null());
let name = CStr::from_ptr(name).to_str().unwrap();
let txt = doc.as_mut().unwrap().get_or_insert_text(name);
txt.into_raw_branch()
}
/// Gets or creates a new shared `YArray` data type instance as a root-level type of a given document.
/// This structure can later be accessed using its `name`, which must be a null-terminated UTF-8
/// compatible string.
///
/// Use [yarray_destroy] in order to release pointer returned that way - keep in mind that this will
/// not remove `YArray` instance from the document itself (once created it'll last for the entire
/// lifecycle of a document).
#[no_mangle]
pub unsafe extern "C" fn yarray(doc: *mut Doc, name: *const c_char) -> *mut Branch {
assert!(!doc.is_null());
assert!(!name.is_null());
let name = CStr::from_ptr(name).to_str().unwrap();
doc.as_mut()
.unwrap()
.get_or_insert_array(name)
.into_raw_branch()
}
/// Gets or creates a new shared `YMap` data type instance as a root-level type of a given document.
/// This structure can later be accessed using its `name`, which must be a null-terminated UTF-8
/// compatible string.
///
/// Use [ymap_destroy] in order to release pointer returned that way - keep in mind that this will
/// not remove `YMap` instance from the document itself (once created it'll last for the entire
/// lifecycle of a document).
#[no_mangle]
pub unsafe extern "C" fn ymap(doc: *mut Doc, name: *const c_char) -> *mut Branch {
assert!(!doc.is_null());
assert!(!name.is_null());
let name = CStr::from_ptr(name).to_str().unwrap();
doc.as_mut()
.unwrap()
.get_or_insert_map(name)
.into_raw_branch()
}
/// Gets or creates a new shared `YXmlElement` data type instance as a root-level type of a given
/// document. This structure can later be accessed using its `name`, which must be a null-terminated
/// UTF-8 compatible string.
#[no_mangle]
pub unsafe extern "C" fn yxmlelem(doc: *mut Doc, name: *const c_char) -> *mut Branch {
assert!(!doc.is_null());
assert!(!name.is_null());
let name = CStr::from_ptr(name).to_str().unwrap();
doc.as_mut()
.unwrap()
.get_or_insert_xml_element(name)
.into_raw_branch()
}
/// Gets or creates a new shared `YXmlElement` data type instance as a root-level type of a given
/// document. This structure can later be accessed using its `name`, which must be a null-terminated
/// UTF-8 compatible string.
#[no_mangle]
pub unsafe extern "C" fn yxmlfragment(doc: *mut Doc, name: *const c_char) -> *mut Branch {
assert!(!doc.is_null());
assert!(!name.is_null());
let name = CStr::from_ptr(name).to_str().unwrap();
doc.as_mut()
.unwrap()
.get_or_insert_xml_fragment(name)
.into_raw_branch()
}
/// Gets or creates a new shared `YXmlText` data type instance as a root-level type of a given
/// document. This structure can later be accessed using its `name`, which must be a null-terminated
/// UTF-8 compatible string.
#[no_mangle]
pub unsafe extern "C" fn yxmltext(doc: *mut Doc, name: *const c_char) -> *mut Branch {
assert!(!doc.is_null());
assert!(!name.is_null());
let name = CStr::from_ptr(name).to_str().unwrap();
doc.as_mut()
.unwrap()
.get_or_insert_xml_text(name)
.into_raw_branch()
}
/// Returns a state vector of a current transaction's document, serialized using lib0 version 1
/// encoding. Payload created by this function can then be send over the network to a remote peer,
/// where it can be used as a parameter of [ytransaction_state_diff_v1] in order to produce a delta
/// update payload, that can be send back and applied locally in order to efficiently propagate
/// updates from one peer to another.
///
/// The length of a generated binary will be passed within a `len` out parameter.
///
/// Once no longer needed, a returned binary can be disposed using [ybinary_destroy] function.
#[no_mangle]
pub unsafe extern "C" fn ytransaction_state_vector_v1(
txn: *const Transaction,
len: *mut u32,
) -> *mut c_char {
assert!(!txn.is_null());
let txn = txn.as_ref().unwrap();
let state_vector = txn.state_vector();
let binary = state_vector.encode_v1().into_boxed_slice();
*len = binary.len() as u32;
Box::into_raw(binary) as *mut c_char
}
/// Returns a delta difference between current state of a transaction's document and a state vector
/// `sv` encoded as a binary payload using lib0 version 1 encoding (which could be generated using
/// [ytransaction_state_vector_v1]). Such delta can be send back to the state vector's sender in
/// order to propagate and apply (using [ytransaction_apply]) all updates known to a current
/// document, which remote peer was not aware of.
///
/// If passed `sv` pointer is null, the generated diff will be a snapshot containing entire state of
/// the document.
///
/// A length of an encoded state vector payload must be passed as `sv_len` parameter.
///
/// A length of generated delta diff binary will be passed within a `len` out parameter.
///
/// Once no longer needed, a returned binary can be disposed using [ybinary_destroy] function.
#[no_mangle]
pub unsafe extern "C" fn ytransaction_state_diff_v1(
txn: *const Transaction,
sv: *const c_char,
sv_len: u32,
len: *mut u32,
) -> *mut c_char {
assert!(!txn.is_null());
let txn = txn.as_ref().unwrap();
let sv = {
if sv.is_null() {
StateVector::default()
} else {
let sv_slice = std::slice::from_raw_parts(sv as *const u8, sv_len as usize);
if let Ok(sv) = StateVector::decode_v1(sv_slice) {
sv
} else {
return null_mut();
}
}
};
let mut encoder = EncoderV1::new();
txn.encode_diff(&sv, &mut encoder);
let binary = encoder.to_vec().into_boxed_slice();
*len = binary.len() as u32;
Box::into_raw(binary) as *mut c_char
}
/// Returns a delta difference between current state of a transaction's document and a state vector
/// `sv` encoded as a binary payload using lib0 version 1 encoding (which could be generated using
/// [ytransaction_state_vector_v1]). Such delta can be send back to the state vector's sender in
/// order to propagate and apply (using [ytransaction_apply_v2]) all updates known to a current
/// document, which remote peer was not aware of.
///
/// If passed `sv` pointer is null, the generated diff will be a snapshot containing entire state of
/// the document.
///
/// A length of an encoded state vector payload must be passed as `sv_len` parameter.
///
/// A length of generated delta diff binary will be passed within a `len` out parameter.
///
/// Once no longer needed, a returned binary can be disposed using [ybinary_destroy] function.
#[no_mangle]
pub unsafe extern "C" fn ytransaction_state_diff_v2(
txn: *const Transaction,
sv: *const c_char,
sv_len: u32,
len: *mut u32,
) -> *mut c_char {
assert!(!txn.is_null());
let txn = txn.as_ref().unwrap();
let sv = {
if sv.is_null() {
StateVector::default()
} else {
let sv_slice = std::slice::from_raw_parts(sv as *const u8, sv_len as usize);
if let Ok(sv) = StateVector::decode_v1(sv_slice) {
sv
} else {
return null_mut();
}
}
};
let mut encoder = EncoderV2::new();
txn.encode_diff(&sv, &mut encoder);
let binary = encoder.to_vec().into_boxed_slice();
*len = binary.len() as u32;
Box::into_raw(binary) as *mut c_char
}
/// Returns a snapshot descriptor of a current state of the document. This snapshot information
/// can be then used to encode document data at a particular point in time
/// (see: `ytransaction_encode_state_from_snapshot`).
#[no_mangle]
pub unsafe extern "C" fn ytransaction_snapshot(
txn: *const Transaction,
len: *mut u32,
) -> *mut c_char {
assert!(!txn.is_null());
let txn = txn.as_ref().unwrap();
let binary = txn.snapshot().encode_v1().into_boxed_slice();
*len = binary.len() as u32;
Box::into_raw(binary) as *mut c_char
}
/// Encodes a state of the document at a point in time specified by the provided `snapshot`
/// (generated by: `ytransaction_snapshot`). This is useful to generate a past view of the document.
///
/// The returned update is binary compatible with Yrs update lib0 v1 encoding, and can be processed
/// with functions dedicated to work on it, like `ytransaction_apply`.
///
/// This function requires document with a GC option flag turned off (otherwise "time travel" would
/// not be a safe operation). If this is not a case, the NULL pointer will be returned.
#[no_mangle]
pub unsafe extern "C" fn ytransaction_encode_state_from_snapshot_v1(
txn: *const Transaction,
snapshot: *const c_char,
snapshot_len: u32,
len: *mut u32,
) -> *mut c_char {
assert!(!txn.is_null());
let txn = txn.as_ref().unwrap();
let snapshot = {
let len = snapshot_len as usize;
let data = std::slice::from_raw_parts(snapshot as *mut u8, len);
Snapshot::decode_v1(&data).unwrap()
};
let mut encoder = EncoderV1::new();
match txn.encode_state_from_snapshot(&snapshot, &mut encoder) {
Err(_) => null_mut(),
Ok(_) => {
let binary = encoder.to_vec().into_boxed_slice();
*len = binary.len() as u32;
Box::into_raw(binary) as *mut c_char
}
}
}
/// Encodes a state of the document at a point in time specified by the provided `snapshot`
/// (generated by: `ytransaction_snapshot`). This is useful to generate a past view of the document.
///
/// The returned update is binary compatible with Yrs update lib0 v2 encoding, and can be processed
/// with functions dedicated to work on it, like `ytransaction_apply_v2`.