1use std::collections::{Bound, HashMap};
2use std::ffi::{c_char, c_void, CStr, CString};
3use std::mem::{forget, ManuallyDrop, MaybeUninit};
4use std::ops::{Deref, RangeBounds};
5use std::ptr::{null, null_mut};
6use std::sync::atomic::{AtomicPtr, Ordering};
7use std::sync::Arc;
8use yrs::block::{ClientID, EmbedPrelim, ItemContent, Prelim, Unused};
9use yrs::branch::BranchPtr;
10use yrs::encoding::read::Error;
11use yrs::error::UpdateError;
12use yrs::json_path::JsonPathIter as NativeJsonPathIter;
13use yrs::types::array::ArrayEvent;
14use yrs::types::array::ArrayIter as NativeArrayIter;
15use yrs::types::map::MapEvent;
16use yrs::types::map::MapIter as NativeMapIter;
17use yrs::types::text::{Diff, TextEvent, YChange};
18use yrs::types::weak::{LinkSource, Unquote as NativeUnquote, WeakEvent, WeakRef};
19use yrs::types::xml::{Attributes as NativeAttributes, XmlOut};
20use yrs::types::xml::{TreeWalker as NativeTreeWalker, XmlFragment};
21use yrs::types::xml::{XmlEvent, XmlTextEvent};
22use yrs::types::{Attrs, Change, Delta, EntryChange, Event, PathSegment, ToJson, TypeRef};
23use yrs::undo::EventKind;
24use yrs::updates::decoder::{Decode, DecoderV1};
25use yrs::updates::encoder::{Encode, Encoder, EncoderV1, EncoderV2};
26use yrs::{
27 uuid_v4, Any, Array, ArrayRef, Assoc, BranchID, GetString, IdSet, JsonPath, JsonPathEval, Map,
28 MapRef, Number, Observable, OffsetKind, Options, Origin, Out, Quotable, ReadTxn, Snapshot,
29 StateVector, StickyIndex, Store, SubdocsEvent, SubdocsEventIter, Text, TextRef, Transact,
30 TransactionCleanupEvent, Update, Xml, XmlElementPrelim, XmlElementRef, XmlFragmentRef,
31 XmlTextPrelim, XmlTextRef, ID,
32};
33
34pub const Y_JSON: i8 = -9;
37
38pub const Y_JSON_BOOL: i8 = -8;
40
41pub const Y_JSON_NUM: i8 = -7;
43
44pub const Y_JSON_INT: i8 = -6;
46
47pub const Y_JSON_STR: i8 = -5;
49
50pub const Y_JSON_BUF: i8 = -4;
52
53pub const Y_JSON_ARR: i8 = -3;
56
57pub const Y_JSON_MAP: i8 = -2;
60
61pub const Y_JSON_NULL: i8 = -1;
63
64pub const Y_JSON_UNDEF: i8 = 0;
66
67pub const Y_ARRAY: i8 = 1;
69
70pub const Y_MAP: i8 = 2;
72
73pub const Y_TEXT: i8 = 3;
75
76pub const Y_XML_ELEM: i8 = 4;
78
79pub const Y_XML_TEXT: i8 = 5;
81
82pub const Y_XML_FRAG: i8 = 6;
84
85pub const Y_DOC: i8 = 7;
87
88pub const Y_WEAK_LINK: i8 = 8;
90
91pub const Y_UNDEFINED: i8 = 9;
94
95pub const Y_TRUE: u8 = 1;
97
98pub const Y_FALSE: u8 = 0;
100
101pub type Doc = yrs::Doc;
111
112pub type Branch = yrs::branch::Branch;
120
121#[repr(transparent)]
123pub struct ArrayIter(NativeArrayIter<&'static Transaction, Transaction>);
124
125#[repr(transparent)]
127pub struct WeakIter(NativeUnquote<'static, Transaction>);
128
129#[repr(transparent)]
132pub struct MapIter(NativeMapIter<'static, &'static Transaction, Transaction>);
133
134#[repr(transparent)]
138pub struct Attributes(NativeAttributes<'static, &'static Transaction, Transaction>);
139
140#[repr(transparent)]
145pub struct TreeWalker(NativeTreeWalker<'static, &'static Transaction, Transaction>);
146
147#[repr(transparent)]
151pub struct Transaction(TransactionInner);
152
153#[repr(C)]
155pub struct JsonPathIter {
156 query: String,
157 json_path: Box<JsonPath<'static>>,
158 inner: NativeJsonPathIter<'static, Transaction>,
159}
160
161enum TransactionInner {
162 ReadOnly(yrs::Transaction<'static>),
163 ReadWrite(yrs::TransactionMut<'static>),
164}
165
166impl Transaction {
167 fn read_only(txn: yrs::Transaction) -> Self {
168 Transaction(TransactionInner::ReadOnly(unsafe {
169 std::mem::transmute(txn)
170 }))
171 }
172
173 fn read_write(txn: yrs::TransactionMut) -> Self {
174 Transaction(TransactionInner::ReadWrite(unsafe {
175 std::mem::transmute(txn)
176 }))
177 }
178
179 fn is_writeable(&self) -> bool {
180 match &self.0 {
181 TransactionInner::ReadOnly(_) => false,
182 TransactionInner::ReadWrite(_) => true,
183 }
184 }
185
186 fn as_mut(&mut self) -> Option<&mut yrs::TransactionMut<'static>> {
187 match &mut self.0 {
188 TransactionInner::ReadOnly(_) => None,
189 TransactionInner::ReadWrite(txn) => Some(txn),
190 }
191 }
192}
193
194impl ReadTxn for Transaction {
195 fn store(&self) -> &Store {
196 match &self.0 {
197 TransactionInner::ReadOnly(txn) => txn.store(),
198 TransactionInner::ReadWrite(txn) => txn.store(),
199 }
200 }
201}
202
203#[repr(C)]
206pub struct YMapEntry {
207 pub key: *const c_char,
209 pub value: *const YOutput,
212}
213
214impl YMapEntry {
215 fn new(key: &str, value: Box<YOutput>) -> Self {
216 let key = CString::new(key).unwrap().into_raw();
217 let value = Box::into_raw(value) as *const YOutput;
218 YMapEntry { key, value }
219 }
220}
221
222impl Drop for YMapEntry {
223 fn drop(&mut self) {
224 unsafe {
225 drop(CString::from_raw(self.key as *mut c_char));
226 drop(Box::from_raw(self.value as *mut YOutput));
227 }
228 }
229}
230
231#[repr(C)]
234pub struct YXmlAttr {
235 pub name: *const c_char,
236 pub value: *const YOutput,
237}
238
239impl Drop for YXmlAttr {
240 fn drop(&mut self) {
241 unsafe {
242 drop(CString::from_raw(self.name as *mut _));
243 if (!self.value.is_null()) {
244 drop(Box::from_raw(self.value as *mut YOutput));
245 }
246 }
247 }
248}
249
250#[repr(C)]
252pub struct YOptions {
253 pub id: u64,
260
261 pub guid: *const c_char,
264
265 pub collection_id: *const c_char,
268
269 pub flags: u8,
277}
278
279pub const Y_OFFSET_BYTES: u8 = 0;
282
283pub const Y_OFFSET_UTF16: u8 = 1;
286
287pub const Y_SKIP_GC: u8 = 1 << 1;
290
291pub const Y_AUTO_LOAD: u8 = 1 << 2;
294
295pub const Y_SHOULD_LOAD: u8 = 1 << 3;
297
298pub const Y_CLEANUP_FMT: u8 = 1 << 4;
304
305impl Into<Options> for YOptions {
306 fn into(self) -> Options {
307 let mut offset_kind = OffsetKind::Bytes;
308 if self.flags & Y_OFFSET_UTF16 != 0 {
309 offset_kind = OffsetKind::Utf16;
310 }
311 let skip_gc = self.flags & Y_SKIP_GC != 0;
312 let auto_load = self.flags & Y_AUTO_LOAD != 0;
313 let should_load = self.flags & Y_SHOULD_LOAD != 0;
314 let cleanup_formatting = self.flags & Y_CLEANUP_FMT != 0;
315 let guid = if self.guid.is_null() {
316 uuid_v4()
317 } else {
318 let c_str = unsafe { CStr::from_ptr(self.guid) };
319 let str = c_str.to_str().unwrap();
320 str.into()
321 };
322 let collection_id = if self.collection_id.is_null() {
323 None
324 } else {
325 let c_str = unsafe { CStr::from_ptr(self.collection_id) };
326 let str = Arc::from(c_str.to_str().unwrap());
327 Some(str)
328 };
329 Options {
330 client_id: ClientID::new(self.id),
331 guid,
332 collection_id,
333 skip_gc,
334 auto_load,
335 should_load,
336 offset_kind,
337 cleanup_formatting,
338 }
339 }
340}
341
342impl From<Options> for YOptions {
343 fn from(o: Options) -> Self {
344 let mut flags = 0;
345 if o.offset_kind == OffsetKind::Utf16 {
346 flags |= Y_OFFSET_UTF16;
347 }
348 if o.skip_gc {
349 flags |= Y_SKIP_GC;
350 }
351 if o.auto_load {
352 flags |= Y_AUTO_LOAD;
353 }
354 if o.should_load {
355 flags |= Y_SHOULD_LOAD;
356 }
357 if o.cleanup_formatting {
358 flags |= Y_CLEANUP_FMT;
359 }
360
361 YOptions {
362 id: o.client_id.get(),
363 guid: CString::new(o.guid.as_ref()).unwrap().into_raw(),
364 collection_id: if let Some(collection_id) = o.collection_id {
365 CString::new(collection_id.to_string()).unwrap().into_raw()
366 } else {
367 null_mut()
368 },
369 flags,
370 }
371 }
372}
373
374#[no_mangle]
376pub unsafe extern "C" fn yoptions() -> YOptions {
377 Options::default().into()
378}
379
380#[no_mangle]
382pub unsafe extern "C" fn ydoc_destroy(value: *mut Doc) {
383 if !value.is_null() {
384 drop(Box::from_raw(value));
385 }
386}
387
388#[no_mangle]
390pub unsafe extern "C" fn ymap_entry_destroy(value: *mut YMapEntry) {
391 if !value.is_null() {
392 drop(Box::from_raw(value));
393 }
394}
395
396#[no_mangle]
398pub unsafe extern "C" fn yxmlattr_destroy(attr: *mut YXmlAttr) {
399 if !attr.is_null() {
400 drop(Box::from_raw(attr));
401 }
402}
403
404#[no_mangle]
407pub unsafe extern "C" fn ystring_destroy(str: *mut c_char) {
408 if !str.is_null() {
409 drop(CString::from_raw(str));
410 }
411}
412
413#[no_mangle]
418pub unsafe extern "C" fn ybinary_destroy(ptr: *mut c_char, len: u32) {
419 if !ptr.is_null() {
420 drop(Vec::from_raw_parts(ptr, len as usize, len as usize));
421 }
422}
423
424#[no_mangle]
428pub extern "C" fn ydoc_new() -> *mut Doc {
429 Box::into_raw(Box::new(Doc::new()))
430}
431
432#[no_mangle]
438pub unsafe extern "C" fn ydoc_clone(doc: *mut Doc) -> *mut Doc {
439 let doc = doc.as_mut().unwrap();
440 Box::into_raw(Box::new(doc.clone()))
441}
442
443#[no_mangle]
447pub extern "C" fn ydoc_new_with_options(options: YOptions) -> *mut Doc {
448 Box::into_raw(Box::new(Doc::with_options(options.into())))
449}
450
451#[no_mangle]
453pub unsafe extern "C" fn ydoc_id(doc: *mut Doc) -> u64 {
454 let doc = doc.as_ref().unwrap();
455 doc.client_id().get()
456}
457
458#[no_mangle]
462pub unsafe extern "C" fn ydoc_guid(doc: *mut Doc) -> *mut c_char {
463 let doc = doc.as_ref().unwrap();
464 let uid = doc.guid();
465 CString::new(uid.as_ref()).unwrap().into_raw()
466}
467
468#[no_mangle]
473pub unsafe extern "C" fn ydoc_collection_id(doc: *mut Doc) -> *mut c_char {
474 let doc = doc.as_ref().unwrap();
475 if let Some(cid) = doc.collection_id() {
476 CString::new(cid.as_ref()).unwrap().into_raw()
477 } else {
478 null_mut()
479 }
480}
481
482#[no_mangle]
485pub unsafe extern "C" fn ydoc_should_load(doc: *mut Doc) -> u8 {
486 let doc = doc.as_ref().unwrap();
487 doc.should_load() as u8
488}
489
490#[no_mangle]
493pub unsafe extern "C" fn ydoc_auto_load(doc: *mut Doc) -> u8 {
494 let doc = doc.as_ref().unwrap();
495 doc.auto_load() as u8
496}
497
498#[repr(transparent)]
499struct CallbackState(*mut c_void);
500
501unsafe impl Send for CallbackState {}
502unsafe impl Sync for CallbackState {}
503
504impl CallbackState {
505 #[inline]
506 fn new(state: *mut c_void) -> Self {
507 CallbackState(state)
508 }
509}
510
511unsafe fn origin(len: u32, ptr: *const c_char) -> Origin {
513 let bytes: &[u8] = if len == 0 {
514 &[]
515 } else {
516 std::slice::from_raw_parts(ptr as *const u8, len as usize)
517 };
518 Origin::from(bytes)
519}
520
521unsafe fn txn_mut<'a>(txn: *mut Transaction) -> &'a mut yrs::TransactionMut<'static> {
523 txn.as_mut()
524 .unwrap()
525 .as_mut()
526 .expect("read-write transaction expected")
527}
528
529#[no_mangle]
532pub unsafe extern "C" fn ytransaction_observe_updates_v1(
533 txn: *mut Transaction,
534 key_len: u32,
535 key: *const c_char,
536 state: *mut c_void,
537 cb: extern "C" fn(*mut c_void, u32, *const c_char),
538) {
539 let state = CallbackState::new(state);
540 let key = origin(key_len, key);
541 txn_mut(txn).observe_update_v1(key, move |_, e| {
542 let bytes = &e.update;
543 let len = bytes.len() as u32;
544 cb(state.0, len, bytes.as_ptr() as *const c_char)
545 });
546}
547
548#[no_mangle]
551pub unsafe extern "C" fn ytransaction_unobserve_updates_v1(
552 txn: *mut Transaction,
553 key_len: u32,
554 key: *const c_char,
555) -> u8 {
556 let key = origin(key_len, key);
557 txn_mut(txn).unobserve_update_v1(key) as u8
558}
559
560#[no_mangle]
563pub unsafe extern "C" fn ytransaction_observe_updates_v2(
564 txn: *mut Transaction,
565 key_len: u32,
566 key: *const c_char,
567 state: *mut c_void,
568 cb: extern "C" fn(*mut c_void, u32, *const c_char),
569) {
570 let state = CallbackState::new(state);
571 let key = origin(key_len, key);
572 txn_mut(txn).observe_update_v2(key, move |_, e| {
573 let bytes = &e.update;
574 let len = bytes.len() as u32;
575 cb(state.0, len, bytes.as_ptr() as *const c_char)
576 });
577}
578
579#[no_mangle]
582pub unsafe extern "C" fn ytransaction_unobserve_updates_v2(
583 txn: *mut Transaction,
584 key_len: u32,
585 key: *const c_char,
586) -> u8 {
587 let key = origin(key_len, key);
588 txn_mut(txn).unobserve_update_v2(key) as u8
589}
590
591#[no_mangle]
594pub unsafe extern "C" fn ytransaction_observe_after_transaction(
595 txn: *mut Transaction,
596 key_len: u32,
597 key: *const c_char,
598 state: *mut c_void,
599 cb: extern "C" fn(*mut c_void, *mut YAfterTransactionEvent),
600) {
601 let state = CallbackState::new(state);
602 let key = origin(key_len, key);
603 txn_mut(txn).observe_transaction_cleanup(key, move |_, e| {
604 let mut event = YAfterTransactionEvent::new(e);
605 cb(state.0, (&mut event) as *mut _);
606 });
607}
608
609#[no_mangle]
612pub unsafe extern "C" fn ytransaction_unobserve_after_transaction(
613 txn: *mut Transaction,
614 key_len: u32,
615 key: *const c_char,
616) -> u8 {
617 let key = origin(key_len, key);
618 txn_mut(txn).unobserve_transaction_cleanup(key) as u8
619}
620
621#[no_mangle]
624pub unsafe extern "C" fn ytransaction_observe_subdocs(
625 txn: *mut Transaction,
626 key_len: u32,
627 key: *const c_char,
628 state: *mut c_void,
629 cb: extern "C" fn(*mut c_void, *mut YSubdocsEvent),
630) {
631 let state = CallbackState::new(state);
632 let key = origin(key_len, key);
633 txn_mut(txn).observe_subdocs(key, move |_, e| {
634 let mut event = YSubdocsEvent::new(e);
635 cb(state.0, (&mut event) as *mut _);
636 });
637}
638
639#[no_mangle]
642pub unsafe extern "C" fn ytransaction_unobserve_subdocs(
643 txn: *mut Transaction,
644 key_len: u32,
645 key: *const c_char,
646) -> u8 {
647 let key = origin(key_len, key);
648 txn_mut(txn).unobserve_subdocs(key) as u8
649}
650
651#[no_mangle]
654pub unsafe extern "C" fn ytransaction_observe_clear(
655 txn: *mut Transaction,
656 key_len: u32,
657 key: *const c_char,
658 state: *mut c_void,
659 cb: extern "C" fn(*mut c_void, *mut Doc),
660) {
661 let state = CallbackState::new(state);
662 let key = origin(key_len, key);
663 txn_mut(txn).observe_destroy(key, move |_, e| cb(state.0, e as *const Doc as *mut _));
664}
665
666#[no_mangle]
669pub unsafe extern "C" fn ytransaction_unobserve_clear(
670 txn: *mut Transaction,
671 key_len: u32,
672 key: *const c_char,
673) -> u8 {
674 let key = origin(key_len, key);
675 txn_mut(txn).unobserve_destroy(key) as u8
676}
677
678#[no_mangle]
680pub unsafe extern "C" fn ydoc_load(doc: *mut Doc, parent_txn: *mut Transaction) {
681 let doc = doc.as_ref().unwrap();
682 let txn = parent_txn.as_mut().unwrap();
683 if let Some(txn) = txn.as_mut() {
684 doc.load(txn)
685 } else {
686 panic!("ydoc_load: passed read-only parent transaction, where read-write one was expected")
687 }
688}
689
690#[no_mangle]
693pub unsafe extern "C" fn ydoc_clear(doc: *mut Doc, parent_txn: *mut Transaction) {
694 let doc = doc.as_mut().unwrap();
695 let txn = parent_txn.as_mut();
696 let txn = txn.and_then(|tx| tx.as_mut());
697 doc.destroy(txn);
698}
699
700#[no_mangle]
707pub unsafe extern "C" fn ydoc_read_transaction(doc: *mut Doc) -> *mut Transaction {
708 assert!(!doc.is_null());
709
710 let doc = doc.as_mut().unwrap();
711 if let Ok(txn) = doc.try_transact() {
712 Box::into_raw(Box::new(Transaction::read_only(txn)))
713 } else {
714 null_mut()
715 }
716}
717
718#[no_mangle]
730pub unsafe extern "C" fn ydoc_write_transaction(
731 doc: *mut Doc,
732 origin_len: u32,
733 origin: *const c_char,
734) -> *mut Transaction {
735 assert!(!doc.is_null());
736
737 let doc = doc.as_mut().unwrap();
738 if origin_len == 0 {
739 if let Ok(txn) = doc.try_transact_mut() {
740 Box::into_raw(Box::new(Transaction::read_write(txn)))
741 } else {
742 null_mut()
743 }
744 } else {
745 let origin = std::slice::from_raw_parts(origin as *const u8, origin_len as usize);
746 if let Ok(txn) = doc.try_transact_mut_with(origin) {
747 Box::into_raw(Box::new(Transaction::read_write(txn)))
748 } else {
749 null_mut()
750 }
751 }
752}
753
754#[no_mangle]
756pub unsafe extern "C" fn ytransaction_subdocs(
757 txn: *mut Transaction,
758 len: *mut u32,
759) -> *mut *mut Doc {
760 let txn = txn.as_ref().unwrap();
761 let subdocs: Vec<_> = txn
762 .subdocs()
763 .map(|doc| doc as *const Doc as *mut Doc)
764 .collect();
765 let out = subdocs.into_boxed_slice();
766 *len = out.len() as u32;
767 Box::into_raw(out) as *mut _
768}
769
770#[repr(C)]
773pub struct YRootRef {
774 pub name: *mut c_char,
776 pub branch: *mut Branch,
778}
779
780#[no_mangle]
787pub unsafe extern "C" fn ytransaction_root_refs(
788 txn: *const Transaction,
789 len: *mut u32,
790) -> *mut YRootRef {
791 assert!(!txn.is_null());
792 assert!(!len.is_null());
793
794 let txn = txn.as_ref().unwrap();
795 let roots: Vec<_> = txn
796 .root_refs()
797 .filter_map(|(name, value)| {
798 let branch = match value {
799 Out::YText(v) => v.into_raw_branch(),
800 Out::YArray(v) => v.into_raw_branch(),
801 Out::YMap(v) => v.into_raw_branch(),
802 Out::YXmlElement(v) => v.into_raw_branch(),
803 Out::YXmlFragment(v) => v.into_raw_branch(),
804 Out::YXmlText(v) => v.into_raw_branch(),
805 Out::YWeakLink(v) => v.into_raw_branch(),
806 Out::UndefinedRef(v) => v.as_ref() as *const Branch as *mut Branch,
807 Out::Any(_) | Out::YDoc(_) => return None,
809 };
810 Some(YRootRef {
811 name: CString::new(name).unwrap().into_raw(),
812 branch,
813 })
814 })
815 .collect();
816 let out = roots.into_boxed_slice();
817 *len = out.len() as u32;
818 Box::into_raw(out) as *mut YRootRef
819}
820
821#[no_mangle]
824pub unsafe extern "C" fn yroot_refs_destroy(roots: *mut YRootRef, len: u32) {
825 if roots.is_null() {
826 return;
827 }
828 let roots = Box::from_raw(std::ptr::slice_from_raw_parts_mut(roots, len as usize));
829 for root in roots.iter() {
830 ystring_destroy(root.name);
831 }
832}
833
834#[no_mangle]
838pub unsafe extern "C" fn ytransaction_commit(txn: *mut Transaction) {
839 assert!(!txn.is_null());
840 drop(Box::from_raw(txn)); }
842
843#[no_mangle]
847pub unsafe extern "C" fn ytransaction_force_gc(txn: *mut Transaction) {
848 assert!(!txn.is_null());
849 let txn = txn.as_mut().unwrap();
850 let txn = txn.as_mut().unwrap();
851 txn.gc(None);
852}
853
854#[no_mangle]
857pub unsafe extern "C" fn ytransaction_writeable(txn: *mut Transaction) -> u8 {
858 assert!(!txn.is_null());
859 if txn.as_ref().unwrap().is_writeable() {
860 1
861 } else {
862 0
863 }
864}
865
866#[no_mangle]
887pub unsafe extern "C" fn ytransaction_json_path(
888 txn: *mut Transaction,
889 json_path: *const c_char,
890) -> *mut JsonPathIter {
891 assert!(!txn.is_null());
892 let txn = txn.as_ref().unwrap();
893
894 let query: String = CStr::from_ptr(json_path).to_str().unwrap().into();
896 let json_path: &'static str = unsafe { std::mem::transmute(query.as_str()) };
898 let json_path = match JsonPath::parse(json_path) {
899 Ok(query) => Box::new(query),
900 Err(_) => return null_mut(),
901 };
902 let json_path_ref: &'static JsonPath = unsafe { std::mem::transmute(json_path.as_ref()) };
904 let inner = txn.json_path(json_path_ref);
905 let iter = Box::new(JsonPathIter {
906 query,
907 json_path,
908 inner,
909 });
910 Box::into_raw(iter)
911}
912
913#[no_mangle]
915pub unsafe extern "C" fn yjson_path_iter_next(iter: *mut JsonPathIter) -> *mut YOutput {
916 assert!(!iter.is_null());
917 let iter = iter.as_mut().unwrap();
918 if let Some(value) = iter.inner.next() {
919 let youtput = YOutput::from(value);
920 Box::into_raw(Box::new(youtput))
921 } else {
922 null_mut()
923 }
924}
925
926#[no_mangle]
928pub unsafe extern "C" fn yjson_path_iter_destroy(iter: *mut JsonPathIter) {
929 if !iter.is_null() {
930 drop(Box::from_raw(iter));
931 }
932}
933
934#[no_mangle]
940pub unsafe extern "C" fn ytype_get(txn: *mut Transaction, name: *const c_char) -> *mut Branch {
941 assert!(!txn.is_null());
942 assert!(!name.is_null());
943
944 let name = CStr::from_ptr(name).to_str().unwrap();
945 if let Some(txt) = txn.as_mut().unwrap().get_text(name) {
948 txt.into_raw_branch()
949 } else {
950 null_mut()
951 }
952}
953
954#[no_mangle]
958pub unsafe extern "C" fn ytext(doc: *mut Doc, name: *const c_char) -> *mut Branch {
959 assert!(!doc.is_null());
960 assert!(!name.is_null());
961
962 let name = CStr::from_ptr(name).to_str().unwrap();
963 let txt = doc.as_mut().unwrap().get_or_insert_text(name);
964 txt.into_raw_branch()
965}
966
967#[no_mangle]
973pub unsafe extern "C" fn yarray(doc: *mut Doc, name: *const c_char) -> *mut Branch {
974 assert!(!doc.is_null());
975 assert!(!name.is_null());
976
977 let name = CStr::from_ptr(name).to_str().unwrap();
978 doc.as_mut()
979 .unwrap()
980 .get_or_insert_array(name)
981 .into_raw_branch()
982}
983
984#[no_mangle]
990pub unsafe extern "C" fn ymap(doc: *mut Doc, name: *const c_char) -> *mut Branch {
991 assert!(!doc.is_null());
992 assert!(!name.is_null());
993
994 let name = CStr::from_ptr(name).to_str().unwrap();
995 doc.as_mut()
996 .unwrap()
997 .get_or_insert_map(name)
998 .into_raw_branch()
999}
1000
1001#[no_mangle]
1005pub unsafe extern "C" fn yxmlfragment(doc: *mut Doc, name: *const c_char) -> *mut Branch {
1006 assert!(!doc.is_null());
1007 assert!(!name.is_null());
1008
1009 let name = CStr::from_ptr(name).to_str().unwrap();
1010 doc.as_mut()
1011 .unwrap()
1012 .get_or_insert_xml_fragment(name)
1013 .into_raw_branch()
1014}
1015
1016#[no_mangle]
1026pub unsafe extern "C" fn ytransaction_state_vector_v1(
1027 txn: *const Transaction,
1028 len: *mut u32,
1029) -> *mut c_char {
1030 assert!(!txn.is_null());
1031
1032 let txn = txn.as_ref().unwrap();
1033 let state_vector = txn.state_vector();
1034 let binary = state_vector.encode_v1().into_boxed_slice();
1035
1036 *len = binary.len() as u32;
1037 Box::into_raw(binary) as *mut c_char
1038}
1039
1040#[no_mangle]
1055pub unsafe extern "C" fn ytransaction_state_diff_v1(
1056 txn: *const Transaction,
1057 sv: *const c_char,
1058 sv_len: u32,
1059 len: *mut u32,
1060) -> *mut c_char {
1061 assert!(!txn.is_null());
1062
1063 let txn = txn.as_ref().unwrap();
1064 let sv = {
1065 if sv.is_null() {
1066 StateVector::default()
1067 } else {
1068 let sv_slice = std::slice::from_raw_parts(sv as *const u8, sv_len as usize);
1069 if let Ok(sv) = StateVector::decode_v1(sv_slice) {
1070 sv
1071 } else {
1072 return null_mut();
1073 }
1074 }
1075 };
1076
1077 let mut encoder = EncoderV1::new();
1078 txn.encode_diff(&sv, &mut encoder);
1079 let binary = encoder.to_vec().into_boxed_slice();
1080 *len = binary.len() as u32;
1081 Box::into_raw(binary) as *mut c_char
1082}
1083
1084#[no_mangle]
1099pub unsafe extern "C" fn ytransaction_state_diff_v2(
1100 txn: *const Transaction,
1101 sv: *const c_char,
1102 sv_len: u32,
1103 len: *mut u32,
1104) -> *mut c_char {
1105 assert!(!txn.is_null());
1106
1107 let txn = txn.as_ref().unwrap();
1108 let sv = {
1109 if sv.is_null() {
1110 StateVector::default()
1111 } else {
1112 let sv_slice = std::slice::from_raw_parts(sv as *const u8, sv_len as usize);
1113 if let Ok(sv) = StateVector::decode_v1(sv_slice) {
1114 sv
1115 } else {
1116 return null_mut();
1117 }
1118 }
1119 };
1120
1121 let mut encoder = EncoderV2::new();
1122 txn.encode_diff(&sv, &mut encoder);
1123 let binary = encoder.to_vec().into_boxed_slice();
1124 *len = binary.len() as u32;
1125 Box::into_raw(binary) as *mut c_char
1126}
1127
1128#[no_mangle]
1132pub unsafe extern "C" fn ytransaction_snapshot(
1133 txn: *const Transaction,
1134 len: *mut u32,
1135) -> *mut c_char {
1136 assert!(!txn.is_null());
1137 let txn = txn.as_ref().unwrap();
1138 let binary = txn.snapshot().encode_v1().into_boxed_slice();
1139
1140 *len = binary.len() as u32;
1141 Box::into_raw(binary) as *mut c_char
1142}
1143
1144#[no_mangle]
1153pub unsafe extern "C" fn ytransaction_encode_state_from_snapshot_v1(
1154 txn: *const Transaction,
1155 snapshot: *const c_char,
1156 snapshot_len: u32,
1157 len: *mut u32,
1158) -> *mut c_char {
1159 assert!(!txn.is_null());
1160 let txn = txn.as_ref().unwrap();
1161 let snapshot = {
1162 let len = snapshot_len as usize;
1163 let data = std::slice::from_raw_parts(snapshot as *mut u8, len);
1164 Snapshot::decode_v1(&data).unwrap()
1165 };
1166 let mut encoder = EncoderV1::new();
1167 match txn.encode_state_from_snapshot(&snapshot, &mut encoder) {
1168 Err(_) => null_mut(),
1169 Ok(_) => {
1170 let binary = encoder.to_vec().into_boxed_slice();
1171 *len = binary.len() as u32;
1172 Box::into_raw(binary) as *mut c_char
1173 }
1174 }
1175}
1176
1177#[no_mangle]
1186pub unsafe extern "C" fn ytransaction_encode_state_from_snapshot_v2(
1187 txn: *const Transaction,
1188 snapshot: *const c_char,
1189 snapshot_len: u32,
1190 len: *mut u32,
1191) -> *mut c_char {
1192 assert!(!txn.is_null());
1193 let txn = txn.as_ref().unwrap();
1194 let snapshot = {
1195 let len = snapshot_len as usize;
1196 let data = std::slice::from_raw_parts(snapshot as *mut u8, len);
1197 Snapshot::decode_v1(&data).unwrap()
1198 };
1199 let mut encoder = EncoderV2::new();
1200 match txn.encode_state_from_snapshot(&snapshot, &mut encoder) {
1201 Err(_) => null_mut(),
1202 Ok(_) => {
1203 let binary = encoder.to_vec().into_boxed_slice();
1204 *len = binary.len() as u32;
1205 Box::into_raw(binary) as *mut c_char
1206 }
1207 }
1208}
1209
1210#[no_mangle]
1216pub unsafe extern "C" fn ytransaction_pending_ds(txn: *const Transaction) -> *mut YIdSet {
1217 let txn = txn.as_ref().unwrap();
1218 match txn.store().pending_ds() {
1219 None => null_mut(),
1220 Some(ds) => Box::into_raw(Box::new(YIdSet::new(ds))),
1221 }
1222}
1223
1224#[no_mangle]
1225pub unsafe extern "C" fn ydelete_set_destroy(ds: *mut YIdSet) {
1226 if ds.is_null() {
1227 return;
1228 }
1229 drop(Box::from_raw(ds))
1230}
1231
1232#[no_mangle]
1241pub unsafe extern "C" fn ytransaction_pending_update(
1242 txn: *const Transaction,
1243) -> *mut YPendingUpdate {
1244 let txn = txn.as_ref().unwrap();
1245 match txn.store().pending_update() {
1246 None => null_mut(),
1247 Some(u) => {
1248 let binary = u.update.encode_v1().into_boxed_slice();
1249 let update_len = binary.len() as u32;
1250 let missing = YStateVector::new(&u.missing);
1251 let update = YPendingUpdate {
1252 missing,
1253 update_len,
1254 update_v1: Box::into_raw(binary) as *mut c_char,
1255 };
1256 Box::into_raw(Box::new(update))
1257 }
1258 }
1259}
1260
1261#[repr(C)]
1265pub struct YPendingUpdate {
1266 pub missing: YStateVector,
1269 pub update_v1: *mut c_char,
1271 pub update_len: u32,
1273}
1274
1275#[no_mangle]
1276pub unsafe extern "C" fn ypending_update_destroy(update: *mut YPendingUpdate) {
1277 if update.is_null() {
1278 return;
1279 }
1280 let update = Box::from_raw(update);
1281 drop(update.missing);
1282 ybinary_destroy(update.update_v1, update.update_len);
1283}
1284
1285#[no_mangle]
1289pub unsafe extern "C" fn yupdate_debug_v1(update: *const c_char, update_len: u32) -> *mut c_char {
1290 assert!(!update.is_null());
1291
1292 let data = std::slice::from_raw_parts(update as *const u8, update_len as usize);
1293 if let Ok(u) = Update::decode_v1(data) {
1294 let str = format!("{:#?}", u);
1295 CString::new(str).unwrap().into_raw()
1296 } else {
1297 null_mut()
1298 }
1299}
1300
1301#[no_mangle]
1305pub unsafe extern "C" fn yupdate_debug_v2(update: *const c_char, update_len: u32) -> *mut c_char {
1306 assert!(!update.is_null());
1307
1308 let data = std::slice::from_raw_parts(update as *const u8, update_len as usize);
1309 if let Ok(u) = Update::decode_v2(data) {
1310 let str = format!("{:#?}", u);
1311 CString::new(str).unwrap().into_raw()
1312 } else {
1313 null_mut()
1314 }
1315}
1316
1317#[no_mangle]
1331pub unsafe extern "C" fn ytransaction_apply(
1332 txn: *mut Transaction,
1333 diff: *const c_char,
1334 diff_len: u32,
1335) -> u8 {
1336 assert!(!txn.is_null());
1337 assert!(!diff.is_null());
1338
1339 let update = std::slice::from_raw_parts(diff as *const u8, diff_len as usize);
1340 let mut decoder = DecoderV1::from(update);
1341 match Update::decode(&mut decoder) {
1342 Ok(update) => {
1343 let txn = txn.as_mut().unwrap();
1344 let txn = txn
1345 .as_mut()
1346 .expect("provided transaction was not writeable");
1347 match txn.apply_update(update) {
1348 Ok(_) => 0,
1349 Err(e) => update_err_code(e),
1350 }
1351 }
1352 Err(e) => err_code(e),
1353 }
1354}
1355
1356#[no_mangle]
1370pub unsafe extern "C" fn ytransaction_apply_v2(
1371 txn: *mut Transaction,
1372 diff: *const c_char,
1373 diff_len: u32,
1374) -> u8 {
1375 assert!(!txn.is_null());
1376 assert!(!diff.is_null());
1377
1378 let mut update = std::slice::from_raw_parts(diff as *const u8, diff_len as usize);
1379 match Update::decode_v2(&mut update) {
1380 Ok(update) => {
1381 let txn = txn.as_mut().unwrap();
1382 let txn = txn
1383 .as_mut()
1384 .expect("provided transaction was not writeable");
1385 match txn.apply_update(update) {
1386 Ok(_) => 0,
1387 Err(e) => update_err_code(e),
1388 }
1389 }
1390 Err(e) => err_code(e),
1391 }
1392}
1393
1394pub const ERR_CODE_IO: u8 = 1;
1396
1397pub const ERR_CODE_VAR_INT: u8 = 2;
1399
1400pub const ERR_CODE_EOS: u8 = 3;
1402
1403pub const ERR_CODE_UNEXPECTED_VALUE: u8 = 4;
1405
1406pub const ERR_CODE_INVALID_JSON: u8 = 5;
1408
1409pub const ERR_CODE_OTHER: u8 = 6;
1411
1412pub const ERR_NOT_ENOUGH_MEMORY: u8 = 7;
1414
1415pub const ERR_TYPE_MISMATCH: u8 = 8;
1417
1418pub const ERR_CUSTOM: u8 = 9;
1420
1421pub const ERR_MALFORMED: u8 = 10;
1423
1424pub const ERR_INVALID_PARENT: u8 = 9;
1426
1427fn err_code(e: Error) -> u8 {
1428 match e {
1429 Error::InvalidVarInt => ERR_CODE_VAR_INT,
1430 Error::EndOfBuffer(_) => ERR_CODE_EOS,
1431 Error::UnexpectedValue => ERR_CODE_UNEXPECTED_VALUE,
1432 Error::InvalidJSON(_) => ERR_CODE_INVALID_JSON,
1433 Error::NotEnoughMemory(_) => ERR_NOT_ENOUGH_MEMORY,
1434 Error::TypeMismatch(_) => ERR_TYPE_MISMATCH,
1435 Error::Custom(_) => ERR_CUSTOM,
1436 Error::Malformed(_) => ERR_MALFORMED,
1437 }
1438}
1439fn update_err_code(e: UpdateError) -> u8 {
1440 match e {
1441 UpdateError::InvalidParent(_, _) => ERR_INVALID_PARENT,
1442 }
1443}
1444
1445#[no_mangle]
1447pub unsafe extern "C" fn ytext_len(txt: *const Branch, txn: *const Transaction) -> u32 {
1448 assert!(!txt.is_null());
1449 let txn = txn.as_ref().unwrap();
1450 let txt = TextRef::from_raw_branch(txt);
1451 txt.len(txn)
1452}
1453
1454#[no_mangle]
1458pub unsafe extern "C" fn ytext_string(txt: *const Branch, txn: *const Transaction) -> *mut c_char {
1459 assert!(!txt.is_null());
1460
1461 let txn = txn.as_ref().unwrap();
1462 let txt = TextRef::from_raw_branch(txt);
1463 let str = txt.get_string(txn);
1464 CString::new(str).unwrap().into_raw()
1465}
1466
1467#[no_mangle]
1478pub unsafe extern "C" fn ytext_insert(
1479 txt: *const Branch,
1480 txn: *mut Transaction,
1481 index: u32,
1482 value: *const c_char,
1483 attrs: *const YInput,
1484) {
1485 assert!(!txt.is_null());
1486 assert!(!txn.is_null());
1487 assert!(!value.is_null());
1488
1489 let chunk = CStr::from_ptr(value).to_str().unwrap();
1490 let txn = txn.as_mut().unwrap();
1491 let txn = txn
1492 .as_mut()
1493 .expect("provided transaction was not writeable");
1494 let txt = TextRef::from_raw_branch(txt);
1495 let index = index as u32;
1496 if attrs.is_null() {
1497 txt.insert(txn, index, chunk)
1498 } else {
1499 if let Some(attrs) = map_attrs(attrs.read().into()) {
1500 txt.insert_with_attributes(txn, index, chunk, attrs)
1501 } else {
1502 panic!("ytext_insert: passed attributes are not of map type")
1503 }
1504 }
1505}
1506
1507#[no_mangle]
1510pub unsafe extern "C" fn ytext_format(
1511 txt: *const Branch,
1512 txn: *mut Transaction,
1513 index: u32,
1514 len: u32,
1515 attrs: *const YInput,
1516) {
1517 assert!(!txt.is_null());
1518 assert!(!txn.is_null());
1519 assert!(!attrs.is_null());
1520
1521 if let Some(attrs) = map_attrs(attrs.read().into()) {
1522 let txt = TextRef::from_raw_branch(txt);
1523 let txn = txn.as_mut().unwrap();
1524 let txn = txn
1525 .as_mut()
1526 .expect("provided transaction was not writeable");
1527 let index = index as u32;
1528 let len = len as u32;
1529 txt.format(txn, index, len, attrs);
1530 } else {
1531 panic!("ytext_format: passed attributes are not of map type")
1532 }
1533}
1534
1535#[no_mangle]
1546pub unsafe extern "C" fn ytext_insert_embed(
1547 txt: *const Branch,
1548 txn: *mut Transaction,
1549 index: u32,
1550 content: *const YInput,
1551 attrs: *const YInput,
1552) {
1553 assert!(!txt.is_null());
1554 assert!(!txn.is_null());
1555 assert!(!content.is_null());
1556
1557 let txn = txn.as_mut().unwrap();
1558 let txn = txn
1559 .as_mut()
1560 .expect("provided transaction was not writeable");
1561 let txt = TextRef::from_raw_branch(txt);
1562 let index = index as u32;
1563 let content = content.read();
1564 if attrs.is_null() {
1565 txt.insert_embed(txn, index, content);
1566 } else {
1567 if let Some(attrs) = map_attrs(attrs.read().into()) {
1568 txt.insert_embed_with_attributes(txn, index, content, attrs);
1569 } else {
1570 panic!("ytext_insert_embed: passed attributes are not of map type")
1571 }
1572 }
1573}
1574
1575#[no_mangle]
1589pub unsafe extern "C" fn ytext_insert_delta(
1590 txt: *const Branch,
1591 txn: *mut Transaction,
1592 delta: *mut YDeltaIn,
1593 delta_len: u32,
1594) {
1595 let txt = TextRef::from_raw_branch(txt);
1596 let txn = txn.as_mut().unwrap();
1597 let txn = txn
1598 .as_mut()
1599 .expect("provided transaction was not writeable");
1600 let delta = std::slice::from_raw_parts(delta, delta_len as usize);
1601 let mut insert = Vec::with_capacity(delta.len());
1602 for chunk in delta {
1603 let d = chunk.as_input();
1604 insert.push(d);
1605 }
1606 txt.apply_delta(txn, insert);
1607}
1608
1609#[no_mangle]
1613pub unsafe extern "C" fn ydelta_input_retain(len: u32, attrs: *const YInput) -> YDeltaIn {
1614 YDeltaIn {
1615 tag: Y_EVENT_CHANGE_RETAIN,
1616 len,
1617 attributes: attrs,
1618 insert: null(),
1619 }
1620}
1621
1622#[no_mangle]
1625pub unsafe extern "C" fn ydelta_input_delete(len: u32) -> YDeltaIn {
1626 YDeltaIn {
1627 tag: Y_EVENT_CHANGE_DELETE,
1628 len,
1629 attributes: null(),
1630 insert: null(),
1631 }
1632}
1633
1634#[no_mangle]
1640pub unsafe extern "C" fn ydelta_input_insert(
1641 data: *const YInput,
1642 attrs: *const YInput,
1643) -> YDeltaIn {
1644 YDeltaIn {
1645 tag: Y_EVENT_CHANGE_ADD,
1646 len: 1,
1647 attributes: attrs,
1648 insert: data,
1649 }
1650}
1651
1652fn map_attrs(attrs: Any) -> Option<Attrs> {
1653 if let Any::Map(attrs) = attrs {
1654 let attrs = attrs
1655 .iter()
1656 .map(|(k, v)| (k.as_str().into(), v.clone()))
1657 .collect();
1658 Some(attrs)
1659 } else {
1660 None
1661 }
1662}
1663
1664#[no_mangle]
1673pub unsafe extern "C" fn ytext_remove_range(
1674 txt: *const Branch,
1675 txn: *mut Transaction,
1676 index: u32,
1677 length: u32,
1678) {
1679 assert!(!txt.is_null());
1680 assert!(!txn.is_null());
1681
1682 let txn = txn.as_mut().unwrap();
1683 let txn = txn
1684 .as_mut()
1685 .expect("provided transaction was not writeable");
1686 let txt = TextRef::from_raw_branch(txt);
1687 txt.remove_range(txn, index as u32, length as u32)
1688}
1689
1690#[no_mangle]
1692pub unsafe extern "C" fn yarray_len(array: *const Branch) -> u32 {
1693 assert!(!array.is_null());
1694
1695 let array = array.as_ref().unwrap();
1696 array.len() as u32
1697}
1698
1699#[no_mangle]
1704pub unsafe extern "C" fn yarray_get(
1705 array: *const Branch,
1706 txn: *const Transaction,
1707 index: u32,
1708) -> *mut YOutput {
1709 assert!(!array.is_null());
1710
1711 let array = ArrayRef::from_raw_branch(array);
1712 let txn = txn.as_ref().unwrap();
1713
1714 if let Some(val) = array.get(txn, index as u32) {
1715 Box::into_raw(Box::new(YOutput::from(val)))
1716 } else {
1717 std::ptr::null_mut()
1718 }
1719}
1720
1721#[no_mangle]
1732pub unsafe extern "C" fn yarray_get_json(
1733 array: *const Branch,
1734 txn: *const Transaction,
1735 index: u32,
1736) -> *mut c_char {
1737 assert!(!array.is_null());
1738
1739 let array = ArrayRef::from_raw_branch(array);
1740 let txn = txn.as_ref().unwrap();
1741
1742 if let Some(val) = array.get(txn, index as u32) {
1743 let any = val.to_json(txn);
1744 let json = match serde_json::to_string(&any) {
1745 Ok(json) => json,
1746 Err(_) => return std::ptr::null_mut(),
1747 };
1748 CString::new(json).unwrap().into_raw()
1749 } else {
1750 std::ptr::null_mut()
1751 }
1752}
1753
1754#[no_mangle]
1765pub unsafe extern "C" fn yarray_insert_range(
1766 array: *const Branch,
1767 txn: *mut Transaction,
1768 index: u32,
1769 items: *const YInput,
1770 items_len: u32,
1771) {
1772 assert!(!array.is_null());
1773 assert!(!txn.is_null());
1774 assert!(!items.is_null());
1775
1776 let array = ArrayRef::from_raw_branch(array);
1777 let txn = txn.as_mut().unwrap();
1778 let txn = txn
1779 .as_mut()
1780 .expect("provided transaction was not writeable");
1781
1782 let ptr = items;
1783 let mut i = 0;
1784 let mut j = index as u32;
1785 let len = items_len as isize;
1786 while i < len {
1787 let mut vec: Vec<Any> = Vec::default();
1788
1789 while i < len {
1791 let val = ptr.offset(i).read();
1792 if val.tag <= 0 {
1793 let any = val.into();
1794 vec.push(any);
1795 } else {
1796 break;
1797 }
1798 i += 1;
1799 }
1800
1801 if !vec.is_empty() {
1802 let len = vec.len() as u32;
1803 array.insert_range(txn, j, vec);
1804 j += len;
1805 } else {
1806 let val = ptr.offset(i).read();
1807 array.insert(txn, j, val);
1808 i += 1;
1809 j += 1;
1810 }
1811 }
1812}
1813
1814#[no_mangle]
1818pub unsafe extern "C" fn yarray_remove_range(
1819 array: *const Branch,
1820 txn: *mut Transaction,
1821 index: u32,
1822 len: u32,
1823) {
1824 assert!(!array.is_null());
1825 assert!(!txn.is_null());
1826
1827 let array = ArrayRef::from_raw_branch(array);
1828 let txn = txn.as_mut().unwrap();
1829 let txn = txn
1830 .as_mut()
1831 .expect("provided transaction was not writeable");
1832
1833 array.remove_range(txn, index as u32, len as u32)
1834}
1835
1836#[no_mangle]
1842pub unsafe extern "C" fn yarray_iter(
1843 array: *const Branch,
1844 txn: *mut Transaction,
1845) -> *mut ArrayIter {
1846 assert!(!array.is_null());
1847 assert!(!txn.is_null());
1848
1849 let txn = txn.as_ref().unwrap();
1850 let array = &ArrayRef::from_raw_branch(array) as *const ArrayRef;
1851 Box::into_raw(Box::new(ArrayIter(array.as_ref().unwrap().iter(txn))))
1852}
1853
1854#[no_mangle]
1856pub unsafe extern "C" fn yarray_iter_destroy(iter: *mut ArrayIter) {
1857 if !iter.is_null() {
1858 drop(Box::from_raw(iter))
1859 }
1860}
1861
1862#[no_mangle]
1867pub unsafe extern "C" fn yarray_iter_next(iterator: *mut ArrayIter) -> *mut YOutput {
1868 assert!(!iterator.is_null());
1869
1870 let iter = iterator.as_mut().unwrap();
1871 if let Some(v) = iter.0.next() {
1872 let out = YOutput::from(v);
1873 Box::into_raw(Box::new(out))
1874 } else {
1875 std::ptr::null_mut()
1876 }
1877}
1878
1879#[no_mangle]
1884pub unsafe extern "C" fn ymap_iter(map: *const Branch, txn: *const Transaction) -> *mut MapIter {
1885 assert!(!map.is_null());
1886
1887 let txn = txn.as_ref().unwrap();
1888 let map = &MapRef::from_raw_branch(map) as *const MapRef;
1889 Box::into_raw(Box::new(MapIter(map.as_ref().unwrap().iter(txn))))
1890}
1891
1892#[no_mangle]
1894pub unsafe extern "C" fn ymap_iter_destroy(iter: *mut MapIter) {
1895 if !iter.is_null() {
1896 drop(Box::from_raw(iter))
1897 }
1898}
1899
1900#[no_mangle]
1906pub unsafe extern "C" fn ymap_iter_next(iter: *mut MapIter) -> *mut YMapEntry {
1907 assert!(!iter.is_null());
1908
1909 let iter = iter.as_mut().unwrap();
1910 if let Some((key, value)) = iter.0.next() {
1911 let output = YOutput::from(value);
1912 Box::into_raw(Box::new(YMapEntry::new(key, Box::new(output))))
1913 } else {
1914 std::ptr::null_mut()
1915 }
1916}
1917
1918#[no_mangle]
1920pub unsafe extern "C" fn ymap_len(map: *const Branch, txn: *const Transaction) -> u32 {
1921 assert!(!map.is_null());
1922
1923 let txn = txn.as_ref().unwrap();
1924 let map = MapRef::from_raw_branch(map);
1925
1926 map.len(txn)
1927}
1928
1929#[no_mangle]
1938pub unsafe extern "C" fn ymap_insert(
1939 map: *const Branch,
1940 txn: *mut Transaction,
1941 key: *const c_char,
1942 value: *const YInput,
1943) {
1944 assert!(!map.is_null());
1945 assert!(!txn.is_null());
1946 assert!(!key.is_null());
1947 assert!(!value.is_null());
1948
1949 let cstr = CStr::from_ptr(key);
1950 let key = cstr.to_str().unwrap().to_string();
1951
1952 let map = MapRef::from_raw_branch(map);
1953 let txn = txn.as_mut().unwrap();
1954 let txn = txn
1955 .as_mut()
1956 .expect("provided transaction was not writeable");
1957
1958 map.insert(txn, key, value.read());
1959}
1960
1961#[no_mangle]
1966pub unsafe extern "C" fn ymap_remove(
1967 map: *const Branch,
1968 txn: *mut Transaction,
1969 key: *const c_char,
1970) -> u8 {
1971 assert!(!map.is_null());
1972 assert!(!txn.is_null());
1973 assert!(!key.is_null());
1974
1975 let key = CStr::from_ptr(key).to_str().unwrap();
1976
1977 let map = MapRef::from_raw_branch(map);
1978 let txn = txn.as_mut().unwrap();
1979 let txn = txn
1980 .as_mut()
1981 .expect("provided transaction was not writeable");
1982
1983 if let Some(_) = map.remove(txn, key) {
1984 Y_TRUE
1985 } else {
1986 Y_FALSE
1987 }
1988}
1989
1990#[no_mangle]
1996pub unsafe extern "C" fn ymap_get(
1997 map: *const Branch,
1998 txn: *const Transaction,
1999 key: *const c_char,
2000) -> *mut YOutput {
2001 assert!(!map.is_null());
2002 assert!(!key.is_null());
2003 assert!(!txn.is_null());
2004
2005 let txn = txn.as_ref().unwrap();
2006 let key = CStr::from_ptr(key).to_str().unwrap();
2007
2008 let map = MapRef::from_raw_branch(map);
2009
2010 if let Some(value) = map.get(txn, key) {
2011 let output = YOutput::from(value);
2012 Box::into_raw(Box::new(output))
2013 } else {
2014 std::ptr::null_mut()
2015 }
2016}
2017
2018#[no_mangle]
2027pub unsafe extern "C" fn ymap_get_json(
2028 map: *const Branch,
2029 txn: *const Transaction,
2030 key: *const c_char,
2031) -> *mut c_char {
2032 assert!(!map.is_null());
2033 assert!(!key.is_null());
2034 assert!(!txn.is_null());
2035
2036 let txn = txn.as_ref().unwrap();
2037 let key = CStr::from_ptr(key).to_str().unwrap();
2038
2039 let map = MapRef::from_raw_branch(map);
2040
2041 if let Some(value) = map.get(txn, key) {
2042 let any = value.to_json(txn);
2043 match serde_json::to_string(&any) {
2044 Ok(json) => CString::new(json).unwrap().into_raw(),
2045 Err(_) => std::ptr::null_mut(),
2046 }
2047 } else {
2048 std::ptr::null_mut()
2049 }
2050}
2051
2052#[no_mangle]
2054pub unsafe extern "C" fn ymap_remove_all(map: *const Branch, txn: *mut Transaction) {
2055 assert!(!map.is_null());
2056 assert!(!txn.is_null());
2057
2058 let map = MapRef::from_raw_branch(map);
2059 let txn = txn.as_mut().unwrap();
2060 let txn = txn
2061 .as_mut()
2062 .expect("provided transaction was not writeable");
2063
2064 map.clear(txn);
2065}
2066
2067#[no_mangle]
2073pub unsafe extern "C" fn yxmlelem_tag(xml: *const Branch) -> *mut c_char {
2074 assert!(!xml.is_null());
2075 let xml = XmlElementRef::from_raw_branch(xml);
2076 if let Some(tag) = xml.try_tag() {
2077 CString::new(tag.deref()).unwrap().into_raw()
2078 } else {
2079 null_mut()
2080 }
2081}
2082
2083#[no_mangle]
2089pub unsafe extern "C" fn yxmlelem_string(
2090 xml: *const Branch,
2091 txn: *const Transaction,
2092) -> *mut c_char {
2093 assert!(!xml.is_null());
2094 assert!(!txn.is_null());
2095
2096 let txn = txn.as_ref().unwrap();
2097 let xml = XmlElementRef::from_raw_branch(xml);
2098
2099 let str = xml.get_string(txn);
2100 CString::new(str).unwrap().into_raw()
2101}
2102
2103#[no_mangle]
2109pub unsafe extern "C" fn yxmlelem_insert_attr(
2110 xml: *const Branch,
2111 txn: *mut Transaction,
2112 attr_name: *const c_char,
2113 attr_value: *const YInput,
2114) {
2115 assert!(!xml.is_null());
2116 assert!(!txn.is_null());
2117 assert!(!attr_name.is_null());
2118 assert!(!attr_value.is_null());
2119
2120 let xml = XmlElementRef::from_raw_branch(xml);
2121 let txn = txn.as_mut().unwrap();
2122 let txn = txn
2123 .as_mut()
2124 .expect("provided transaction was not writeable");
2125
2126 let key = CStr::from_ptr(attr_name).to_str().unwrap();
2127
2128 xml.insert_attribute(txn, key, attr_value.read());
2129}
2130
2131#[no_mangle]
2135pub unsafe extern "C" fn yxmlelem_remove_attr(
2136 xml: *const Branch,
2137 txn: *mut Transaction,
2138 attr_name: *const c_char,
2139) {
2140 assert!(!xml.is_null());
2141 assert!(!txn.is_null());
2142 assert!(!attr_name.is_null());
2143
2144 let xml = XmlElementRef::from_raw_branch(xml);
2145 let txn = txn.as_mut().unwrap();
2146 let txn = txn
2147 .as_mut()
2148 .expect("provided transaction was not writeable");
2149
2150 let key = CStr::from_ptr(attr_name).to_str().unwrap();
2151 xml.remove_attribute(txn, &key);
2152}
2153
2154#[no_mangle]
2160pub unsafe extern "C" fn yxmlelem_get_attr(
2161 xml: *const Branch,
2162 txn: *const Transaction,
2163 attr_name: *const c_char,
2164) -> *mut YOutput {
2165 assert!(!xml.is_null());
2166 assert!(!attr_name.is_null());
2167 assert!(!txn.is_null());
2168
2169 let xml = XmlElementRef::from_raw_branch(xml);
2170
2171 let key = CStr::from_ptr(attr_name).to_str().unwrap();
2172 let txn = txn.as_ref().unwrap();
2173 if let Some(value) = xml.get_attribute(txn, key) {
2174 let output = YOutput::from(value);
2175 Box::into_raw(Box::new(output))
2176 } else {
2177 std::ptr::null_mut()
2178 }
2179}
2180
2181#[no_mangle]
2186pub unsafe extern "C" fn yxmlelem_attr_iter(
2187 xml: *const Branch,
2188 txn: *const Transaction,
2189) -> *mut Attributes {
2190 assert!(!xml.is_null());
2191 assert!(!txn.is_null());
2192
2193 let xml = &XmlElementRef::from_raw_branch(xml) as *const XmlElementRef;
2194 let txn = txn.as_ref().unwrap();
2195 Box::into_raw(Box::new(Attributes(xml.as_ref().unwrap().attributes(txn))))
2196}
2197
2198#[no_mangle]
2203pub unsafe extern "C" fn yxmltext_attr_iter(
2204 xml: *const Branch,
2205 txn: *const Transaction,
2206) -> *mut Attributes {
2207 assert!(!xml.is_null());
2208 assert!(!txn.is_null());
2209
2210 let xml = &XmlTextRef::from_raw_branch(xml) as *const XmlTextRef;
2211 let txn = txn.as_ref().unwrap();
2212 Box::into_raw(Box::new(Attributes(xml.as_ref().unwrap().attributes(txn))))
2213}
2214
2215#[no_mangle]
2218pub unsafe extern "C" fn yxmlattr_iter_destroy(iterator: *mut Attributes) {
2219 if !iterator.is_null() {
2220 drop(Box::from_raw(iterator))
2221 }
2222}
2223
2224#[no_mangle]
2230pub unsafe extern "C" fn yxmlattr_iter_next(iterator: *mut Attributes) -> *mut YXmlAttr {
2231 assert!(!iterator.is_null());
2232
2233 let iter = iterator.as_mut().unwrap();
2234
2235 if let Some((name, value)) = iter.0.next() {
2236 Box::into_raw(Box::new(YXmlAttr {
2237 name: CString::new(name).unwrap().into_raw(),
2238 value: Box::into_raw(Box::new(YOutput::from(value))),
2239 }))
2240 } else {
2241 std::ptr::null_mut()
2242 }
2243}
2244
2245#[no_mangle]
2253pub unsafe extern "C" fn yxml_next_sibling(
2254 xml: *const Branch,
2255 txn: *const Transaction,
2256) -> *mut YOutput {
2257 assert!(!xml.is_null());
2258 assert!(!txn.is_null());
2259
2260 let xml = XmlElementRef::from_raw_branch(xml);
2261 let txn = txn.as_ref().unwrap();
2262
2263 let mut siblings = xml.siblings(txn);
2264 if let Some(next) = siblings.next() {
2265 match next {
2266 XmlOut::Element(v) => Box::into_raw(Box::new(YOutput::from(Out::YXmlElement(v)))),
2267 XmlOut::Text(v) => Box::into_raw(Box::new(YOutput::from(Out::YXmlText(v)))),
2268 XmlOut::Fragment(v) => Box::into_raw(Box::new(YOutput::from(Out::YXmlFragment(v)))),
2269 }
2270 } else {
2271 null_mut()
2272 }
2273}
2274
2275#[no_mangle]
2281pub unsafe extern "C" fn yxml_prev_sibling(
2282 xml: *const Branch,
2283 txn: *const Transaction,
2284) -> *mut YOutput {
2285 assert!(!xml.is_null());
2286 assert!(!txn.is_null());
2287
2288 let xml = XmlElementRef::from_raw_branch(xml);
2289 let txn = txn.as_ref().unwrap();
2290
2291 let mut siblings = xml.siblings(txn);
2292 if let Some(next) = siblings.next_back() {
2293 match next {
2294 XmlOut::Element(v) => Box::into_raw(Box::new(YOutput::from(Out::YXmlElement(v)))),
2295 XmlOut::Text(v) => Box::into_raw(Box::new(YOutput::from(Out::YXmlText(v)))),
2296 XmlOut::Fragment(v) => Box::into_raw(Box::new(YOutput::from(Out::YXmlFragment(v)))),
2297 }
2298 } else {
2299 null_mut()
2300 }
2301}
2302
2303#[no_mangle]
2306pub unsafe extern "C" fn yxmlelem_parent(xml: *const Branch) -> *mut Branch {
2307 assert!(!xml.is_null());
2308
2309 let xml = XmlElementRef::from_raw_branch(xml);
2310
2311 if let Some(parent) = xml.parent() {
2312 let branch = parent.as_ptr();
2313 branch.deref() as *const Branch as *mut Branch
2314 } else {
2315 std::ptr::null_mut()
2316 }
2317}
2318
2319#[no_mangle]
2322pub unsafe extern "C" fn yxmlelem_child_len(xml: *const Branch, txn: *const Transaction) -> u32 {
2323 assert!(!xml.is_null());
2324 assert!(!txn.is_null());
2325
2326 let txn = txn.as_ref().unwrap();
2327 let xml = XmlElementRef::from_raw_branch(xml);
2328
2329 xml.len(txn) as u32
2330}
2331
2332#[no_mangle]
2337pub unsafe extern "C" fn yxmlelem_first_child(xml: *const Branch) -> *mut YOutput {
2338 assert!(!xml.is_null());
2339
2340 let xml = XmlElementRef::from_raw_branch(xml);
2341
2342 if let Some(value) = xml.first_child() {
2343 match value {
2344 XmlOut::Element(v) => Box::into_raw(Box::new(YOutput::from(Out::YXmlElement(v)))),
2345 XmlOut::Text(v) => Box::into_raw(Box::new(YOutput::from(Out::YXmlText(v)))),
2346 XmlOut::Fragment(v) => Box::into_raw(Box::new(YOutput::from(Out::YXmlFragment(v)))),
2347 }
2348 } else {
2349 std::ptr::null_mut()
2350 }
2351}
2352
2353#[no_mangle]
2359pub unsafe extern "C" fn yxmlelem_tree_walker(
2360 xml: *const Branch,
2361 txn: *const Transaction,
2362) -> *mut TreeWalker {
2363 assert!(!xml.is_null());
2364 assert!(!txn.is_null());
2365
2366 let txn = txn.as_ref().unwrap();
2367 let xml = &XmlElementRef::from_raw_branch(xml) as *const XmlElementRef;
2368 Box::into_raw(Box::new(TreeWalker(xml.as_ref().unwrap().successors(txn))))
2369}
2370
2371#[no_mangle]
2373pub unsafe extern "C" fn yxmlelem_tree_walker_destroy(iter: *mut TreeWalker) {
2374 if !iter.is_null() {
2375 drop(Box::from_raw(iter))
2376 }
2377}
2378
2379#[no_mangle]
2384pub unsafe extern "C" fn yxmlelem_tree_walker_next(iterator: *mut TreeWalker) -> *mut YOutput {
2385 assert!(!iterator.is_null());
2386
2387 let iter = iterator.as_mut().unwrap();
2388
2389 if let Some(next) = iter.0.next() {
2390 match next {
2391 XmlOut::Element(v) => Box::into_raw(Box::new(YOutput::from(Out::YXmlElement(v)))),
2392 XmlOut::Text(v) => Box::into_raw(Box::new(YOutput::from(Out::YXmlText(v)))),
2393 XmlOut::Fragment(v) => Box::into_raw(Box::new(YOutput::from(Out::YXmlFragment(v)))),
2394 }
2395 } else {
2396 std::ptr::null_mut()
2397 }
2398}
2399
2400#[no_mangle]
2409pub unsafe extern "C" fn yxmlelem_insert_elem(
2410 xml: *const Branch,
2411 txn: *mut Transaction,
2412 index: u32,
2413 name: *const c_char,
2414) -> *mut Branch {
2415 assert!(!xml.is_null());
2416 assert!(!txn.is_null());
2417 assert!(!name.is_null());
2418
2419 let xml = XmlElementRef::from_raw_branch(xml);
2420 let txn = txn.as_mut().unwrap();
2421 let txn = txn
2422 .as_mut()
2423 .expect("provided transaction was not writeable");
2424
2425 let name = CStr::from_ptr(name).to_str().unwrap();
2426 xml.insert(txn, index as u32, XmlElementPrelim::empty(name))
2427 .into_raw_branch()
2428}
2429
2430#[no_mangle]
2436pub unsafe extern "C" fn yxmlelem_insert_text(
2437 xml: *const Branch,
2438 txn: *mut Transaction,
2439 index: u32,
2440) -> *mut Branch {
2441 assert!(!xml.is_null());
2442 assert!(!txn.is_null());
2443
2444 let xml = XmlElementRef::from_raw_branch(xml);
2445 let txn = txn.as_mut().unwrap();
2446 let txn = txn
2447 .as_mut()
2448 .expect("provided transaction was not writeable");
2449 xml.insert(txn, index as u32, XmlTextPrelim::new(""))
2450 .into_raw_branch()
2451}
2452
2453#[no_mangle]
2457pub unsafe extern "C" fn yxmlelem_remove_range(
2458 xml: *const Branch,
2459 txn: *mut Transaction,
2460 index: u32,
2461 len: u32,
2462) {
2463 assert!(!xml.is_null());
2464 assert!(!txn.is_null());
2465
2466 let xml = XmlElementRef::from_raw_branch(xml);
2467 let txn = txn.as_mut().unwrap();
2468 let txn = txn
2469 .as_mut()
2470 .expect("provided transaction was not writeable");
2471
2472 xml.remove_range(txn, index as u32, len as u32)
2473}
2474
2475#[no_mangle]
2481pub unsafe extern "C" fn yxmlelem_get(
2482 xml: *const Branch,
2483 txn: *const Transaction,
2484 index: u32,
2485) -> *const YOutput {
2486 assert!(!xml.is_null());
2487 assert!(!txn.is_null());
2488
2489 let xml = XmlElementRef::from_raw_branch(xml);
2490 let txn = txn.as_ref().unwrap();
2491
2492 if let Some(child) = xml.get(txn, index as u32) {
2493 match child {
2494 XmlOut::Element(v) => Box::into_raw(Box::new(YOutput::from(Out::YXmlElement(v)))),
2495 XmlOut::Text(v) => Box::into_raw(Box::new(YOutput::from(Out::YXmlText(v)))),
2496 XmlOut::Fragment(v) => Box::into_raw(Box::new(YOutput::from(Out::YXmlFragment(v)))),
2497 }
2498 } else {
2499 std::ptr::null()
2500 }
2501}
2502
2503#[no_mangle]
2506pub unsafe extern "C" fn yxmltext_len(txt: *const Branch, txn: *const Transaction) -> u32 {
2507 assert!(!txt.is_null());
2508 assert!(!txn.is_null());
2509
2510 let txn = txn.as_ref().unwrap();
2511 let txt = XmlTextRef::from_raw_branch(txt);
2512
2513 txt.len(txn) as u32
2514}
2515
2516#[no_mangle]
2520pub unsafe extern "C" fn yxmltext_string(
2521 txt: *const Branch,
2522 txn: *const Transaction,
2523) -> *mut c_char {
2524 assert!(!txt.is_null());
2525 assert!(!txn.is_null());
2526
2527 let txn = txn.as_ref().unwrap();
2528 let txt = XmlTextRef::from_raw_branch(txt);
2529
2530 let str = txt.get_string(txn);
2531 CString::new(str).unwrap().into_raw()
2532}
2533
2534#[no_mangle]
2545pub unsafe extern "C" fn yxmltext_insert(
2546 txt: *const Branch,
2547 txn: *mut Transaction,
2548 index: u32,
2549 str: *const c_char,
2550 attrs: *const YInput,
2551) {
2552 assert!(!txt.is_null());
2553 assert!(!txn.is_null());
2554 assert!(!str.is_null());
2555
2556 let txt = XmlTextRef::from_raw_branch(txt);
2557 let txn = txn.as_mut().unwrap();
2558 let txn = txn
2559 .as_mut()
2560 .expect("provided transaction was not writeable");
2561 let chunk = CStr::from_ptr(str).to_str().unwrap();
2562
2563 if attrs.is_null() {
2564 txt.insert(txn, index as u32, chunk)
2565 } else {
2566 if let Some(attrs) = map_attrs(attrs.read().into()) {
2567 txt.insert_with_attributes(txn, index as u32, chunk, attrs)
2568 } else {
2569 panic!("yxmltext_insert: passed attributes are not of map type")
2570 }
2571 }
2572}
2573
2574#[no_mangle]
2585pub unsafe extern "C" fn yxmltext_insert_embed(
2586 txt: *const Branch,
2587 txn: *mut Transaction,
2588 index: u32,
2589 content: *const YInput,
2590 attrs: *const YInput,
2591) {
2592 assert!(!txt.is_null());
2593 assert!(!txn.is_null());
2594 assert!(!content.is_null());
2595
2596 let txn = txn.as_mut().unwrap();
2597 let txn = txn
2598 .as_mut()
2599 .expect("provided transaction was not writeable");
2600 let txt = XmlTextRef::from_raw_branch(txt);
2601 let index = index as u32;
2602 let content = content.read();
2603 if attrs.is_null() {
2604 txt.insert_embed(txn, index, content);
2605 } else {
2606 if let Some(attrs) = map_attrs(attrs.read().into()) {
2607 txt.insert_embed_with_attributes(txn, index, content, attrs);
2608 } else {
2609 panic!("yxmltext_insert_embed: passed attributes are not of map type")
2610 }
2611 }
2612}
2613
2614#[no_mangle]
2617pub unsafe extern "C" fn yxmltext_format(
2618 txt: *const Branch,
2619 txn: *mut Transaction,
2620 index: u32,
2621 len: u32,
2622 attrs: *const YInput,
2623) {
2624 assert!(!txt.is_null());
2625 assert!(!txn.is_null());
2626 assert!(!attrs.is_null());
2627
2628 if let Some(attrs) = map_attrs(attrs.read().into()) {
2629 let txt = XmlTextRef::from_raw_branch(txt);
2630 let txn = txn.as_mut().unwrap();
2631 let txn = txn
2632 .as_mut()
2633 .expect("provided transaction was not writeable");
2634 let index = index as u32;
2635 let len = len as u32;
2636 txt.format(txn, index, len, attrs);
2637 } else {
2638 panic!("yxmltext_format: passed attributes are not of map type")
2639 }
2640}
2641
2642#[no_mangle]
2651pub unsafe extern "C" fn yxmltext_remove_range(
2652 txt: *const Branch,
2653 txn: *mut Transaction,
2654 idx: u32,
2655 len: u32,
2656) {
2657 assert!(!txt.is_null());
2658 assert!(!txn.is_null());
2659
2660 let txt = XmlTextRef::from_raw_branch(txt);
2661 let txn = txn.as_mut().unwrap();
2662 let txn = txn
2663 .as_mut()
2664 .expect("provided transaction was not writeable");
2665 txt.remove_range(txn, idx as u32, len as u32)
2666}
2667
2668#[no_mangle]
2674pub unsafe extern "C" fn yxmltext_insert_attr(
2675 txt: *const Branch,
2676 txn: *mut Transaction,
2677 attr_name: *const c_char,
2678 attr_value: *const YInput,
2679) {
2680 assert!(!txt.is_null());
2681 assert!(!txn.is_null());
2682 assert!(!attr_name.is_null());
2683 assert!(!attr_value.is_null());
2684
2685 let txt = XmlTextRef::from_raw_branch(txt);
2686 let txn = txn.as_mut().unwrap();
2687 let txn = txn
2688 .as_mut()
2689 .expect("provided transaction was not writeable");
2690
2691 let name = CStr::from_ptr(attr_name).to_str().unwrap();
2692
2693 txt.insert_attribute(txn, name, attr_value.read());
2694}
2695
2696#[no_mangle]
2700pub unsafe extern "C" fn yxmltext_remove_attr(
2701 txt: *const Branch,
2702 txn: *mut Transaction,
2703 attr_name: *const c_char,
2704) {
2705 assert!(!txt.is_null());
2706 assert!(!txn.is_null());
2707 assert!(!attr_name.is_null());
2708
2709 let txt = XmlTextRef::from_raw_branch(txt);
2710 let txn = txn.as_mut().unwrap();
2711 let txn = txn
2712 .as_mut()
2713 .expect("provided transaction was not writeable");
2714 let name = CStr::from_ptr(attr_name).to_str().unwrap();
2715
2716 txt.remove_attribute(txn, &name)
2717}
2718
2719#[no_mangle]
2725pub unsafe extern "C" fn yxmltext_get_attr(
2726 txt: *const Branch,
2727 txn: *const Transaction,
2728 attr_name: *const c_char,
2729) -> *mut YOutput {
2730 assert!(!txt.is_null());
2731 assert!(!attr_name.is_null());
2732 assert!(!txn.is_null());
2733
2734 let txn = txn.as_ref().unwrap();
2735 let txt = XmlTextRef::from_raw_branch(txt);
2736 let name = CStr::from_ptr(attr_name).to_str().unwrap();
2737
2738 if let Some(value) = txt.get_attribute(txn, name) {
2739 let output = YOutput::from(value);
2740 Box::into_raw(Box::new(output))
2741 } else {
2742 std::ptr::null_mut()
2743 }
2744}
2745
2746#[no_mangle]
2752pub unsafe extern "C" fn ytext_chunks(
2753 txt: *const Branch,
2754 txn: *const Transaction,
2755 chunks_len: *mut u32,
2756) -> *mut YChunk {
2757 assert!(!txt.is_null());
2758 assert!(!txn.is_null());
2759
2760 let txt = TextRef::from_raw_branch(txt);
2761 let txn = txn.as_ref().unwrap();
2762
2763 let diffs = txt.diff(txn, YChange::identity);
2764 let chunks: Vec<_> = diffs.into_iter().map(YChunk::from).collect();
2765 let out = chunks.into_boxed_slice();
2766 *chunks_len = out.len() as u32;
2767 Box::into_raw(out) as *mut _
2768}
2769
2770#[no_mangle]
2772pub unsafe extern "C" fn ychunks_destroy(chunks: *mut YChunk, len: u32) {
2773 drop(Vec::from_raw_parts(chunks, len as usize, len as usize));
2774}
2775
2776pub const YCHANGE_ADD: i8 = 1;
2777pub const YCHANGE_RETAIN: i8 = 0;
2778pub const YCHANGE_REMOVE: i8 = -1;
2779
2780#[repr(C)]
2782pub struct YChunk {
2783 pub data: YOutput,
2786 pub fmt_len: u32,
2788 pub fmt: *mut YMapEntry,
2790}
2791
2792impl From<Diff<YChange>> for YChunk {
2793 fn from(diff: Diff<YChange>) -> Self {
2794 let data = YOutput::from(diff.insert);
2795 let mut fmt_len = 0;
2796 let fmt = if let Some(attrs) = diff.attributes {
2797 fmt_len = attrs.len() as u32;
2798 let mut fmt = Vec::with_capacity(attrs.len());
2799 for (k, v) in attrs.into_iter() {
2800 let output = YOutput::from(&v); let e = YMapEntry::new(k.as_ref(), Box::new(output));
2802 fmt.push(e);
2803 }
2804 Box::into_raw(fmt.into_boxed_slice()) as *mut _
2805 } else {
2806 null_mut()
2807 };
2808 YChunk { data, fmt_len, fmt }
2809 }
2810}
2811
2812impl Drop for YChunk {
2813 fn drop(&mut self) {
2814 if !self.fmt.is_null() {
2815 drop(unsafe {
2816 Vec::from_raw_parts(self.fmt, self.fmt_len as usize, self.fmt_len as usize)
2817 });
2818 }
2819 }
2820}
2821
2822#[repr(C)]
2829pub struct YInput {
2830 pub tag: i8,
2847
2848 pub len: u32,
2857
2858 value: YInputContent,
2860}
2861
2862impl YInput {
2863 fn into(self) -> Any {
2864 let tag = self.tag;
2865 unsafe {
2866 match tag {
2867 Y_JSON_STR => {
2868 let str = CStr::from_ptr(self.value.str).to_str().unwrap().into();
2869 Any::String(str)
2870 }
2871 Y_JSON => {
2872 let json_str = CStr::from_ptr(self.value.str).to_str().unwrap();
2873 serde_json::from_str(json_str).unwrap()
2874 }
2875 Y_JSON_NULL => Any::Null,
2876 Y_JSON_UNDEF => Any::Undefined,
2877 Y_JSON_INT => Any::Number(Number::Int(self.value.integer)),
2878 Y_JSON_NUM => Any::Number(Number::Float(self.value.num)),
2879 Y_JSON_BOOL => Any::Bool(if self.value.flag == 0 { false } else { true }),
2880 Y_JSON_BUF => Any::from(std::slice::from_raw_parts(
2881 self.value.buf as *mut u8,
2882 self.len as usize,
2883 )),
2884 Y_JSON_ARR => {
2885 let ptr = self.value.values;
2886 let mut dst: Vec<Any> = Vec::with_capacity(self.len as usize);
2887 let mut i = 0;
2888 while i < self.len as isize {
2889 let value = ptr.offset(i).read();
2890 let any = value.into();
2891 dst.push(any);
2892 i += 1;
2893 }
2894 Any::from(dst)
2895 }
2896 Y_JSON_MAP => {
2897 let mut dst = HashMap::with_capacity(self.len as usize);
2898 let keys = self.value.map.keys;
2899 let values = self.value.map.values;
2900 let mut i = 0;
2901 while i < self.len as isize {
2902 let key = CStr::from_ptr(keys.offset(i).read())
2903 .to_str()
2904 .unwrap()
2905 .to_owned();
2906 let value = values.offset(i).read().into();
2907 dst.insert(key, value);
2908 i += 1;
2909 }
2910 Any::from(dst)
2911 }
2912 Y_DOC => Any::Undefined,
2913 other => panic!("Cannot convert input - unknown tag: {}", other),
2914 }
2915 }
2916 }
2917}
2918
2919impl Into<EmbedPrelim<YInput>> for YInput {
2920 fn into(self) -> EmbedPrelim<YInput> {
2921 if self.tag <= 0 {
2922 EmbedPrelim::Primitive(self.into())
2923 } else {
2924 EmbedPrelim::Shared(self)
2925 }
2926 }
2927}
2928
2929#[repr(C)]
2930union YInputContent {
2931 flag: u8,
2932 num: f64,
2933 integer: i64,
2934 str: *mut c_char,
2935 buf: *mut c_char,
2936 values: *mut YInput,
2937 map: ManuallyDrop<YMapInputData>,
2938 doc: *mut Doc,
2939 weak: *const Weak,
2940}
2941
2942#[repr(C)]
2943struct YMapInputData {
2944 keys: *mut *mut c_char,
2945 values: *mut YInput,
2946}
2947
2948impl Drop for YInput {
2949 fn drop(&mut self) {}
2950}
2951
2952impl Prelim for YInput {
2953 type Return = Unused;
2954
2955 fn into_content<'doc>(self, _: &mut yrs::TransactionMut<'doc>) -> (ItemContent, Option<Self>) {
2956 unsafe {
2957 if self.tag <= 0 {
2958 (ItemContent::Any(vec![self.into()]), None)
2959 } else if self.tag == Y_DOC {
2960 let doc = self.value.doc.as_ref().unwrap();
2961 (ItemContent::Doc(None, doc.clone()), None)
2962 } else {
2963 let type_ref = match self.tag {
2964 Y_MAP => TypeRef::Map,
2965 Y_ARRAY => TypeRef::Array,
2966 Y_TEXT => TypeRef::Text,
2967 Y_XML_TEXT => TypeRef::XmlText,
2968 Y_XML_ELEM => {
2969 let name: Arc<str> =
2970 CStr::from_ptr(self.value.str).to_str().unwrap().into();
2971 TypeRef::XmlElement(name)
2972 }
2973 Y_WEAK_LINK => {
2974 let source = Arc::from_raw(self.value.weak);
2975 TypeRef::WeakLink(source)
2976 }
2977 Y_XML_FRAG => TypeRef::XmlFragment,
2978 other => panic!("unrecognized YInput tag: {}", other),
2979 };
2980 let inner = Branch::new(type_ref);
2981 (ItemContent::Type(inner), Some(self))
2982 }
2983 }
2984 }
2985
2986 fn integrate(self, txn: &mut yrs::TransactionMut, inner_ref: BranchPtr) {
2987 unsafe {
2988 match self.tag {
2989 Y_MAP => {
2990 let map = MapRef::from(inner_ref);
2991 let keys = self.value.map.keys;
2992 let values = self.value.map.values;
2993 let mut i = 0;
2994 while i < self.len as isize {
2995 let key = CStr::from_ptr(keys.offset(i).read())
2996 .to_str()
2997 .unwrap()
2998 .to_owned();
2999 let value = values.offset(i).read();
3000 map.insert(txn, key, value);
3001 i += 1;
3002 }
3003 }
3004 Y_ARRAY => {
3005 let array = ArrayRef::from(inner_ref);
3006 let ptr = self.value.values;
3007 let len = self.len as isize;
3008 let mut i = 0;
3009 while i < len {
3010 let value = ptr.offset(i).read();
3011 array.push_back(txn, value);
3012 i += 1;
3013 }
3014 }
3015 Y_TEXT => {
3016 let text = TextRef::from(inner_ref);
3017 let init = CStr::from_ptr(self.value.str).to_str().unwrap();
3018 text.push(txn, init);
3019 }
3020 Y_XML_TEXT => {
3021 let text = XmlTextRef::from(inner_ref);
3022 let init = CStr::from_ptr(self.value.str).to_str().unwrap();
3023 text.push(txn, init);
3024 }
3025 _ => { }
3026 }
3027 }
3028 }
3029}
3030
3031#[repr(C)]
3037pub struct YOutput {
3038 pub tag: i8,
3056
3057 pub len: u32,
3065
3066 value: YOutputContent,
3068}
3069
3070impl YOutput {
3071 #[inline]
3072 unsafe fn null() -> YOutput {
3073 YOutput {
3074 tag: Y_JSON_NULL,
3075 len: 0,
3076 value: MaybeUninit::uninit().assume_init(),
3077 }
3078 }
3079
3080 #[inline]
3081 unsafe fn undefined() -> YOutput {
3082 YOutput {
3083 tag: Y_JSON_UNDEF,
3084 len: 0,
3085 value: MaybeUninit::uninit().assume_init(),
3086 }
3087 }
3088}
3089
3090impl std::fmt::Display for YOutput {
3091 fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
3092 let tag = self.tag;
3093 unsafe {
3094 if tag == Y_JSON_INT {
3095 write!(f, "{}", self.value.integer)
3096 } else if tag == Y_JSON_NUM {
3097 write!(f, "{}", self.value.num)
3098 } else if tag == Y_JSON_BOOL {
3099 write!(
3100 f,
3101 "{}",
3102 if self.value.flag == 0 {
3103 "false"
3104 } else {
3105 "true"
3106 }
3107 )
3108 } else if tag == Y_JSON_UNDEF {
3109 write!(f, "undefined")
3110 } else if tag == Y_JSON_NULL {
3111 write!(f, "null")
3112 } else if tag == Y_JSON_STR {
3113 write!(f, "{}", CString::from_raw(self.value.str).to_str().unwrap())
3114 } else if tag == Y_MAP {
3115 write!(f, "YMap")
3116 } else if tag == Y_ARRAY {
3117 write!(f, "YArray")
3118 } else if tag == Y_JSON_ARR {
3119 write!(f, "[")?;
3120 let slice = std::slice::from_raw_parts(self.value.array, self.len as usize);
3121 for o in slice {
3122 write!(f, ", {}", o)?;
3123 }
3124 write!(f, "]")
3125 } else if tag == Y_JSON_MAP {
3126 write!(f, "{{")?;
3127 let slice = std::slice::from_raw_parts(self.value.map, self.len as usize);
3128 for e in slice {
3129 let key = CStr::from_ptr(e.key).to_str().unwrap();
3130 let value = e.value.as_ref().unwrap();
3131 write!(f, ", '{}' => {}", key, value)?;
3132 }
3133 write!(f, "}}")
3134 } else if tag == Y_TEXT {
3135 write!(f, "YText")
3136 } else if tag == Y_XML_TEXT {
3137 write!(f, "YXmlText")
3138 } else if tag == Y_XML_ELEM {
3139 write!(f, "YXmlElement",)
3140 } else if tag == Y_JSON_BUF {
3141 write!(f, "YBinary(len: {})", self.len)
3142 } else {
3143 Ok(())
3144 }
3145 }
3146 }
3147}
3148
3149impl Drop for YOutput {
3150 fn drop(&mut self) {
3151 let tag = self.tag;
3152 unsafe {
3153 match tag {
3154 Y_JSON_STR => drop(CString::from_raw(self.value.str)),
3155 Y_JSON_ARR => drop(Vec::from_raw_parts(
3156 self.value.array,
3157 self.len as usize,
3158 self.len as usize,
3159 )),
3160 Y_JSON_MAP => drop(Vec::from_raw_parts(
3161 self.value.map,
3162 self.len as usize,
3163 self.len as usize,
3164 )),
3165 Y_JSON_BUF => drop(Vec::from_raw_parts(
3166 self.value.buf as *mut u8,
3168 self.len as usize,
3169 self.len as usize,
3170 )),
3171 Y_DOC => drop(Box::from_raw(self.value.y_doc)),
3172 _ => { }
3173 }
3174 }
3175 }
3176}
3177
3178impl From<Out> for YOutput {
3179 fn from(v: Out) -> Self {
3180 match v {
3181 Out::Any(v) => Self::from(v),
3182 Out::YText(v) => Self::from(v),
3183 Out::YArray(v) => Self::from(v),
3184 Out::YMap(v) => Self::from(v),
3185 Out::YXmlElement(v) => Self::from(v),
3186 Out::YXmlFragment(v) => Self::from(v),
3187 Out::YXmlText(v) => Self::from(v),
3188 Out::YDoc(v) => Self::from(v),
3189 Out::YWeakLink(v) => Self::from(v),
3190 Out::UndefinedRef(v) => Self::from(v),
3191 }
3192 }
3193}
3194
3195impl From<bool> for YOutput {
3196 #[inline]
3197 fn from(value: bool) -> Self {
3198 YOutput {
3199 tag: Y_JSON_BOOL,
3200 len: 1,
3201 value: YOutputContent {
3202 flag: if value { Y_TRUE } else { Y_FALSE },
3203 },
3204 }
3205 }
3206}
3207
3208impl From<f64> for YOutput {
3209 #[inline]
3210 fn from(value: f64) -> Self {
3211 YOutput {
3212 tag: Y_JSON_NUM,
3213 len: 1,
3214 value: YOutputContent { num: value },
3215 }
3216 }
3217}
3218
3219impl From<Number> for YOutput {
3220 #[inline]
3221 fn from(value: Number) -> Self {
3222 match value {
3223 Number::Int(value) => YOutput::from(value),
3224 Number::Float(value) => YOutput::from(value),
3225 }
3226 }
3227}
3228
3229impl From<i64> for YOutput {
3230 #[inline]
3231 fn from(value: i64) -> Self {
3232 YOutput {
3233 tag: Y_JSON_INT,
3234 len: 1,
3235 value: YOutputContent { integer: value },
3236 }
3237 }
3238}
3239
3240impl<'a> From<&'a str> for YOutput {
3241 fn from(value: &'a str) -> Self {
3242 YOutput {
3243 tag: Y_JSON_STR,
3244 len: value.len() as u32,
3245 value: YOutputContent {
3246 str: CString::new(value).unwrap().into_raw(),
3247 },
3248 }
3249 }
3250}
3251
3252impl<'a> From<&'a [u8]> for YOutput {
3253 fn from(value: &'a [u8]) -> Self {
3254 let value: Box<[u8]> = value.into();
3255 YOutput {
3256 tag: Y_JSON_BUF,
3257 len: value.len() as u32,
3258 value: YOutputContent {
3259 buf: Box::into_raw(value) as *const u8 as *mut c_char,
3260 },
3261 }
3262 }
3263}
3264
3265impl<'a> From<&'a [Any]> for YOutput {
3266 fn from(values: &'a [Any]) -> Self {
3267 let len = values.len() as u32;
3268 let mut array = Vec::with_capacity(values.len());
3269 for v in values.iter() {
3270 let output = YOutput::from(v);
3271 array.push(output);
3272 }
3273 let ptr = array.as_mut_ptr();
3274 forget(array);
3275 YOutput {
3276 tag: Y_JSON_ARR,
3277 len,
3278 value: YOutputContent { array: ptr },
3279 }
3280 }
3281}
3282
3283impl<'a> From<&'a HashMap<String, Any>> for YOutput {
3284 fn from(value: &'a HashMap<String, Any>) -> Self {
3285 let len = value.len() as u32;
3286 let mut array = Vec::with_capacity(len as usize);
3287 for (k, v) in value.iter() {
3288 let entry = YMapEntry::new(k.as_str(), Box::new(YOutput::from(v)));
3289 array.push(entry);
3290 }
3291 let ptr = array.as_mut_ptr();
3292 forget(array);
3293 YOutput {
3294 tag: Y_JSON_MAP,
3295 len,
3296 value: YOutputContent { map: ptr },
3297 }
3298 }
3299}
3300
3301impl<'a> From<&'a Any> for YOutput {
3302 fn from(v: &'a Any) -> Self {
3303 unsafe {
3304 match v {
3305 Any::Null => YOutput::null(),
3306 Any::Undefined => YOutput::undefined(),
3307 Any::Bool(v) => YOutput::from(*v),
3308 Any::Number(v) => YOutput::from(*v),
3309 Any::String(v) => YOutput::from(v.as_ref()),
3310 Any::Buffer(v) => YOutput::from(v.as_ref()),
3311 Any::Array(v) => YOutput::from(v.as_ref()),
3312 Any::Map(v) => YOutput::from(v.as_ref()),
3313 }
3314 }
3315 }
3316}
3317
3318impl From<Any> for YOutput {
3319 fn from(v: Any) -> Self {
3320 unsafe {
3321 match v {
3322 Any::Null => YOutput::null(),
3323 Any::Undefined => YOutput::undefined(),
3324 Any::Bool(v) => YOutput::from(v),
3325 Any::Number(v) => YOutput::from(v),
3326 Any::String(v) => YOutput::from(v.as_ref()),
3327 Any::Buffer(v) => YOutput::from(v.as_ref()),
3328 Any::Array(v) => YOutput::from(v.as_ref()),
3329 Any::Map(v) => YOutput::from(v.as_ref()),
3330 }
3331 }
3332 }
3333}
3334
3335impl From<TextRef> for YOutput {
3336 fn from(v: TextRef) -> Self {
3337 YOutput {
3338 tag: Y_TEXT,
3339 len: 1,
3340 value: YOutputContent {
3341 y_type: v.into_raw_branch(),
3342 },
3343 }
3344 }
3345}
3346
3347impl From<ArrayRef> for YOutput {
3348 fn from(v: ArrayRef) -> Self {
3349 YOutput {
3350 tag: Y_ARRAY,
3351 len: 1,
3352 value: YOutputContent {
3353 y_type: v.into_raw_branch(),
3354 },
3355 }
3356 }
3357}
3358
3359impl From<WeakRef<BranchPtr>> for YOutput {
3360 fn from(v: WeakRef<BranchPtr>) -> Self {
3361 YOutput {
3362 tag: Y_WEAK_LINK,
3363 len: 1,
3364 value: YOutputContent {
3365 y_type: v.into_raw_branch(),
3366 },
3367 }
3368 }
3369}
3370
3371impl From<MapRef> for YOutput {
3372 fn from(v: MapRef) -> Self {
3373 YOutput {
3374 tag: Y_MAP,
3375 len: 1,
3376 value: YOutputContent {
3377 y_type: v.into_raw_branch(),
3378 },
3379 }
3380 }
3381}
3382
3383impl From<BranchPtr> for YOutput {
3384 fn from(v: BranchPtr) -> Self {
3385 let branch_ref = v.as_ref();
3386 YOutput {
3387 tag: Y_UNDEFINED,
3388 len: 1,
3389 value: YOutputContent {
3390 y_type: branch_ref as *const Branch as *mut Branch,
3391 },
3392 }
3393 }
3394}
3395
3396impl From<XmlElementRef> for YOutput {
3397 fn from(v: XmlElementRef) -> Self {
3398 YOutput {
3399 tag: Y_XML_ELEM,
3400 len: 1,
3401 value: YOutputContent {
3402 y_type: v.into_raw_branch(),
3403 },
3404 }
3405 }
3406}
3407
3408impl From<XmlTextRef> for YOutput {
3409 fn from(v: XmlTextRef) -> Self {
3410 YOutput {
3411 tag: Y_XML_TEXT,
3412 len: 1,
3413 value: YOutputContent {
3414 y_type: v.into_raw_branch(),
3415 },
3416 }
3417 }
3418}
3419
3420impl From<XmlFragmentRef> for YOutput {
3421 fn from(v: XmlFragmentRef) -> Self {
3422 YOutput {
3423 tag: Y_XML_FRAG,
3424 len: 1,
3425 value: YOutputContent {
3426 y_type: v.into_raw_branch(),
3427 },
3428 }
3429 }
3430}
3431
3432impl From<Doc> for YOutput {
3433 fn from(v: Doc) -> Self {
3434 YOutput {
3435 tag: Y_DOC,
3436 len: 1,
3437 value: YOutputContent {
3438 y_doc: Box::into_raw(Box::new(v.clone())),
3439 },
3440 }
3441 }
3442}
3443
3444#[repr(C)]
3445union YOutputContent {
3446 flag: u8,
3447 num: f64,
3448 integer: i64,
3449 str: *mut c_char,
3450 buf: *const c_char,
3451 array: *mut YOutput,
3452 map: *mut YMapEntry,
3453 y_type: *mut Branch,
3454 y_doc: *mut Doc,
3455}
3456
3457#[no_mangle]
3459pub unsafe extern "C" fn youtput_destroy(val: *mut YOutput) {
3460 if !val.is_null() {
3461 drop(Box::from_raw(val))
3462 }
3463}
3464
3465#[no_mangle]
3468pub unsafe extern "C" fn yinput_null() -> YInput {
3469 YInput {
3470 tag: Y_JSON_NULL,
3471 len: 0,
3472 value: MaybeUninit::uninit().assume_init(),
3473 }
3474}
3475
3476#[no_mangle]
3479pub unsafe extern "C" fn yinput_undefined() -> YInput {
3480 YInput {
3481 tag: Y_JSON_UNDEF,
3482 len: 0,
3483 value: MaybeUninit::uninit().assume_init(),
3484 }
3485}
3486
3487#[no_mangle]
3490pub unsafe extern "C" fn yinput_bool(flag: u8) -> YInput {
3491 YInput {
3492 tag: Y_JSON_BOOL,
3493 len: 1,
3494 value: YInputContent { flag },
3495 }
3496}
3497
3498#[no_mangle]
3501pub unsafe extern "C" fn yinput_float(num: f64) -> YInput {
3502 YInput {
3503 tag: Y_JSON_NUM,
3504 len: 1,
3505 value: YInputContent { num },
3506 }
3507}
3508
3509#[no_mangle]
3512pub unsafe extern "C" fn yinput_long(integer: i64) -> YInput {
3513 YInput {
3514 tag: Y_JSON_INT,
3515 len: 1,
3516 value: YInputContent { integer },
3517 }
3518}
3519
3520#[no_mangle]
3525pub unsafe extern "C" fn yinput_string(str: *const c_char) -> YInput {
3526 YInput {
3527 tag: Y_JSON_STR,
3528 len: 1,
3529 value: YInputContent {
3530 str: str as *mut c_char,
3531 },
3532 }
3533}
3534
3535#[no_mangle]
3541pub unsafe extern "C" fn yinput_json(str: *const c_char) -> YInput {
3542 YInput {
3543 tag: Y_JSON,
3544 len: 1,
3545 value: YInputContent {
3546 str: str as *mut c_char,
3547 },
3548 }
3549}
3550
3551#[no_mangle]
3555pub unsafe extern "C" fn yinput_binary(buf: *const c_char, len: u32) -> YInput {
3556 YInput {
3557 tag: Y_JSON_BUF,
3558 len,
3559 value: YInputContent {
3560 buf: buf as *mut c_char,
3561 },
3562 }
3563}
3564
3565#[no_mangle]
3569pub unsafe extern "C" fn yinput_json_array(values: *mut YInput, len: u32) -> YInput {
3570 YInput {
3571 tag: Y_JSON_ARR,
3572 len,
3573 value: YInputContent { values },
3574 }
3575}
3576
3577#[no_mangle]
3584pub unsafe extern "C" fn yinput_json_map(
3585 keys: *mut *mut c_char,
3586 values: *mut YInput,
3587 len: u32,
3588) -> YInput {
3589 YInput {
3590 tag: Y_JSON_MAP,
3591 len,
3592 value: YInputContent {
3593 map: ManuallyDrop::new(YMapInputData { keys, values }),
3594 },
3595 }
3596}
3597
3598#[no_mangle]
3603pub unsafe extern "C" fn yinput_yarray(values: *mut YInput, len: u32) -> YInput {
3604 YInput {
3605 tag: Y_ARRAY,
3606 len,
3607 value: YInputContent { values },
3608 }
3609}
3610
3611#[no_mangle]
3618pub unsafe extern "C" fn yinput_ymap(
3619 keys: *mut *mut c_char,
3620 values: *mut YInput,
3621 len: u32,
3622) -> YInput {
3623 YInput {
3624 tag: Y_MAP,
3625 len,
3626 value: YInputContent {
3627 map: ManuallyDrop::new(YMapInputData { keys, values }),
3628 },
3629 }
3630}
3631
3632#[no_mangle]
3638pub unsafe extern "C" fn yinput_ytext(str: *mut c_char) -> YInput {
3639 YInput {
3640 tag: Y_TEXT,
3641 len: 1,
3642 value: YInputContent { str },
3643 }
3644}
3645
3646#[no_mangle]
3652pub unsafe extern "C" fn yinput_yxmlelem(name: *mut c_char) -> YInput {
3653 YInput {
3654 tag: Y_XML_ELEM,
3655 len: 1,
3656 value: YInputContent { str: name },
3657 }
3658}
3659
3660#[no_mangle]
3666pub unsafe extern "C" fn yinput_yxmltext(str: *mut c_char) -> YInput {
3667 YInput {
3668 tag: Y_XML_TEXT,
3669 len: 1,
3670 value: YInputContent { str },
3671 }
3672}
3673
3674#[no_mangle]
3679pub unsafe extern "C" fn yinput_ydoc(doc: *mut Doc) -> YInput {
3680 YInput {
3681 tag: Y_DOC,
3682 len: 1,
3683 value: YInputContent { doc },
3684 }
3685}
3686
3687#[no_mangle]
3690pub unsafe extern "C" fn yinput_weak(weak: *const Weak) -> YInput {
3691 YInput {
3692 tag: Y_WEAK_LINK,
3693 len: 1,
3694 value: YInputContent { weak },
3695 }
3696}
3697
3698#[no_mangle]
3701pub unsafe extern "C" fn youtput_read_ydoc(val: *const YOutput) -> *mut Doc {
3702 let v = val.as_ref().unwrap();
3703 if v.tag == Y_DOC {
3704 v.value.y_doc
3705 } else {
3706 std::ptr::null_mut()
3707 }
3708}
3709
3710#[no_mangle]
3714pub unsafe extern "C" fn youtput_read_bool(val: *const YOutput) -> *const u8 {
3715 let v = val.as_ref().unwrap();
3716 if v.tag == Y_JSON_BOOL {
3717 &v.value.flag
3718 } else {
3719 std::ptr::null()
3720 }
3721}
3722
3723#[no_mangle]
3728pub unsafe extern "C" fn youtput_read_float(val: *const YOutput) -> *const f64 {
3729 let v = val.as_ref().unwrap();
3730 if v.tag == Y_JSON_NUM {
3731 &v.value.num
3732 } else {
3733 std::ptr::null()
3734 }
3735}
3736
3737#[no_mangle]
3742pub unsafe extern "C" fn youtput_read_long(val: *const YOutput) -> *const i64 {
3743 let v = val.as_ref().unwrap();
3744 if v.tag == Y_JSON_INT {
3745 &v.value.integer
3746 } else {
3747 std::ptr::null()
3748 }
3749}
3750
3751#[no_mangle]
3758pub unsafe extern "C" fn youtput_read_string(val: *const YOutput) -> *mut c_char {
3759 let v = val.as_ref().unwrap();
3760 if v.tag == Y_JSON_STR {
3761 v.value.str
3762 } else {
3763 std::ptr::null_mut()
3764 }
3765}
3766
3767#[no_mangle]
3774pub unsafe extern "C" fn youtput_read_binary(val: *const YOutput) -> *const c_char {
3775 let v = val.as_ref().unwrap();
3776 if v.tag == Y_JSON_BUF {
3777 v.value.buf
3778 } else {
3779 std::ptr::null()
3780 }
3781}
3782
3783#[no_mangle]
3790pub unsafe extern "C" fn youtput_read_json_array(val: *const YOutput) -> *mut YOutput {
3791 let v = val.as_ref().unwrap();
3792 if v.tag == Y_JSON_ARR {
3793 v.value.array
3794 } else {
3795 std::ptr::null_mut()
3796 }
3797}
3798
3799#[no_mangle]
3806pub unsafe extern "C" fn youtput_read_json_map(val: *const YOutput) -> *mut YMapEntry {
3807 let v = val.as_ref().unwrap();
3808 if v.tag == Y_JSON_MAP {
3809 v.value.map
3810 } else {
3811 std::ptr::null_mut()
3812 }
3813}
3814
3815#[no_mangle]
3821pub unsafe extern "C" fn youtput_read_yarray(val: *const YOutput) -> *mut Branch {
3822 let v = val.as_ref().unwrap();
3823 if v.tag == Y_ARRAY {
3824 v.value.y_type
3825 } else {
3826 std::ptr::null_mut()
3827 }
3828}
3829
3830#[no_mangle]
3836pub unsafe extern "C" fn youtput_read_yxmlelem(val: *const YOutput) -> *mut Branch {
3837 let v = val.as_ref().unwrap();
3838 if v.tag == Y_XML_ELEM {
3839 v.value.y_type
3840 } else {
3841 std::ptr::null_mut()
3842 }
3843}
3844
3845#[no_mangle]
3851pub unsafe extern "C" fn youtput_read_ymap(val: *const YOutput) -> *mut Branch {
3852 let v = val.as_ref().unwrap();
3853 if v.tag == Y_MAP {
3854 v.value.y_type
3855 } else {
3856 std::ptr::null_mut()
3857 }
3858}
3859
3860#[no_mangle]
3866pub unsafe extern "C" fn youtput_read_ytext(val: *const YOutput) -> *mut Branch {
3867 let v = val.as_ref().unwrap();
3868 if v.tag == Y_TEXT {
3869 v.value.y_type
3870 } else {
3871 std::ptr::null_mut()
3872 }
3873}
3874
3875#[no_mangle]
3881pub unsafe extern "C" fn youtput_read_yxmltext(val: *const YOutput) -> *mut Branch {
3882 let v = val.as_ref().unwrap();
3883 if v.tag == Y_XML_TEXT {
3884 v.value.y_type
3885 } else {
3886 std::ptr::null_mut()
3887 }
3888}
3889
3890#[no_mangle]
3896pub unsafe extern "C" fn youtput_read_yweak(val: *const YOutput) -> *mut Branch {
3897 let v = val.as_ref().unwrap();
3898 if v.tag == Y_WEAK_LINK {
3899 v.value.y_type
3900 } else {
3901 std::ptr::null_mut()
3902 }
3903}
3904
3905#[no_mangle]
3908pub unsafe extern "C" fn yunobserve(branch: *const Branch, key_len: u32, key: *const c_char) -> u8 {
3909 assert!(!branch.is_null());
3910 let key = origin(key_len, key);
3911 let branch = (branch as *mut Branch).as_mut().unwrap();
3912 branch.unobserve(&key) as u8
3913}
3914
3915#[no_mangle]
3918pub unsafe extern "C" fn yunobserve_deep(
3919 branch: *const Branch,
3920 key_len: u32,
3921 key: *const c_char,
3922) -> u8 {
3923 assert!(!branch.is_null());
3924 let key = origin(key_len, key);
3925 let branch = (branch as *mut Branch).as_mut().unwrap();
3926 branch.unobserve_deep(&key) as u8
3927}
3928
3929#[no_mangle]
3933pub unsafe extern "C" fn ytext_observe(
3934 txt: *const Branch,
3935 key_len: u32,
3936 key: *const c_char,
3937 state: *mut c_void,
3938 cb: extern "C" fn(*mut c_void, *const YTextEvent),
3939) {
3940 assert!(!txt.is_null());
3941 let state = CallbackState::new(state);
3942
3943 let txt = TextRef::from_raw_branch(txt);
3944 txt.observe(origin(key_len, key), move |txn, e| {
3945 let e = YTextEvent::new(e, txn);
3946 cb(state.0, &e as *const YTextEvent);
3947 });
3948}
3949
3950#[no_mangle]
3954pub unsafe extern "C" fn ymap_observe(
3955 map: *const Branch,
3956 key_len: u32,
3957 key: *const c_char,
3958 state: *mut c_void,
3959 cb: extern "C" fn(*mut c_void, *const YMapEvent),
3960) {
3961 assert!(!map.is_null());
3962 let state = CallbackState::new(state);
3963
3964 let map = MapRef::from_raw_branch(map);
3965 map.observe(origin(key_len, key), move |txn, e| {
3966 let e = YMapEvent::new(e, txn);
3967 cb(state.0, &e as *const YMapEvent);
3968 });
3969}
3970
3971#[no_mangle]
3975pub unsafe extern "C" fn yarray_observe(
3976 array: *const Branch,
3977 key_len: u32,
3978 key: *const c_char,
3979 state: *mut c_void,
3980 cb: extern "C" fn(*mut c_void, *const YArrayEvent),
3981) {
3982 assert!(!array.is_null());
3983 let state = CallbackState::new(state);
3984
3985 let array = ArrayRef::from_raw_branch(array);
3986 array.observe(origin(key_len, key), move |txn, e| {
3987 let e = YArrayEvent::new(e, txn);
3988 cb(state.0, &e as *const YArrayEvent);
3989 });
3990}
3991
3992#[no_mangle]
3996pub unsafe extern "C" fn yxmlelem_observe(
3997 xml: *const Branch,
3998 key_len: u32,
3999 key: *const c_char,
4000 state: *mut c_void,
4001 cb: extern "C" fn(*mut c_void, *const YXmlEvent),
4002) {
4003 assert!(!xml.is_null());
4004 let state = CallbackState::new(state);
4005
4006 let xml = XmlElementRef::from_raw_branch(xml);
4007 xml.observe(origin(key_len, key), move |txn, e| {
4008 let e = YXmlEvent::new(e, txn);
4009 cb(state.0, &e as *const YXmlEvent);
4010 });
4011}
4012
4013#[no_mangle]
4017pub unsafe extern "C" fn yxmltext_observe(
4018 xml: *const Branch,
4019 key_len: u32,
4020 key: *const c_char,
4021 state: *mut c_void,
4022 cb: extern "C" fn(*mut c_void, *const YXmlTextEvent),
4023) {
4024 assert!(!xml.is_null());
4025
4026 let state = CallbackState::new(state);
4027 let xml = XmlTextRef::from_raw_branch(xml);
4028 xml.observe(origin(key_len, key), move |txn, e| {
4029 let e = YXmlTextEvent::new(e, txn);
4030 cb(state.0, &e as *const YXmlTextEvent);
4031 });
4032}
4033
4034#[no_mangle]
4038pub unsafe extern "C" fn yobserve_deep(
4039 ytype: *mut Branch,
4040 key_len: u32,
4041 key: *const c_char,
4042 state: *mut c_void,
4043 cb: extern "C" fn(*mut c_void, u32, *const YEvent),
4044) {
4045 assert!(!ytype.is_null());
4046
4047 let state = CallbackState::new(state);
4048 let key = origin(key_len, key);
4049 let branch = ytype.as_mut().unwrap();
4050 branch.observe_deep(key, move |txn, events| {
4051 let events: Vec<_> = events.iter().map(|e| YEvent::new(txn, e)).collect();
4052 let len = events.len() as u32;
4053 cb(state.0, len, events.as_ptr());
4054 });
4055}
4056
4057#[repr(C)]
4060pub struct YAfterTransactionEvent {
4061 pub before_state: YStateVector,
4063 pub after_state: YStateVector,
4065 pub delete_set: YIdSet,
4067}
4068
4069impl YAfterTransactionEvent {
4070 unsafe fn new(e: &TransactionCleanupEvent) -> Self {
4071 YAfterTransactionEvent {
4072 before_state: YStateVector::new(&e.before_state),
4073 after_state: YStateVector::new(&e.after_state),
4074 delete_set: YIdSet::new(&e.delete_set),
4075 }
4076 }
4077}
4078
4079#[repr(C)]
4080pub struct YSubdocsEvent {
4081 added_len: u32,
4082 removed_len: u32,
4083 loaded_len: u32,
4084 added: *mut *mut Doc,
4085 removed: *mut *mut Doc,
4086 loaded: *mut *mut Doc,
4087}
4088
4089impl YSubdocsEvent {
4090 unsafe fn new(e: &SubdocsEvent) -> Self {
4091 fn into_ptr(v: SubdocsEventIter) -> *mut *mut Doc {
4092 let array: Vec<_> = v.map(|doc| Box::into_raw(Box::new(doc.clone()))).collect();
4093 let mut boxed = array.into_boxed_slice();
4094 let ptr = boxed.as_mut_ptr();
4095 forget(boxed);
4096 ptr
4097 }
4098
4099 let added = e.added();
4100 let removed = e.removed();
4101 let loaded = e.loaded();
4102
4103 YSubdocsEvent {
4104 added_len: added.len() as u32,
4105 removed_len: removed.len() as u32,
4106 loaded_len: loaded.len() as u32,
4107 added: into_ptr(added),
4108 removed: into_ptr(removed),
4109 loaded: into_ptr(loaded),
4110 }
4111 }
4112}
4113
4114impl Drop for YSubdocsEvent {
4115 fn drop(&mut self) {
4116 fn release(len: u32, buf: *mut *mut Doc) {
4117 unsafe {
4118 let docs = Vec::from_raw_parts(buf, len as usize, len as usize);
4119 for d in docs {
4120 drop(Box::from_raw(d));
4121 }
4122 }
4123 }
4124
4125 release(self.added_len, self.added);
4126 release(self.removed_len, self.removed);
4127 release(self.loaded_len, self.loaded);
4128 }
4129}
4130
4131#[repr(C)]
4134pub struct YStateVector {
4135 pub entries_count: u32,
4137 pub client_ids: *mut u64,
4141 pub clocks: *mut u32,
4145}
4146
4147impl YStateVector {
4148 unsafe fn new(sv: &StateVector) -> Self {
4149 let entries_count = sv.len() as u32;
4150 let mut client_ids = Vec::with_capacity(sv.len());
4151 let mut clocks = Vec::with_capacity(sv.len());
4152 for (&client, &clock) in sv.iter() {
4153 client_ids.push(client.get());
4154 clocks.push(clock as u32);
4155 }
4156
4157 YStateVector {
4158 entries_count,
4159 client_ids: Box::into_raw(client_ids.into_boxed_slice()) as *mut _,
4160 clocks: Box::into_raw(clocks.into_boxed_slice()) as *mut _,
4161 }
4162 }
4163}
4164
4165impl Drop for YStateVector {
4166 fn drop(&mut self) {
4167 let len = self.entries_count as usize;
4168 drop(unsafe { Vec::from_raw_parts(self.client_ids, len, len) });
4169 drop(unsafe { Vec::from_raw_parts(self.clocks, len, len) });
4170 }
4171}
4172
4173#[repr(C)]
4177pub struct YIdSet {
4178 pub entries_count: u32,
4180 pub client_ids: *mut u64,
4184 pub ranges: *mut YIdRangeSeq,
4188}
4189
4190impl YIdSet {
4191 unsafe fn new(ds: &IdSet) -> Self {
4192 let len = ds.len();
4193 let mut client_ids = Vec::with_capacity(len);
4194 let mut ranges = Vec::with_capacity(len);
4195
4196 for (&client, range) in ds.iter() {
4197 client_ids.push(client.get());
4198 let seq: Vec<_> = range
4199 .iter()
4200 .map(|r| YIdRange {
4201 start: r.start as u32,
4202 end: r.end as u32,
4203 })
4204 .collect();
4205 ranges.push(YIdRangeSeq {
4206 len: seq.len() as u32,
4207 seq: Box::into_raw(seq.into_boxed_slice()) as *mut _,
4208 })
4209 }
4210
4211 YIdSet {
4212 entries_count: len as u32,
4213 client_ids: Box::into_raw(client_ids.into_boxed_slice()) as *mut _,
4214 ranges: Box::into_raw(ranges.into_boxed_slice()) as *mut _,
4215 }
4216 }
4217}
4218
4219impl Drop for YIdSet {
4220 fn drop(&mut self) {
4221 let len = self.entries_count as usize;
4222 drop(unsafe { Vec::from_raw_parts(self.client_ids, len, len) });
4223 drop(unsafe { Vec::from_raw_parts(self.ranges, len, len) });
4224 }
4225}
4226
4227#[repr(C)]
4230pub struct YIdRangeSeq {
4231 pub len: u32,
4233 pub seq: *mut YIdRange,
4237}
4238
4239impl Drop for YIdRangeSeq {
4240 fn drop(&mut self) {
4241 let len = self.len as usize;
4242 drop(unsafe { Vec::from_raw_parts(self.seq, len, len) })
4243 }
4244}
4245
4246#[repr(C)]
4247pub struct YIdRange {
4248 pub start: u32,
4249 pub end: u32,
4250}
4251
4252#[repr(C)]
4253pub struct YEvent {
4254 pub tag: i8,
4262
4263 pub content: YEventContent,
4266}
4267
4268impl YEvent {
4269 fn new<'doc>(txn: &yrs::TransactionMut<'doc>, e: &Event) -> YEvent {
4270 match e {
4271 Event::Text(e) => YEvent {
4272 tag: Y_TEXT,
4273 content: YEventContent {
4274 text: YTextEvent::new(e, txn),
4275 },
4276 },
4277 Event::Array(e) => YEvent {
4278 tag: Y_ARRAY,
4279 content: YEventContent {
4280 array: YArrayEvent::new(e, txn),
4281 },
4282 },
4283 Event::Map(e) => YEvent {
4284 tag: Y_MAP,
4285 content: YEventContent {
4286 map: YMapEvent::new(e, txn),
4287 },
4288 },
4289 Event::XmlFragment(e) => YEvent {
4290 tag: if let XmlOut::Fragment(_) = e.target() {
4291 Y_XML_FRAG
4292 } else {
4293 Y_XML_ELEM
4294 },
4295 content: YEventContent {
4296 xml_elem: YXmlEvent::new(e, txn),
4297 },
4298 },
4299 Event::XmlText(e) => YEvent {
4300 tag: Y_XML_TEXT,
4301 content: YEventContent {
4302 xml_text: YXmlTextEvent::new(e, txn),
4303 },
4304 },
4305 Event::Weak(e) => YEvent {
4306 tag: Y_WEAK_LINK,
4307 content: YEventContent {
4308 weak: YWeakLinkEvent::new(e, txn),
4309 },
4310 },
4311 }
4312 }
4313}
4314
4315#[repr(C)]
4316pub union YEventContent {
4317 pub text: YTextEvent,
4318 pub map: YMapEvent,
4319 pub array: YArrayEvent,
4320 pub xml_elem: YXmlEvent,
4321 pub xml_text: YXmlTextEvent,
4322 pub weak: YWeakLinkEvent,
4323}
4324
4325#[repr(C)]
4329#[derive(Copy, Clone)]
4330pub struct YTextEvent {
4331 inner: *const c_void,
4332 txn: *const yrs::TransactionMut<'static>,
4333}
4334
4335impl YTextEvent {
4336 fn new<'dev>(inner: &TextEvent, txn: &yrs::TransactionMut<'dev>) -> Self {
4337 let inner = inner as *const TextEvent as *const _;
4338 let txn: &yrs::TransactionMut<'static> = unsafe { std::mem::transmute(txn) };
4339 let txn = txn as *const _;
4340 YTextEvent { inner, txn }
4341 }
4342
4343 fn txn(&self) -> &yrs::TransactionMut {
4344 unsafe { self.txn.as_ref().unwrap() }
4345 }
4346}
4347
4348impl Deref for YTextEvent {
4349 type Target = TextEvent;
4350
4351 fn deref(&self) -> &Self::Target {
4352 unsafe { (self.inner as *const TextEvent).as_ref().unwrap() }
4353 }
4354}
4355
4356#[repr(C)]
4360#[derive(Copy, Clone)]
4361pub struct YArrayEvent {
4362 inner: *const c_void,
4363 txn: *const yrs::TransactionMut<'static>,
4364}
4365
4366impl YArrayEvent {
4367 fn new<'doc>(inner: &ArrayEvent, txn: &yrs::TransactionMut<'doc>) -> Self {
4368 let inner = inner as *const ArrayEvent as *const _;
4369 let txn: &yrs::TransactionMut<'static> = unsafe { std::mem::transmute(txn) };
4370 let txn = txn as *const _;
4371 YArrayEvent { inner, txn }
4372 }
4373
4374 fn txn(&self) -> &yrs::TransactionMut {
4375 unsafe { self.txn.as_ref().unwrap() }
4376 }
4377}
4378
4379impl Deref for YArrayEvent {
4380 type Target = ArrayEvent;
4381
4382 fn deref(&self) -> &Self::Target {
4383 unsafe { (self.inner as *const ArrayEvent).as_ref().unwrap() }
4384 }
4385}
4386
4387#[repr(C)]
4391#[derive(Copy, Clone)]
4392pub struct YMapEvent {
4393 inner: *const c_void,
4394 txn: *const yrs::TransactionMut<'static>,
4395}
4396
4397impl YMapEvent {
4398 fn new<'doc>(inner: &MapEvent, txn: &yrs::TransactionMut<'doc>) -> Self {
4399 let inner = inner as *const MapEvent as *const _;
4400 let txn: &yrs::TransactionMut<'static> = unsafe { std::mem::transmute(txn) };
4401 let txn = txn as *const _;
4402 YMapEvent { inner, txn }
4403 }
4404
4405 fn txn(&self) -> &yrs::TransactionMut<'static> {
4406 unsafe { self.txn.as_ref().unwrap() }
4407 }
4408}
4409
4410impl Deref for YMapEvent {
4411 type Target = MapEvent;
4412
4413 fn deref(&self) -> &Self::Target {
4414 unsafe { (self.inner as *const MapEvent).as_ref().unwrap() }
4415 }
4416}
4417
4418#[repr(C)]
4423#[derive(Copy, Clone)]
4424pub struct YXmlEvent {
4425 inner: *const c_void,
4426 txn: *const yrs::TransactionMut<'static>,
4427}
4428
4429impl YXmlEvent {
4430 fn new<'doc>(inner: &XmlEvent, txn: &yrs::TransactionMut<'doc>) -> Self {
4431 let inner = inner as *const XmlEvent as *const _;
4432 let txn: &yrs::TransactionMut<'static> = unsafe { std::mem::transmute(txn) };
4433 let txn = txn as *const _;
4434 YXmlEvent { inner, txn }
4435 }
4436
4437 fn txn(&self) -> &yrs::TransactionMut<'static> {
4438 unsafe { self.txn.as_ref().unwrap() }
4439 }
4440}
4441
4442impl Deref for YXmlEvent {
4443 type Target = XmlEvent;
4444
4445 fn deref(&self) -> &Self::Target {
4446 unsafe { (self.inner as *const XmlEvent).as_ref().unwrap() }
4447 }
4448}
4449
4450#[repr(C)]
4455#[derive(Copy, Clone)]
4456pub struct YXmlTextEvent {
4457 inner: *const c_void,
4458 txn: *const yrs::TransactionMut<'static>,
4459}
4460
4461impl YXmlTextEvent {
4462 fn new<'doc>(inner: &XmlTextEvent, txn: &yrs::TransactionMut<'doc>) -> Self {
4463 let inner = inner as *const XmlTextEvent as *const _;
4464 let txn: &yrs::TransactionMut<'static> = unsafe { std::mem::transmute(txn) };
4465 let txn = txn as *const _;
4466 YXmlTextEvent { inner, txn }
4467 }
4468
4469 fn txn(&self) -> &yrs::TransactionMut<'static> {
4470 unsafe { self.txn.as_ref().unwrap() }
4471 }
4472}
4473
4474impl Deref for YXmlTextEvent {
4475 type Target = XmlTextEvent;
4476
4477 fn deref(&self) -> &Self::Target {
4478 unsafe { (self.inner as *const XmlTextEvent).as_ref().unwrap() }
4479 }
4480}
4481
4482#[repr(C)]
4485#[derive(Copy, Clone)]
4486pub struct YWeakLinkEvent {
4487 inner: *const c_void,
4488 txn: *const yrs::TransactionMut<'static>,
4489}
4490
4491impl YWeakLinkEvent {
4492 fn new<'doc>(inner: &WeakEvent, txn: &yrs::TransactionMut<'doc>) -> Self {
4493 let inner = inner as *const WeakEvent as *const _;
4494 let txn: &yrs::TransactionMut<'static> = unsafe { std::mem::transmute(txn) };
4495 let txn = txn as *const _;
4496 YWeakLinkEvent { inner, txn }
4497 }
4498}
4499
4500impl Deref for YWeakLinkEvent {
4501 type Target = WeakEvent;
4502
4503 fn deref(&self) -> &Self::Target {
4504 unsafe { (self.inner as *const WeakEvent).as_ref().unwrap() }
4505 }
4506}
4507
4508#[no_mangle]
4510pub unsafe extern "C" fn ytext_event_target(e: *const YTextEvent) -> *mut Branch {
4511 assert!(!e.is_null());
4512 let out = (&*e).target().clone();
4513 out.into_raw_branch()
4514}
4515
4516#[no_mangle]
4518pub unsafe extern "C" fn yarray_event_target(e: *const YArrayEvent) -> *mut Branch {
4519 assert!(!e.is_null());
4520 let out = (&*e).target().clone();
4521 out.into_raw_branch()
4522}
4523
4524#[no_mangle]
4526pub unsafe extern "C" fn ymap_event_target(e: *const YMapEvent) -> *mut Branch {
4527 assert!(!e.is_null());
4528 let out = (&*e).target().clone();
4529 out.into_raw_branch()
4530}
4531
4532#[no_mangle]
4534pub unsafe extern "C" fn yxmlelem_event_target(e: *const YXmlEvent) -> *mut Branch {
4535 assert!(!e.is_null());
4536 let out = (&*e).target().clone();
4537 match out {
4538 XmlOut::Element(e) => e.into_raw_branch(),
4539 XmlOut::Fragment(e) => e.into_raw_branch(),
4540 XmlOut::Text(e) => e.into_raw_branch(),
4541 }
4542}
4543
4544#[no_mangle]
4546pub unsafe extern "C" fn yxmltext_event_target(e: *const YXmlTextEvent) -> *mut Branch {
4547 assert!(!e.is_null());
4548 let out = (&*e).target().clone();
4549 out.into_raw_branch()
4550}
4551
4552#[no_mangle]
4559pub unsafe extern "C" fn ytext_event_path(
4560 e: *const YTextEvent,
4561 len: *mut u32,
4562) -> *mut YPathSegment {
4563 assert!(!e.is_null());
4564 let e = &*e;
4565 let path: Vec<_> = e.path().into_iter().map(YPathSegment::from).collect();
4566 let out = path.into_boxed_slice();
4567 *len = out.len() as u32;
4568 Box::into_raw(out) as *mut _
4569}
4570
4571#[no_mangle]
4578pub unsafe extern "C" fn ymap_event_path(e: *const YMapEvent, len: *mut u32) -> *mut YPathSegment {
4579 assert!(!e.is_null());
4580 let e = &*e;
4581 let path: Vec<_> = e.path().into_iter().map(YPathSegment::from).collect();
4582 let out = path.into_boxed_slice();
4583 *len = out.len() as u32;
4584 Box::into_raw(out) as *mut _
4585}
4586
4587#[no_mangle]
4594pub unsafe extern "C" fn yxmlelem_event_path(
4595 e: *const YXmlEvent,
4596 len: *mut u32,
4597) -> *mut YPathSegment {
4598 assert!(!e.is_null());
4599 let e = &*e;
4600 let path: Vec<_> = e.path().into_iter().map(YPathSegment::from).collect();
4601 let out = path.into_boxed_slice();
4602 *len = out.len() as u32;
4603 Box::into_raw(out) as *mut _
4604}
4605
4606#[no_mangle]
4613pub unsafe extern "C" fn yxmltext_event_path(
4614 e: *const YXmlTextEvent,
4615 len: *mut u32,
4616) -> *mut YPathSegment {
4617 assert!(!e.is_null());
4618 let e = &*e;
4619 let path: Vec<_> = e.path().into_iter().map(YPathSegment::from).collect();
4620 let out = path.into_boxed_slice();
4621 *len = out.len() as u32;
4622 Box::into_raw(out) as *mut _
4623}
4624
4625#[no_mangle]
4632pub unsafe extern "C" fn yarray_event_path(
4633 e: *const YArrayEvent,
4634 len: *mut u32,
4635) -> *mut YPathSegment {
4636 assert!(!e.is_null());
4637 let e = &*e;
4638 let path: Vec<_> = e.path().into_iter().map(YPathSegment::from).collect();
4639 let out = path.into_boxed_slice();
4640 *len = out.len() as u32;
4641 Box::into_raw(out) as *mut _
4642}
4643
4644#[no_mangle]
4647pub unsafe extern "C" fn ypath_destroy(path: *mut YPathSegment, len: u32) {
4648 if !path.is_null() {
4649 drop(Vec::from_raw_parts(path, len as usize, len as usize));
4650 }
4651}
4652
4653#[no_mangle]
4660pub unsafe extern "C" fn ytext_event_delta(e: *const YTextEvent, len: *mut u32) -> *mut YDeltaOut {
4661 assert!(!e.is_null());
4662 let e = &*e;
4663 let delta: Vec<_> = e.delta(e.txn()).into_iter().map(YDeltaOut::from).collect();
4664
4665 let out = delta.into_boxed_slice();
4666 *len = out.len() as u32;
4667 Box::into_raw(out) as *mut _
4668}
4669
4670#[no_mangle]
4677pub unsafe extern "C" fn yxmltext_event_delta(
4678 e: *const YXmlTextEvent,
4679 len: *mut u32,
4680) -> *mut YDeltaOut {
4681 assert!(!e.is_null());
4682 let e = &*e;
4683 let delta: Vec<_> = e.delta(e.txn()).into_iter().map(YDeltaOut::from).collect();
4684
4685 let out = delta.into_boxed_slice();
4686 *len = out.len() as u32;
4687 Box::into_raw(out) as *mut _
4688}
4689
4690#[no_mangle]
4697pub unsafe extern "C" fn yarray_event_delta(
4698 e: *const YArrayEvent,
4699 len: *mut u32,
4700) -> *mut YEventChange {
4701 assert!(!e.is_null());
4702 let e = &*e;
4703 let delta: Vec<_> = e
4704 .delta(e.txn())
4705 .into_iter()
4706 .map(YEventChange::from)
4707 .collect();
4708
4709 let out = delta.into_boxed_slice();
4710 *len = out.len() as u32;
4711 Box::into_raw(out) as *mut _
4712}
4713
4714#[no_mangle]
4721pub unsafe extern "C" fn yxmlelem_event_delta(
4722 e: *const YXmlEvent,
4723 len: *mut u32,
4724) -> *mut YEventChange {
4725 assert!(!e.is_null());
4726 let e = &*e;
4727 let delta: Vec<_> = e
4728 .delta(e.txn())
4729 .into_iter()
4730 .map(YEventChange::from)
4731 .collect();
4732
4733 let out = delta.into_boxed_slice();
4734 *len = out.len() as u32;
4735 Box::into_raw(out) as *mut _
4736}
4737
4738#[no_mangle]
4740pub unsafe extern "C" fn ytext_delta_destroy(delta: *mut YDeltaOut, len: u32) {
4741 if !delta.is_null() {
4742 let delta = Vec::from_raw_parts(delta, len as usize, len as usize);
4743 drop(delta);
4744 }
4745}
4746
4747#[no_mangle]
4749pub unsafe extern "C" fn yevent_delta_destroy(delta: *mut YEventChange, len: u32) {
4750 if !delta.is_null() {
4751 let delta = Vec::from_raw_parts(delta, len as usize, len as usize);
4752 drop(delta);
4753 }
4754}
4755
4756#[no_mangle]
4763pub unsafe extern "C" fn ymap_event_keys(
4764 e: *const YMapEvent,
4765 len: *mut u32,
4766) -> *mut YEventKeyChange {
4767 assert!(!e.is_null());
4768 let e = &*e;
4769 let delta: Vec<_> = e
4770 .keys(e.txn())
4771 .into_iter()
4772 .map(|(k, v)| YEventKeyChange::new(k.as_ref(), v))
4773 .collect();
4774
4775 let out = delta.into_boxed_slice();
4776 *len = out.len() as u32;
4777 Box::into_raw(out) as *mut _
4778}
4779
4780#[no_mangle]
4786pub unsafe extern "C" fn yxmlelem_event_keys(
4787 e: *const YXmlEvent,
4788 len: *mut u32,
4789) -> *mut YEventKeyChange {
4790 assert!(!e.is_null());
4791 let e = &*e;
4792 let delta: Vec<_> = e
4793 .keys(e.txn())
4794 .into_iter()
4795 .map(|(k, v)| YEventKeyChange::new(k.as_ref(), v))
4796 .collect();
4797
4798 let out = delta.into_boxed_slice();
4799 *len = out.len() as u32;
4800 Box::into_raw(out) as *mut _
4801}
4802
4803#[no_mangle]
4809pub unsafe extern "C" fn yxmltext_event_keys(
4810 e: *const YXmlTextEvent,
4811 len: *mut u32,
4812) -> *mut YEventKeyChange {
4813 assert!(!e.is_null());
4814 let e = &*e;
4815 let delta: Vec<_> = e
4816 .keys(e.txn())
4817 .into_iter()
4818 .map(|(k, v)| YEventKeyChange::new(k.as_ref(), v))
4819 .collect();
4820
4821 let out = delta.into_boxed_slice();
4822 *len = out.len() as u32;
4823 Box::into_raw(out) as *mut _
4824}
4825
4826#[no_mangle]
4829pub unsafe extern "C" fn yevent_keys_destroy(keys: *mut YEventKeyChange, len: u32) {
4830 if !keys.is_null() {
4831 drop(Vec::from_raw_parts(keys, len as usize, len as usize));
4832 }
4833}
4834
4835pub type YUndoManager = yrs::undo::UndoManager<AtomicPtr<c_void>>;
4836
4837#[repr(C)]
4838pub struct YUndoManagerOptions {
4839 pub capture_timeout_millis: i32,
4840}
4841
4842#[no_mangle]
4850pub unsafe extern "C" fn yundo_manager(options: *const YUndoManagerOptions) -> *mut YUndoManager {
4851 let mut o = yrs::undo::Options::default();
4852 if let Some(options) = options.as_ref() {
4853 if options.capture_timeout_millis >= 0 {
4854 o.capture_timeout_millis = options.capture_timeout_millis as u64;
4855 }
4856 };
4857 let boxed = Box::new(yrs::undo::UndoManager::with_options(o));
4858 Box::into_raw(boxed)
4859}
4860
4861#[no_mangle]
4863pub unsafe extern "C" fn yundo_manager_destroy(mgr: *mut YUndoManager) {
4864 drop(Box::from_raw(mgr));
4865}
4866
4867#[no_mangle]
4872pub unsafe extern "C" fn yundo_manager_add_origin(
4873 mgr: *mut YUndoManager,
4874 origin_len: u32,
4875 origin: *const c_char,
4876) {
4877 let mgr = mgr.as_mut().unwrap();
4878 let bytes = std::slice::from_raw_parts(origin as *const u8, origin_len as usize);
4879 mgr.include_origin(Origin::from(bytes));
4880}
4881
4882#[no_mangle]
4884pub unsafe extern "C" fn yundo_manager_remove_origin(
4885 mgr: *mut YUndoManager,
4886 origin_len: u32,
4887 origin: *const c_char,
4888) {
4889 let mgr = mgr.as_mut().unwrap();
4890 let bytes = std::slice::from_raw_parts(origin as *const u8, origin_len as usize);
4891 mgr.exclude_origin(Origin::from(bytes));
4892}
4893
4894#[no_mangle]
4896pub unsafe extern "C" fn yundo_manager_add_scope(
4897 mgr: *mut YUndoManager,
4898 doc: *const Doc,
4899 ytype: *const Branch,
4900) {
4901 let mgr = mgr.as_mut().unwrap();
4902 let doc = doc.as_ref().unwrap();
4903 let branch = ytype.as_ref().unwrap();
4904 mgr.expand_scope(doc, &BranchPtr::from(branch));
4905}
4906
4907#[no_mangle]
4916pub unsafe extern "C" fn yundo_manager_clear(mgr: *mut YUndoManager) {
4917 let mgr = mgr.as_mut().unwrap();
4918 mgr.clear_all();
4919}
4920
4921#[no_mangle]
4928pub unsafe extern "C" fn yundo_manager_stop(mgr: *mut YUndoManager) {
4929 let mgr = mgr.as_mut().unwrap();
4930 mgr.reset();
4931}
4932
4933#[no_mangle]
4940pub unsafe extern "C" fn yundo_manager_undo(mgr: *mut YUndoManager) -> u8 {
4941 let mgr = mgr.as_mut().unwrap();
4942
4943 if mgr.undo_blocking() {
4944 Y_TRUE
4945 } else {
4946 Y_FALSE
4947 }
4948}
4949
4950#[no_mangle]
4956pub unsafe extern "C" fn yundo_manager_redo(mgr: *mut YUndoManager) -> u8 {
4957 let mgr = mgr.as_mut().unwrap();
4958 if mgr.redo_blocking() {
4959 Y_TRUE
4960 } else {
4961 Y_FALSE
4962 }
4963}
4964
4965#[no_mangle]
4967pub unsafe extern "C" fn yundo_manager_undo_stack_len(mgr: *mut YUndoManager) -> u32 {
4968 let mgr = mgr.as_mut().unwrap();
4969 mgr.undo_stack().len() as u32
4970}
4971
4972#[no_mangle]
4974pub unsafe extern "C" fn yundo_manager_redo_stack_len(mgr: *mut YUndoManager) -> u32 {
4975 let mgr = mgr.as_mut().unwrap();
4976 mgr.redo_stack().len() as u32
4977}
4978
4979#[no_mangle]
4983pub unsafe extern "C" fn yundo_manager_observe_added(
4984 mgr: *mut YUndoManager,
4985 key_len: u32,
4986 key: *const c_char,
4987 state: *mut c_void,
4988 callback: extern "C" fn(*mut c_void, *const YUndoEvent),
4989) {
4990 let state = CallbackState::new(state);
4991 let mgr = mgr.as_mut().unwrap();
4992 mgr.observe_item_added(origin(key_len, key), move |_, e| {
4993 let meta_ptr = {
4994 let event = YUndoEvent::new(e);
4995 callback(state.0, &event as *const YUndoEvent);
4996 event.meta
4997 };
4998 e.meta().store(meta_ptr, Ordering::Release);
4999 });
5000}
5001
5002#[no_mangle]
5005pub unsafe extern "C" fn yundo_manager_unobserve_added(
5006 mgr: *mut YUndoManager,
5007 key_len: u32,
5008 key: *const c_char,
5009) -> u8 {
5010 let mgr = mgr.as_mut().unwrap();
5011 mgr.unobserve_item_added(origin(key_len, key)) as u8
5012}
5013
5014#[no_mangle]
5018pub unsafe extern "C" fn yundo_manager_observe_popped(
5019 mgr: *mut YUndoManager,
5020 key_len: u32,
5021 key: *const c_char,
5022 state: *mut c_void,
5023 callback: extern "C" fn(*mut c_void, *const YUndoEvent),
5024) {
5025 let mgr = mgr.as_mut().unwrap();
5026 let state = CallbackState::new(state);
5027 mgr.observe_item_popped(origin(key_len, key), move |_, e| {
5028 let meta_ptr = {
5029 let event = YUndoEvent::new(e);
5030 callback(state.0, &event as *const YUndoEvent);
5031 event.meta
5032 };
5033 e.meta().store(meta_ptr, Ordering::Release);
5034 });
5035}
5036
5037#[no_mangle]
5040pub unsafe extern "C" fn yundo_manager_unobserve_popped(
5041 mgr: *mut YUndoManager,
5042 key_len: u32,
5043 key: *const c_char,
5044) -> u8 {
5045 let mgr = mgr.as_mut().unwrap();
5046 mgr.unobserve_item_popped(origin(key_len, key)) as u8
5047}
5048
5049pub const Y_KIND_UNDO: c_char = 0;
5050pub const Y_KIND_REDO: c_char = 1;
5051
5052#[repr(C)]
5056pub struct YUndoEvent {
5057 pub kind: c_char,
5060 pub origin: *const c_char,
5063 pub origin_len: u32,
5067 pub meta: *mut c_void,
5077}
5078
5079impl YUndoEvent {
5080 unsafe fn new(e: &yrs::undo::Event<AtomicPtr<c_void>>) -> Self {
5081 let (origin, origin_len) = if let Some(origin) = e.origin() {
5082 let bytes = origin.as_ref();
5083 let origin_len = bytes.len() as u32;
5084 let origin = bytes.as_ptr() as *const c_char;
5085 (origin, origin_len)
5086 } else {
5087 (null(), 0)
5088 };
5089 YUndoEvent {
5090 kind: match e.kind() {
5091 EventKind::Undo => Y_KIND_UNDO,
5092 EventKind::Redo => Y_KIND_REDO,
5093 },
5094 origin,
5095 origin_len,
5096 meta: e.meta().load(Ordering::Acquire),
5097 }
5098 }
5099}
5100
5101#[no_mangle]
5105pub unsafe extern "C" fn ytype_kind(branch: *const Branch) -> i8 {
5106 if let Some(branch) = branch.as_ref() {
5107 match branch.type_ref() {
5108 TypeRef::Array => Y_ARRAY,
5109 TypeRef::Map => Y_MAP,
5110 TypeRef::Text => Y_TEXT,
5111 TypeRef::XmlElement(_) => Y_XML_ELEM,
5112 TypeRef::XmlText => Y_XML_TEXT,
5113 TypeRef::XmlFragment => Y_XML_FRAG,
5114 TypeRef::SubDoc => Y_DOC,
5115 TypeRef::WeakLink(_) => Y_WEAK_LINK,
5116 TypeRef::XmlHook => 0,
5117 TypeRef::Undefined => 0,
5118 }
5119 } else {
5120 0
5121 }
5122}
5123
5124pub const Y_EVENT_PATH_KEY: c_char = 1;
5126
5127pub const Y_EVENT_PATH_INDEX: c_char = 2;
5129
5130#[repr(C)]
5138pub struct YPathSegment {
5139 pub tag: c_char,
5147
5148 pub value: YPathSegmentCase,
5151}
5152
5153impl From<PathSegment> for YPathSegment {
5154 fn from(ps: PathSegment) -> Self {
5155 match ps {
5156 PathSegment::Key(key) => {
5157 let key = CString::new(key.as_ref()).unwrap().into_raw() as *const _;
5158 YPathSegment {
5159 tag: Y_EVENT_PATH_KEY,
5160 value: YPathSegmentCase { key },
5161 }
5162 }
5163 PathSegment::Index(index) => YPathSegment {
5164 tag: Y_EVENT_PATH_INDEX,
5165 value: YPathSegmentCase {
5166 index: index as u32,
5167 },
5168 },
5169 }
5170 }
5171}
5172
5173impl Drop for YPathSegment {
5174 fn drop(&mut self) {
5175 if self.tag == Y_EVENT_PATH_KEY {
5176 unsafe {
5177 ystring_destroy(self.value.key as *mut _);
5178 }
5179 }
5180 }
5181}
5182
5183#[repr(C)]
5184pub union YPathSegmentCase {
5185 pub key: *const c_char,
5186 pub index: u32,
5187}
5188
5189pub const Y_EVENT_CHANGE_ADD: u8 = 1;
5192
5193pub const Y_EVENT_CHANGE_DELETE: u8 = 2;
5196
5197pub const Y_EVENT_CHANGE_RETAIN: u8 = 3;
5200
5201#[repr(C)]
5217pub struct YEventChange {
5218 pub tag: u8,
5228
5229 pub len: u32,
5232
5233 pub values: *const YOutput,
5236}
5237
5238impl<'a> From<&'a Change> for YEventChange {
5239 fn from(change: &'a Change) -> Self {
5240 match change {
5241 Change::Added(values) => {
5242 let out: Vec<_> = values
5243 .into_iter()
5244 .map(|v| YOutput::from(v.clone()))
5245 .collect();
5246 let len = out.len() as u32;
5247 let out = out.into_boxed_slice();
5248 let values = Box::into_raw(out) as *mut _;
5249
5250 YEventChange {
5251 tag: Y_EVENT_CHANGE_ADD,
5252 len,
5253 values,
5254 }
5255 }
5256 Change::Removed(len) => YEventChange {
5257 tag: Y_EVENT_CHANGE_DELETE,
5258 len: *len as u32,
5259 values: null(),
5260 },
5261 Change::Retain(len) => YEventChange {
5262 tag: Y_EVENT_CHANGE_RETAIN,
5263 len: *len as u32,
5264 values: null(),
5265 },
5266 }
5267 }
5268}
5269
5270impl Drop for YEventChange {
5271 fn drop(&mut self) {
5272 if self.tag == Y_EVENT_CHANGE_ADD {
5273 unsafe {
5274 let len = self.len as usize;
5275 let values = Vec::from_raw_parts(self.values as *mut YOutput, len, len);
5276 drop(values);
5277 }
5278 }
5279 }
5280}
5281
5282#[repr(C)]
5301pub struct YDeltaOut {
5302 pub tag: u8,
5312
5313 pub len: u32,
5316
5317 pub attributes_len: u32,
5319
5320 pub attributes: *mut YDeltaAttr,
5323
5324 pub insert: *mut YOutput,
5327}
5328
5329impl YDeltaOut {
5330 fn insert(value: &Out, attrs: &Option<Box<Attrs>>) -> Self {
5331 let insert = Box::into_raw(Box::new(YOutput::from(value.clone())));
5332 let (attributes_len, attributes) = if let Some(attrs) = attrs {
5333 let len = attrs.len() as u32;
5334 let attrs: Vec<_> = attrs.iter().map(|(k, v)| YDeltaAttr::new(k, v)).collect();
5335 let attrs = Box::into_raw(attrs.into_boxed_slice()) as *mut _;
5336 (len, attrs)
5337 } else {
5338 (0, null_mut())
5339 };
5340
5341 YDeltaOut {
5342 tag: Y_EVENT_CHANGE_ADD,
5343 len: 1,
5344 insert,
5345 attributes_len,
5346 attributes,
5347 }
5348 }
5349
5350 fn retain(len: u32, attrs: &Option<Box<Attrs>>) -> Self {
5351 let (attributes_len, attributes) = if let Some(attrs) = attrs {
5352 let len = attrs.len() as u32;
5353 let attrs: Vec<_> = attrs.iter().map(|(k, v)| YDeltaAttr::new(k, v)).collect();
5354 let attrs = Box::into_raw(attrs.into_boxed_slice()) as *mut _;
5355 (len, attrs)
5356 } else {
5357 (0, null_mut())
5358 };
5359 YDeltaOut {
5360 tag: Y_EVENT_CHANGE_RETAIN,
5361 len,
5362 insert: null_mut(),
5363 attributes_len,
5364 attributes,
5365 }
5366 }
5367
5368 fn delete(len: u32) -> Self {
5369 YDeltaOut {
5370 tag: Y_EVENT_CHANGE_DELETE,
5371 len,
5372 insert: null_mut(),
5373 attributes_len: 0,
5374 attributes: null_mut(),
5375 }
5376 }
5377}
5378
5379impl<'a> From<&'a Delta> for YDeltaOut {
5380 fn from(d: &Delta) -> Self {
5381 match d {
5382 Delta::Inserted(value, attrs) => YDeltaOut::insert(value, attrs),
5383 Delta::Retain(len, attrs) => YDeltaOut::retain(*len, attrs),
5384 Delta::Deleted(len) => YDeltaOut::delete(*len),
5385 }
5386 }
5387}
5388
5389impl Drop for YDeltaOut {
5390 fn drop(&mut self) {
5391 unsafe {
5392 if !self.attributes.is_null() {
5393 let len = self.attributes_len as usize;
5394 drop(Vec::from_raw_parts(self.attributes, len, len));
5395 }
5396 if !self.insert.is_null() {
5397 drop(Box::from_raw(self.insert));
5398 }
5399 }
5400 }
5401}
5402
5403#[repr(C)]
5405pub struct YDeltaAttr {
5406 pub key: *const c_char,
5408 pub value: YOutput,
5410}
5411
5412impl YDeltaAttr {
5413 fn new(k: &Arc<str>, v: &Any) -> Self {
5414 let key = CString::new(k.as_ref()).unwrap().into_raw() as *const _;
5415 let value = YOutput::from(v);
5416 YDeltaAttr { key, value }
5417 }
5418}
5419
5420impl Drop for YDeltaAttr {
5421 fn drop(&mut self) {
5422 unsafe { ystring_destroy(self.key as *mut _) }
5423 }
5424}
5425
5426#[repr(C)]
5441pub struct YDeltaIn {
5442 pub tag: u8,
5452
5453 pub len: u32,
5456
5457 pub attributes: *const YInput,
5460
5461 pub insert: *const YInput,
5464}
5465
5466impl YDeltaIn {
5467 fn as_input(&self) -> Delta<YInput> {
5468 match self.tag {
5469 Y_EVENT_CHANGE_RETAIN => {
5470 let attrs = if self.attributes.is_null() {
5471 None
5472 } else {
5473 let attrs = unsafe { self.attributes.read() };
5474 map_attrs(attrs.into()).map(Box::new)
5475 };
5476 Delta::Retain(self.len, attrs)
5477 }
5478 Y_EVENT_CHANGE_DELETE => Delta::Deleted(self.len),
5479 Y_EVENT_CHANGE_ADD => {
5480 let attrs = if self.attributes.is_null() {
5481 None
5482 } else {
5483 let attrs = unsafe { self.attributes.read() };
5484 map_attrs(attrs.into()).map(Box::new)
5485 };
5486 let input = unsafe { self.insert.read() };
5487 Delta::Inserted(input, attrs)
5488 }
5489 tag => panic!("YDelta tag identifier is of unknown type: {}", tag),
5490 }
5491 }
5492}
5493
5494pub const Y_EVENT_KEY_CHANGE_ADD: c_char = 4;
5497
5498pub const Y_EVENT_KEY_CHANGE_DELETE: c_char = 5;
5501
5502pub const Y_EVENT_KEY_CHANGE_UPDATE: c_char = 6;
5505
5506#[repr(C)]
5519pub struct YEventKeyChange {
5520 pub key: *const c_char,
5522 pub tag: c_char,
5532
5533 pub old_value: *const YOutput,
5535
5536 pub new_value: *const YOutput,
5538}
5539
5540impl YEventKeyChange {
5541 fn new(key: &str, change: &EntryChange) -> Self {
5542 let key = CString::new(key).unwrap().into_raw() as *const _;
5543 match change {
5544 EntryChange::Inserted(new) => YEventKeyChange {
5545 key,
5546 tag: Y_EVENT_KEY_CHANGE_ADD,
5547 old_value: null(),
5548 new_value: Box::into_raw(Box::new(YOutput::from(new.clone()))),
5549 },
5550 EntryChange::Updated(old, new) => YEventKeyChange {
5551 key,
5552 tag: Y_EVENT_KEY_CHANGE_UPDATE,
5553 old_value: Box::into_raw(Box::new(YOutput::from(old.clone()))),
5554 new_value: Box::into_raw(Box::new(YOutput::from(new.clone()))),
5555 },
5556 EntryChange::Removed(old) => YEventKeyChange {
5557 key,
5558 tag: Y_EVENT_KEY_CHANGE_DELETE,
5559 old_value: Box::into_raw(Box::new(YOutput::from(old.clone()))),
5560 new_value: null(),
5561 },
5562 }
5563 }
5564}
5565
5566impl Drop for YEventKeyChange {
5567 fn drop(&mut self) {
5568 unsafe {
5569 ystring_destroy(self.key as *mut _);
5570 youtput_destroy(self.old_value as *mut _);
5571 youtput_destroy(self.new_value as *mut _);
5572 }
5573 }
5574}
5575
5576trait BranchPointable {
5577 fn into_raw_branch(self) -> *mut Branch;
5578 fn from_raw_branch(branch: *const Branch) -> Self;
5579}
5580
5581impl<T> BranchPointable for T
5582where
5583 T: AsRef<Branch> + From<BranchPtr>,
5584{
5585 fn into_raw_branch(self) -> *mut Branch {
5586 let branch_ref = self.as_ref();
5587 branch_ref as *const Branch as *mut Branch
5588 }
5589
5590 fn from_raw_branch(branch: *const Branch) -> Self {
5591 let b = unsafe { branch.as_ref().unwrap() };
5592 let branch_ref = BranchPtr::from(b);
5593 T::from(branch_ref)
5594 }
5595}
5596
5597#[repr(transparent)]
5608pub struct YStickyIndex(StickyIndex);
5609
5610impl From<StickyIndex> for YStickyIndex {
5611 #[inline(always)]
5612 fn from(value: StickyIndex) -> Self {
5613 YStickyIndex(value)
5614 }
5615}
5616
5617#[no_mangle]
5619pub unsafe extern "C" fn ysticky_index_destroy(pos: *mut YStickyIndex) {
5620 drop(Box::from_raw(pos))
5621}
5622
5623#[no_mangle]
5627pub unsafe extern "C" fn ysticky_index_assoc(pos: *const YStickyIndex) -> i8 {
5628 let pos = pos.as_ref().unwrap();
5629 match pos.0.assoc {
5630 Assoc::After => 0,
5631 Assoc::Before => -1,
5632 }
5633}
5634
5635#[no_mangle]
5642pub unsafe extern "C" fn ysticky_index_from_index(
5643 branch: *const Branch,
5644 txn: *mut Transaction,
5645 index: u32,
5646 assoc: i8,
5647) -> *mut YStickyIndex {
5648 assert!(!branch.is_null());
5649 assert!(!txn.is_null());
5650
5651 let branch = BranchPtr::from_raw_branch(branch);
5652 let txn = txn.as_mut().unwrap();
5653 let index = index as u32;
5654 let assoc = if assoc >= 0 {
5655 Assoc::After
5656 } else {
5657 Assoc::Before
5658 };
5659
5660 if let Some(txn) = txn.as_mut() {
5661 if let Some(pos) = StickyIndex::at(txn, branch, index, assoc) {
5662 Box::into_raw(Box::new(YStickyIndex(pos)))
5663 } else {
5664 null_mut()
5665 }
5666 } else {
5667 panic!("ysticky_index_from_index requires a read-write transaction");
5668 }
5669}
5670
5671#[no_mangle]
5674pub unsafe extern "C" fn ysticky_index_encode(
5675 pos: *const YStickyIndex,
5676 len: *mut u32,
5677) -> *mut c_char {
5678 let pos = pos.as_ref().unwrap();
5679 let binary = pos.0.encode_v1().into_boxed_slice();
5680 *len = binary.len() as u32;
5681 Box::into_raw(binary) as *mut c_char
5682}
5683
5684#[no_mangle]
5687pub unsafe extern "C" fn ysticky_index_decode(
5688 binary: *const c_char,
5689 len: u32,
5690) -> *mut YStickyIndex {
5691 let slice = std::slice::from_raw_parts(binary as *const u8, len as usize);
5692 if let Ok(pos) = StickyIndex::decode_v1(slice) {
5693 Box::into_raw(Box::new(YStickyIndex(pos)))
5694 } else {
5695 null_mut()
5696 }
5697}
5698
5699#[no_mangle]
5703pub unsafe extern "C" fn ysticky_index_to_json(pos: *const YStickyIndex) -> *mut c_char {
5704 let pos = pos.as_ref().unwrap();
5705 let json = match serde_json::to_string(&pos.0) {
5706 Ok(json) => json,
5707 Err(_) => return null_mut(),
5708 };
5709 CString::new(json).unwrap().into_raw()
5710}
5711
5712#[no_mangle]
5721pub unsafe extern "C" fn ysticky_index_from_json(json: *const c_char) -> *mut YStickyIndex {
5722 let cstr = CStr::from_ptr(json);
5723 let json = match cstr.to_str() {
5724 Ok(json) => json,
5725 Err(_) => return null_mut(),
5726 };
5727 match serde_json::from_str(json) {
5728 Ok(pos) => Box::into_raw(Box::new(YStickyIndex(pos))),
5729 Err(_) => null_mut(),
5730 }
5731}
5732
5733#[no_mangle]
5739pub unsafe extern "C" fn ysticky_index_read(
5740 pos: *const YStickyIndex,
5741 txn: *const Transaction,
5742 out_branch: *mut *mut Branch,
5743 out_index: *mut u32,
5744) {
5745 let pos = pos.as_ref().unwrap();
5746 let txn = txn.as_ref().unwrap();
5747
5748 if let Some(abs) = pos.0.get_offset(txn) {
5749 *out_branch = abs.branch.as_ref() as *const Branch as *mut Branch;
5750 *out_index = abs.index as u32;
5751 }
5752}
5753
5754pub type Weak = LinkSource;
5755
5756#[no_mangle]
5757pub unsafe extern "C" fn yweak_destroy(weak: *const Weak) {
5758 drop(Arc::from_raw(weak));
5759}
5760
5761#[no_mangle]
5762pub unsafe extern "C" fn yweak_deref(
5763 map_link: *const Branch,
5764 txn: *const Transaction,
5765) -> *mut YOutput {
5766 assert!(!map_link.is_null());
5767 assert!(!txn.is_null());
5768
5769 let txn = txn.as_ref().unwrap();
5770 let weak: WeakRef<MapRef> = WeakRef::from_raw_branch(map_link);
5771 if let Some(value) = weak.try_deref_value(txn) {
5772 Box::into_raw(Box::new(YOutput::from(value)))
5773 } else {
5774 null_mut()
5775 }
5776}
5777
5778#[no_mangle]
5779pub unsafe extern "C" fn yweak_read(
5780 text_link: *const Branch,
5781 txn: *const Transaction,
5782 out_branch: *mut *mut Branch,
5783 out_start_index: *mut u32,
5784 out_end_index: *mut u32,
5785) {
5786 assert!(!text_link.is_null());
5787 assert!(!txn.is_null());
5788
5789 let txn = txn.as_ref().unwrap();
5790 let weak: WeakRef<BranchPtr> = WeakRef::from_raw_branch(text_link);
5791 if let Some(id) = weak.start_id() {
5792 let start = StickyIndex::from_id(*id, Assoc::After);
5794 assert!(weak.end_id() != None);
5795 let end = StickyIndex::from_id(*weak.end_id().unwrap(), Assoc::After);
5796 if let Some(start_pos) = start.get_offset(txn) {
5797 *out_branch = start_pos.branch.as_ref() as *const Branch as *mut Branch;
5798 *out_start_index = start_pos.index as u32;
5799 if let Some(end_pos) = end.get_offset(txn) {
5800 assert!(*out_branch == end_pos.branch.as_ref() as *const Branch as *mut Branch);
5801 *out_end_index = end_pos.index as u32;
5802 }
5803 }
5804 } else {
5805 assert!(weak.end_id() == None); *out_start_index = 0; *out_end_index = 0; }
5810}
5811
5812#[no_mangle]
5813pub unsafe extern "C" fn yweak_iter(
5814 array_link: *const Branch,
5815 txn: *const Transaction,
5816) -> *mut WeakIter {
5817 assert!(!array_link.is_null());
5818 assert!(!txn.is_null());
5819
5820 let txn = txn.as_ref().unwrap();
5821 let weak: WeakRef<ArrayRef> = WeakRef::from_raw_branch(array_link);
5822 let iter: NativeUnquote<'static, Transaction> = std::mem::transmute(weak.unquote(txn));
5823
5824 Box::into_raw(Box::new(WeakIter(iter)))
5825}
5826
5827#[no_mangle]
5828pub unsafe extern "C" fn yweak_iter_destroy(iter: *mut WeakIter) {
5829 drop(Box::from_raw(iter))
5830}
5831
5832#[no_mangle]
5833pub unsafe extern "C" fn yweak_iter_next(iter: *mut WeakIter) -> *mut YOutput {
5834 assert!(!iter.is_null());
5835 let iter = iter.as_mut().unwrap();
5836
5837 if let Some(value) = iter.0.next() {
5838 Box::into_raw(Box::new(YOutput::from(value)))
5839 } else {
5840 null_mut()
5841 }
5842}
5843
5844#[no_mangle]
5845pub unsafe extern "C" fn yweak_string(
5846 text_link: *const Branch,
5847 txn: *const Transaction,
5848) -> *mut c_char {
5849 assert!(!text_link.is_null());
5850 assert!(!txn.is_null());
5851
5852 let txn = txn.as_ref().unwrap();
5853 let weak: WeakRef<TextRef> = WeakRef::from_raw_branch(text_link);
5854
5855 let str = weak.get_string(txn);
5856 CString::new(str).unwrap().into_raw()
5857}
5858
5859#[no_mangle]
5860pub unsafe extern "C" fn yweak_xml_string(
5861 xml_text_link: *const Branch,
5862 txn: *const Transaction,
5863) -> *mut c_char {
5864 assert!(!xml_text_link.is_null());
5865 assert!(!txn.is_null());
5866
5867 let txn = txn.as_ref().unwrap();
5868 let weak: WeakRef<XmlTextRef> = WeakRef::from_raw_branch(xml_text_link);
5869
5870 let str = weak.get_string(txn);
5871 CString::new(str).unwrap().into_raw()
5872}
5873
5874#[no_mangle]
5878pub unsafe extern "C" fn yweak_observe(
5879 weak: *const Branch,
5880 key_len: u32,
5881 key: *const c_char,
5882 state: *mut c_void,
5883 cb: extern "C" fn(*mut c_void, *const YWeakLinkEvent),
5884) {
5885 assert!(!weak.is_null());
5886
5887 let state = CallbackState::new(state);
5888 let txt: WeakRef<BranchPtr> = WeakRef::from_raw_branch(weak);
5889 txt.observe(origin(key_len, key), move |txn, e| {
5890 let e = YWeakLinkEvent::new(e, txn);
5891 cb(state.0, &e as *const YWeakLinkEvent);
5892 });
5893}
5894
5895#[no_mangle]
5896pub unsafe extern "C" fn ymap_link(
5897 map: *const Branch,
5898 txn: *const Transaction,
5899 key: *const c_char,
5900) -> *const Weak {
5901 assert!(!map.is_null());
5902 assert!(!txn.is_null());
5903
5904 let txn = txn.as_ref().unwrap();
5905 let map = MapRef::from_raw_branch(map);
5906 let key = CStr::from_ptr(key).to_str().unwrap();
5907 if let Some(weak) = map.link(txn, key) {
5908 let source = weak.source();
5909 Arc::into_raw(source.clone())
5910 } else {
5911 null()
5912 }
5913}
5914
5915#[no_mangle]
5916pub unsafe extern "C" fn ytext_quote(
5917 text: *const Branch,
5918 txn: *mut Transaction,
5919 start_index: *mut u32,
5920 end_index: *mut u32,
5921 start_exclusive: i8,
5922 end_exclusive: i8,
5923) -> *const Weak {
5924 assert!(!text.is_null());
5925 assert!(!txn.is_null());
5926
5927 let text = TextRef::from_raw_branch(text);
5928 let txn = txn.as_mut().unwrap();
5929 let txn = txn
5930 .as_mut()
5931 .expect("provided transaction was not writeable");
5932
5933 let start_index = start_index.as_ref().cloned();
5934 let end_index = end_index.as_ref().cloned();
5935 let range = ExplicitRange {
5936 start_index,
5937 end_index,
5938 start_exclusive,
5939 end_exclusive,
5940 };
5941 if let Ok(weak) = text.quote(txn, range) {
5942 let source = weak.source();
5943 Arc::into_raw(source.clone())
5944 } else {
5945 null()
5946 }
5947}
5948
5949#[no_mangle]
5950pub unsafe extern "C" fn yarray_quote(
5951 array: *const Branch,
5952 txn: *mut Transaction,
5953 start_index: *mut u32,
5954 end_index: *mut u32,
5955 start_exclusive: i8,
5956 end_exclusive: i8,
5957) -> *const Weak {
5958 assert!(!array.is_null());
5959 assert!(!txn.is_null());
5960
5961 let array = ArrayRef::from_raw_branch(array);
5962 let txn = txn.as_mut().unwrap();
5963 let txn = txn
5964 .as_mut()
5965 .expect("provided transaction was not writeable");
5966
5967 let start_index = start_index.as_ref().cloned();
5968 let end_index = end_index.as_ref().cloned();
5969 let range = ExplicitRange {
5970 start_index,
5971 end_index,
5972 start_exclusive,
5973 end_exclusive,
5974 };
5975 if let Ok(weak) = array.quote(txn, range) {
5976 let source = weak.source();
5977 Arc::into_raw(source.clone())
5978 } else {
5979 null()
5980 }
5981}
5982
5983struct ExplicitRange {
5984 start_index: Option<u32>,
5985 end_index: Option<u32>,
5986 start_exclusive: i8,
5987 end_exclusive: i8,
5988}
5989
5990impl RangeBounds<u32> for ExplicitRange {
5991 fn start_bound(&self) -> Bound<&u32> {
5992 match (&self.start_index, self.start_exclusive) {
5993 (None, _) => Bound::Unbounded,
5994 (Some(i), 0) => Bound::Included(i),
5995 (Some(i), _) => Bound::Excluded(i),
5996 }
5997 }
5998
5999 fn end_bound(&self) -> Bound<&u32> {
6000 match (&self.end_index, self.end_exclusive) {
6001 (None, _) => Bound::Unbounded,
6002 (Some(i), 0) => Bound::Included(i),
6003 (Some(i), _) => Bound::Excluded(i),
6004 }
6005 }
6006}
6007
6008#[repr(C)]
6016pub struct YBranchId {
6017 pub client_or_len: i64,
6020 pub variant: YBranchIdVariant,
6021}
6022
6023#[repr(C)]
6024pub union YBranchIdVariant {
6025 pub clock: u32,
6027 pub name: *const u8,
6032}
6033
6034#[no_mangle]
6037pub unsafe extern "C" fn ybranch_id(branch: *const Branch) -> YBranchId {
6038 let branch = branch.as_ref().unwrap();
6039 match branch.id() {
6040 BranchID::Nested(id) => YBranchId {
6041 client_or_len: id.client.get() as i64,
6042 variant: YBranchIdVariant { clock: id.clock },
6043 },
6044 BranchID::Root(name) => {
6045 let len = -(name.len() as i64);
6046 YBranchId {
6047 client_or_len: len,
6048 variant: YBranchIdVariant {
6049 name: name.as_ptr(),
6050 },
6051 }
6052 }
6053 }
6054}
6055
6056#[no_mangle]
6062pub unsafe extern "C" fn ybranch_get(
6063 branch_id: *const YBranchId,
6064 txn: *mut Transaction,
6065) -> *mut Branch {
6066 let txn = txn.as_ref().unwrap();
6067 let branch_id = branch_id.as_ref().unwrap();
6068 let client_or_len = branch_id.client_or_len;
6069 let ptr = if client_or_len >= 0 {
6070 BranchID::get_nested(
6071 txn,
6072 &ID::new(ClientID::new(client_or_len as u64), branch_id.variant.clock),
6073 )
6074 } else {
6075 let name = std::slice::from_raw_parts(branch_id.variant.name, (-client_or_len) as usize);
6076 BranchID::get_root(txn, std::str::from_utf8_unchecked(name))
6077 };
6078
6079 match ptr {
6080 None => null_mut(),
6081 Some(branch_ptr) => branch_ptr.into_raw_branch(),
6082 }
6083}
6084
6085#[no_mangle]
6089pub unsafe extern "C" fn ybranch_alive(branch: *mut Branch) -> u8 {
6090 if branch.is_null() {
6091 Y_FALSE
6092 } else {
6093 let branch = BranchPtr::from_raw_branch(branch);
6094 if branch.is_deleted() {
6095 Y_FALSE
6096 } else {
6097 Y_TRUE
6098 }
6099 }
6100}
6101
6102#[no_mangle]
6109pub unsafe extern "C" fn ybranch_json(branch: *mut Branch, txn: *mut Transaction) -> *mut c_char {
6110 if branch.is_null() {
6111 std::ptr::null_mut()
6112 } else {
6113 let txn = txn.as_ref().unwrap();
6114 let branch_ref = BranchPtr::from_raw_branch(branch);
6115 let any = match branch_ref.type_ref() {
6116 TypeRef::Array => ArrayRef::from_raw_branch(branch).to_json(txn),
6117 TypeRef::Map => MapRef::from_raw_branch(branch).to_json(txn),
6118 TypeRef::Text => TextRef::from_raw_branch(branch).get_string(txn).into(),
6119 TypeRef::XmlElement(_) => XmlElementRef::from_raw_branch(branch)
6120 .get_string(txn)
6121 .into(),
6122 TypeRef::XmlFragment => XmlFragmentRef::from_raw_branch(branch)
6123 .get_string(txn)
6124 .into(),
6125 TypeRef::XmlText => XmlTextRef::from_raw_branch(branch).get_string(txn).into(),
6126 TypeRef::SubDoc | TypeRef::XmlHook | TypeRef::WeakLink(_) | TypeRef::Undefined => {
6127 return std::ptr::null_mut()
6128 }
6129 };
6130 let json = match serde_json::to_string(&any) {
6131 Ok(json) => json,
6132 Err(_) => return std::ptr::null_mut(),
6133 };
6134 CString::new(json).unwrap().into_raw()
6135 }
6136}