Skip to main content

yrs/
lib.rs

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
34/// Flag used by `YInput` to pass JSON string for an object that should be deserialized and
35/// stored internally as fully fledged scalar type.
36pub const Y_JSON: i8 = -9;
37
38/// Flag used by `YInput` and `YOutput` to tag boolean values.
39pub const Y_JSON_BOOL: i8 = -8;
40
41/// Flag used by `YInput` and `YOutput` to tag floating point numbers.
42pub const Y_JSON_NUM: i8 = -7;
43
44/// Flag used by `YInput` and `YOutput` to tag 64-bit integer numbers.
45pub const Y_JSON_INT: i8 = -6;
46
47/// Flag used by `YInput` and `YOutput` to tag strings.
48pub const Y_JSON_STR: i8 = -5;
49
50/// Flag used by `YInput` and `YOutput` to tag binary content.
51pub const Y_JSON_BUF: i8 = -4;
52
53/// Flag used by `YInput` and `YOutput` to tag embedded JSON-like arrays of values,
54/// which themselves are `YInput` and `YOutput` instances respectively.
55pub const Y_JSON_ARR: i8 = -3;
56
57/// Flag used by `YInput` and `YOutput` to tag embedded JSON-like maps of key-value pairs,
58/// where keys are strings and v
59pub const Y_JSON_MAP: i8 = -2;
60
61/// Flag used by `YInput` and `YOutput` to tag JSON-like null values.
62pub const Y_JSON_NULL: i8 = -1;
63
64/// Flag used by `YInput` and `YOutput` to tag JSON-like undefined values.
65pub const Y_JSON_UNDEF: i8 = 0;
66
67/// Flag used by `YInput` and `YOutput` to tag content, which is an `YArray` shared type.
68pub const Y_ARRAY: i8 = 1;
69
70/// Flag used by `YInput` and `YOutput` to tag content, which is an `YMap` shared type.
71pub const Y_MAP: i8 = 2;
72
73/// Flag used by `YInput` and `YOutput` to tag content, which is an `YText` shared type.
74pub const Y_TEXT: i8 = 3;
75
76/// Flag used by `YInput` and `YOutput` to tag content, which is an `YXmlElement` shared type.
77pub const Y_XML_ELEM: i8 = 4;
78
79/// Flag used by `YInput` and `YOutput` to tag content, which is an `YXmlText` shared type.
80pub const Y_XML_TEXT: i8 = 5;
81
82/// Flag used by `YInput` and `YOutput` to tag content, which is an `YXmlFragment` shared type.
83pub const Y_XML_FRAG: i8 = 6;
84
85/// Flag used by `YInput` and `YOutput` to tag content, which is an `YDoc` shared type.
86pub const Y_DOC: i8 = 7;
87
88/// Flag used by `YInput` and `YOutput` to tag content, which is an `YWeakLink` shared type.
89pub const Y_WEAK_LINK: i8 = 8;
90
91/// Flag used by `YOutput` to tag content, which is an undefined shared type. This usually happens
92/// when it's referencing a root type that has not been initalized localy.
93pub const Y_UNDEFINED: i8 = 9;
94
95/// Flag used to mark a truthy boolean numbers.
96pub const Y_TRUE: u8 = 1;
97
98/// Flag used to mark a falsy boolean numbers.
99pub const Y_FALSE: u8 = 0;
100
101/* pub types below are used by cbindgen for c header generation */
102
103/// A Yrs document type. Documents are the most important units of collaborative resources management.
104/// All shared collections live within a scope of their corresponding documents. All updates are
105/// generated on per-document basis (rather than individual shared type). All operations on shared
106/// collections happen via `YTransaction`, which lifetime is also bound to a document.
107///
108/// Document manages so-called root types, which are top-level shared types definitions (as opposed
109/// to recursively nested types).
110pub type Doc = yrs::Doc;
111
112/// A common shared data type. All Yrs instances can be refered to using this data type (use
113/// `ytype_kind` function if a specific type needs to be determined). Branch pointers are passed
114/// over type-specific functions like `ytext_insert`, `yarray_insert` or `ymap_insert` to perform
115/// a specific shared type operations.
116///
117/// Using write methods of different shared types (eg. `ytext_insert` and `yarray_insert`) over
118/// the same branch may result in undefined behavior.
119pub type Branch = yrs::branch::Branch;
120
121/// Iterator structure used by shared array data type.
122#[repr(transparent)]
123pub struct ArrayIter(NativeArrayIter<&'static Transaction, Transaction>);
124
125/// Iterator structure used by `yweak_iter` function call.
126#[repr(transparent)]
127pub struct WeakIter(NativeUnquote<'static, Transaction>);
128
129/// Iterator structure used by shared map data type. Map iterators are unordered - there's no
130/// specific order in which map entries will be returned during consecutive iterator calls.
131#[repr(transparent)]
132pub struct MapIter(NativeMapIter<'static, &'static Transaction, Transaction>);
133
134/// Iterator structure used by XML nodes (elements and text) to iterate over node's attributes.
135/// Attribute iterators are unordered - there's no specific order in which map entries will be
136/// returned during consecutive iterator calls.
137#[repr(transparent)]
138pub struct Attributes(NativeAttributes<'static, &'static Transaction, Transaction>);
139
140/// Iterator used to traverse over the complex nested tree structure of a XML node. XML node
141/// iterator walks only over `YXmlElement` and `YXmlText` nodes. It does so in ordered manner (using
142/// the order in which children are ordered within their parent nodes) and using **depth-first**
143/// traverse.
144#[repr(transparent)]
145pub struct TreeWalker(NativeTreeWalker<'static, &'static Transaction, Transaction>);
146
147/// Transaction is one of the core types in Yrs. All operations that need to touch or
148/// modify a document's contents (a.k.a. block store), need to be executed in scope of a
149/// transaction.
150#[repr(transparent)]
151pub struct Transaction(TransactionInner);
152
153/// Iterator structure used by json path queries to traverse over the results of a query.
154#[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/// A structure representing single key-value entry of a map output (used by either
204/// embedded JSON-like maps or YMaps).
205#[repr(C)]
206pub struct YMapEntry {
207    /// Null-terminated string representing an entry's key component. Encoded as UTF-8.
208    pub key: *const c_char,
209    /// A `YOutput` value representing containing variadic content that can be stored withing map's
210    /// entry.
211    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/// A structure representing single attribute of an either `YXmlElement` or `YXmlText` instance.
232/// It consists of attribute name and string, both of which are null-terminated UTF-8 strings.
233#[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/// Configuration object used by `YDoc`.
251#[repr(C)]
252pub struct YOptions {
253    /// Globally unique 53-bit integer assigned to corresponding document replica as its identifier.
254    ///
255    /// If two clients share the same `id` and will perform any updates, it will result in
256    /// unrecoverable document state corruption. The same thing may happen if the client restored
257    /// document state from snapshot, that didn't contain all of that clients updates that were sent
258    /// to other peers.
259    pub id: u64,
260
261    /// A NULL-able globally unique Uuid v4 compatible null-terminated string identifier
262    /// of this document. If passed as NULL, a random Uuid will be generated instead.
263    pub guid: *const c_char,
264
265    /// A NULL-able, UTF-8 encoded, null-terminated string of a collection that this document
266    /// belongs to. It's used only by providers.
267    pub collection_id: *const c_char,
268
269    /// Boolean flags used to configure document options:
270    /// - `Y_OFFSET_BYTES`: use UTF-8 byte length for text indexes and offsets.
271    /// - `Y_OFFSET_UTF16`: use UTF-16 code points for text indexes and offsets.
272    /// - `Y_SKIP_GC`: skip automatic garbage collection at transaction commit (useful for snapshots and keeping historical traces).
273    /// - `Y_AUTO_LOAD`: all subdocuments should be loaded automatically.
274    /// - `Y_SHOULD_LOAD`: should current document be synced with its provider immediatelly?
275    /// - `Y_CLEANUP_TEXT_FMT`: automatically remove dangling formatting attributes.
276    pub flags: u8,
277}
278
279/// Flag used by `YOptions` to determine, that text operations offsets and length will be counted by
280/// the byte number of UTF8-encoded string.
281pub const Y_OFFSET_BYTES: u8 = 0;
282
283/// Flag used by `YOptions` to determine, that text operations offsets and length will be counted by
284/// UTF-16 chars of encoded string.
285pub const Y_OFFSET_UTF16: u8 = 1;
286
287/// Boolean flag used to determine if deleted blocks should be garbage collected or not
288/// during the transaction commits. Setting this value to 0 means GC will be performed.
289pub const Y_SKIP_GC: u8 = 1 << 1;
290
291/// Boolean flag used to determine if subdocument should be loaded automatically.
292/// If this is a subdocument, remote peers will load the document as well automatically.
293pub const Y_AUTO_LOAD: u8 = 1 << 2;
294
295/// Boolean flag used to determine whether the document should be synced by the provider now.
296pub const Y_SHOULD_LOAD: u8 = 1 << 3;
297
298/// Whenever we receive an update that might remove piece of text, it might turn out that it was
299/// surrounded by the formatting attributes, that now are effectively dead and unrenderable, but
300/// still are considered alive blocks.
301///
302/// This flag orders cleanup of dangling formatting attributes.
303pub 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/// Returns default ceonfiguration for `YOptions`.
375#[no_mangle]
376pub unsafe extern "C" fn yoptions() -> YOptions {
377    Options::default().into()
378}
379
380/// Releases all memory-allocated resources bound to given document.
381#[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/// Frees all memory-allocated resources bound to a given [YMapEntry].
389#[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/// Frees all memory-allocated resources bound to a given [YXmlAttr].
397#[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/// Frees all memory-allocated resources bound to a given UTF-8 null-terminated string returned from
405/// Yrs document API. Yrs strings don't use libc malloc, so calling `free()` on them will fault.
406#[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/// Frees all memory-allocated resources bound to a given binary returned from Yrs document API.
414/// Unlike strings binaries are not null-terminated and can contain null characters inside,
415/// therefore a size of memory to be released must be explicitly provided.
416/// Yrs binaries don't use libc malloc, so calling `free()` on them will fault.
417#[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/// Creates a new [Doc] instance with a randomized unique client identifier.
425///
426/// Use [ydoc_destroy] in order to release created [Doc] resources.
427#[no_mangle]
428pub extern "C" fn ydoc_new() -> *mut Doc {
429    Box::into_raw(Box::new(Doc::new()))
430}
431
432/// Creates a shallow clone of a provided `doc` - it's realized by increasing the ref-count
433/// value of the document. In result both input and output documents point to the same instance.
434///
435/// Documents created this way can be destroyed via [ydoc_destroy] - keep in mind, that the memory
436/// will still be persisted until all strong references are dropped.
437#[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/// Creates a new [Doc] instance with a specified `options`.
444///
445/// Use [ydoc_destroy] in order to release created [Doc] resources.
446#[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/// Returns a unique client identifier of this [Doc] instance.
452#[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/// Returns a unique document identifier of this [Doc] instance.
459///
460/// Generated string resources should be released using [ystring_destroy] function.
461#[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/// Returns a collection identifier of this [Doc] instance.
469/// If none was defined, a `NULL` will be returned.
470///
471/// Generated string resources should be released using [ystring_destroy] function.
472#[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/// Returns status of should_load flag of this [Doc] instance, informing parent [Doc] if this
483/// document instance requested a data load.
484#[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/// Returns status of auto_load flag of this [Doc] instance. Auto loaded sub-documents automatically
491/// send a load request to their parent documents.
492#[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
511/// Builds an observer key out of a raw byte sequence. Empty (`len == 0`) keys are allowed.
512unsafe 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
521/// Returns a read-write transaction, panicking on read-only ones.
522unsafe 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/// Subscribes a callback `cb` under a given `key` to updates (lib0 v1 encoded) produced by
530/// the document this transaction belongs to. Use `ytransaction_unobserve_updates_v1` to unsubscribe.
531#[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/// Unsubscribes a callback registered under a given `key` via `ytransaction_observe_updates_v1`.
549/// Returns 1 if a callback was removed, 0 otherwise.
550#[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/// Subscribes a callback `cb` under a given `key` to updates (lib0 v2 encoded) produced by
561/// the document this transaction belongs to. Use `ytransaction_unobserve_updates_v2` to unsubscribe.
562#[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/// Unsubscribes a callback registered under a given `key` via `ytransaction_observe_updates_v2`.
580/// Returns 1 if a callback was removed, 0 otherwise.
581#[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/// Subscribes a callback `cb` under a given `key` to be called at the end of every transaction
592/// committed on this document. Use `ytransaction_unobserve_after_transaction` to unsubscribe.
593#[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/// Unsubscribes a callback registered under a given `key` via
610/// `ytransaction_observe_after_transaction`. Returns 1 if a callback was removed, 0 otherwise.
611#[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/// Subscribes a callback `cb` under a given `key` to changes in the set of subdocuments of
622/// this document. Use `ytransaction_unobserve_subdocs` to unsubscribe.
623#[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/// Unsubscribes a callback registered under a given `key` via `ytransaction_observe_subdocs`.
640/// Returns 1 if a callback was removed, 0 otherwise.
641#[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/// Subscribes a callback `cb` under a given `key` to be called when this document is destroyed.
652/// Use `ytransaction_unobserve_clear` to unsubscribe.
653#[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/// Unsubscribes a callback registered under a given `key` via `ytransaction_observe_clear`.
667/// Returns 1 if a callback was removed, 0 otherwise.
668#[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/// Manually send a load request to a parent document of this subdoc.
679#[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/// Destroys current document, sending a 'destroy' event and clearing up all the event callbacks
691/// registered.
692#[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/// Starts a new read-only transaction on a given document. All other operations happen in context
701/// of a transaction. Yrs transactions do not follow ACID rules. Once a set of operations is
702/// complete, a transaction can be finished using `ytransaction_commit` function.
703///
704/// Returns `NULL` if read-only transaction couldn't be created, i.e. when another read-write
705/// transaction is already opened.
706#[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/// Starts a new read-write transaction on a given document. All other operations happen in context
719/// of a transaction. Yrs transactions do not follow ACID rules. Once a set of operations is
720/// complete, a transaction can be finished using `ytransaction_commit` function.
721///
722/// `origin_len` and `origin` are optional parameters to specify a byte sequence used to mark
723/// the origin of this transaction (eg. you may decide to give different origins for transaction
724/// applying remote updates). These can be used by event handlers or `YUndoManager` to perform
725/// specific actions. If origin should not be set, call `ydoc_write_transaction(doc, 0, NULL)`.
726///
727/// Returns `NULL` if read-write transaction couldn't be created, i.e. when another transaction is
728/// already opened.
729#[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/// Returns a list of subdocs existing within current document.
755#[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/// A root-level shared type of a document: its name paired with a pointer to its branch.
771/// Returned by `ytransaction_root_refs`, released via `yroot_refs_destroy`.
772#[repr(C)]
773pub struct YRootRef {
774    /// Null-terminated UTF-8 name of a root-level type. Owned by the array it was returned in.
775    pub name: *mut c_char,
776    /// Branch of a root-level type. Its lifecycle is bound to the document, it must not be released.
777    pub branch: *mut Branch,
778}
779
780/// Returns an array of all root-level shared types defined in a current document, including the
781/// ones that were received from remote peers but never defined locally. Number of returned elements
782/// is written into `len`. Returned array must be released using `yroot_refs_destroy`.
783///
784/// Branches of root types defined only remotely have no concrete type yet: use `ytype_kind` to
785/// check them.
786#[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                // root types are always branches
808                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/// Releases an array of root references returned by `ytransaction_root_refs`. `len` must be the
822/// same value that was written by that call. Branches pointed to by the array are not released.
823#[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/// Commit and dispose provided read-write transaction. This operation releases allocated resources,
835/// triggers update events and performs a storage compression over all operations executed in scope
836/// of a current transaction.
837#[no_mangle]
838pub unsafe extern "C" fn ytransaction_commit(txn: *mut Transaction) {
839    assert!(!txn.is_null());
840    drop(Box::from_raw(txn)); // transaction is auto-committed when dropped
841}
842
843/// Perform garbage collection of deleted blocks, even if a document was created with `skip_gc`
844/// option. This operation will scan over ALL deleted elements, NOT ONLY the ones that have been
845/// changed as part of this transaction scope.
846#[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/// Returns `1` if current transaction is of read-write type.
855/// Returns `0` if transaction is read-only.
856#[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/// Evaluates a JSON path expression (see: https://en.wikipedia.org/wiki/JSONPath) on
867/// the transaction's document and returns an iterator over values matching that query.
868///
869/// Currently, this method supports the following syntax:
870/// - `$` - root object
871/// - `@` - current object
872/// - `.field` or `['field']` - member accessor
873/// - `[1]` - array index (also supports negative indices)
874/// - `.*` or `[*]` - wildcard (matches all members of an object or array)
875/// - `..` - recursive descent (matches all descendants not only direct children)
876/// - `[start:end:step]` - array slice operator (requires positive integer arguments)
877/// - `['a', 'b', 'c']` - union operator (returns an array of values for each query)
878/// - `[1, -1, 3]` - multiple indices operator (returns an array of values for each index)
879///
880/// At the moment, JSON Path does not support filter predicates.
881///
882/// Returns `NULL` if the json_path expression is invalid and couldn't be parsed.
883///
884/// Use ``yjson_path_iter_next` function in order to retrieve a consecutive array elements.
885/// Use ``yjson_path_iter_destroy` function in order to close the iterator and release its resources.
886#[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    // copy JSONPath string to have its ownership
895    let query: String = CStr::from_ptr(json_path).to_str().unwrap().into();
896    // since string is not reallocated/deallocated, we can safely pass it to the parser
897    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    // again, we wraped parsed JSONPath in a Box to ensure that it's owned and not moving
903    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/// Returns the next element of a JSON path iterator. If there are no more elements, `NULL` is returned.
914#[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/// Closes the JSON path iterator created via `ytransaction_json_path` and releases its resources.
927#[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/// Gets a reference to shared data type instance at the document root-level,
935/// identified by its `name`, which must be a null-terminated UTF-8 compatible string.
936///
937/// Returns `NULL` if no such structure was defined in the document before.
938// TODO [LSViana] Rename this to `ytransaction_get_ytype()` (or similar) to match the signature.
939#[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    //NOTE: we're retrieving this as a text, but ultimatelly it doesn't matter as we don't define
946    // nor redefine the underlying branch type
947    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/// Gets or creates a new shared `YText` data type instance as a root-level type of a given document.
955/// This structure can later be accessed using its `name`, which must be a null-terminated UTF-8
956/// compatible string.
957#[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/// Gets or creates a new shared `YArray` data type instance as a root-level type of a given document.
968/// This structure can later be accessed using its `name`, which must be a null-terminated UTF-8
969/// compatible string.
970///
971/// Once created, a `YArray` instance will last for the entire lifecycle of a document.
972#[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/// Gets or creates a new shared `YMap` data type instance as a root-level type of a given document.
985/// This structure can later be accessed using its `name`, which must be a null-terminated UTF-8
986/// compatible string.
987///
988/// Once created, a `YMap` instance will last for the entire lifecycle of a document.
989#[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/// Gets or creates a new shared `YXmlElement` data type instance as a root-level type of a given
1002/// document. This structure can later be accessed using its `name`, which must be a null-terminated
1003/// UTF-8 compatible string.
1004#[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/// Returns a state vector of a current transaction's document, serialized using lib0 version 1
1017/// encoding. Payload created by this function can then be send over the network to a remote peer,
1018/// where it can be used as a parameter of [ytransaction_state_diff_v1] in order to produce a delta
1019/// update payload, that can be send back and applied locally in order to efficiently propagate
1020/// updates from one peer to another.
1021///
1022/// The length of a generated binary will be passed within a `len` out parameter.
1023///
1024/// Once no longer needed, a returned binary can be disposed using [ybinary_destroy] function.
1025#[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/// Returns a delta difference between current state of a transaction's document and a state vector
1041/// `sv` encoded as a binary payload using lib0 version 1 encoding (which could be generated using
1042/// [ytransaction_state_vector_v1]). Such delta can be send back to the state vector's sender in
1043/// order to propagate and apply (using [ytransaction_apply]) all updates known to a current
1044/// document, which remote peer was not aware of.
1045///
1046/// If passed `sv` pointer is null, the generated diff will be a snapshot containing entire state of
1047/// the document.
1048///
1049/// A length of an encoded state vector payload must be passed as `sv_len` parameter.
1050///
1051/// A length of generated delta diff binary will be passed within a `len` out parameter.
1052///
1053/// Once no longer needed, a returned binary can be disposed using [ybinary_destroy] function.
1054#[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/// Returns a delta difference between current state of a transaction's document and a state vector
1085/// `sv` encoded as a binary payload using lib0 version 1 encoding (which could be generated using
1086/// [ytransaction_state_vector_v1]). Such delta can be send back to the state vector's sender in
1087/// order to propagate and apply (using [ytransaction_apply_v2]) all updates known to a current
1088/// document, which remote peer was not aware of.
1089///
1090/// If passed `sv` pointer is null, the generated diff will be a snapshot containing entire state of
1091/// the document.
1092///
1093/// A length of an encoded state vector payload must be passed as `sv_len` parameter.
1094///
1095/// A length of generated delta diff binary will be passed within a `len` out parameter.
1096///
1097/// Once no longer needed, a returned binary can be disposed using [ybinary_destroy] function.
1098#[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/// Returns a snapshot descriptor of a current state of the document. This snapshot information
1129/// can be then used to encode document data at a particular point in time
1130/// (see: `ytransaction_encode_state_from_snapshot`).
1131#[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/// Encodes a state of the document at a point in time specified by the provided `snapshot`
1145/// (generated by: `ytransaction_snapshot`). This is useful to generate a past view of the document.
1146///
1147/// The returned update is binary compatible with Yrs update lib0 v1 encoding, and can be processed
1148/// with functions dedicated to work on it, like `ytransaction_apply`.
1149///
1150/// This function requires document with a GC option flag turned off (otherwise "time travel" would
1151/// not be a safe operation). If this is not a case, the NULL pointer will be returned.
1152#[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/// Encodes a state of the document at a point in time specified by the provided `snapshot`
1178/// (generated by: `ytransaction_snapshot`). This is useful to generate a past view of the document.
1179///
1180/// The returned update is binary compatible with Yrs update lib0 v2 encoding, and can be processed
1181/// with functions dedicated to work on it, like `ytransaction_apply_v2`.
1182///
1183/// This function requires document with a GC option flag turned off (otherwise "time travel" would
1184/// not be a safe operation). If this is not a case, the NULL pointer will be returned.
1185#[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/// Returns an unapplied Delete Set for the current document, waiting for missing updates in order
1211/// to be integrated into document store.
1212///
1213/// Return `NULL` if there's no missing delete set and all deletions have been applied.
1214/// See also: `ytransaction_pending_update`
1215#[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/// Returns a pending update associated with an underlying `YDoc`. Pending update contains update
1233/// data waiting for being integrated into main document store. Usually reason for that is that
1234/// there were missing updates required for integration. In such cases they need to arrive and be
1235/// integrated first.
1236///
1237/// Returns `NULL` if there is not update pending. Returned value can be released by calling
1238/// `ypending_update_destroy`.
1239/// See also: `ytransaction_pending_ds`
1240#[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/// Structure containing unapplied update data.
1262/// Created via `ytransaction_pending_update`.
1263/// Released via `ypending_update_destroy`.
1264#[repr(C)]
1265pub struct YPendingUpdate {
1266    /// A state vector that informs about minimal client clock values that need to be satisfied
1267    /// in order to successfully apply current update.
1268    pub missing: YStateVector,
1269    /// Update data stored in lib0 v1 format.
1270    pub update_v1: *mut c_char,
1271    /// Length of `update_v1` payload.
1272    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/// Returns a null-terminated UTF-8 encoded string representation of an `update` binary payload,
1286/// encoded using lib0 v1 encoding.
1287/// Returns null if update couldn't be parsed into a lib0 v1 formatting.
1288#[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/// Returns a null-terminated UTF-8 encoded string representation of an `update` binary payload,
1302/// encoded using lib0 v2 encoding.
1303/// Returns null if update couldn't be parsed into a lib0 v2 formatting.
1304#[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/// Applies an diff update (generated by `ytransaction_state_diff_v1`) to a local transaction's
1318/// document.
1319///
1320/// A length of generated `diff` binary must be passed within a `diff_len` out parameter.
1321///
1322/// Returns an error code in case if transaction succeeded failed:
1323/// - **0**: success
1324/// - `ERR_CODE_IO` (**1**): couldn't read data from input stream.
1325/// - `ERR_CODE_VAR_INT` (**2**): decoded variable integer outside of the expected integer size bounds.
1326/// - `ERR_CODE_EOS` (**3**): end of stream found when more data was expected.
1327/// - `ERR_CODE_UNEXPECTED_VALUE` (**4**): decoded enum tag value was not among known cases.
1328/// - `ERR_CODE_INVALID_JSON` (**5**): failure when trying to decode JSON content.
1329/// - `ERR_CODE_OTHER` (**6**): other error type than the one specified.
1330#[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/// Applies an diff update (generated by [ytransaction_state_diff_v2]) to a local transaction's
1357/// document.
1358///
1359/// A length of generated `diff` binary must be passed within a `diff_len` out parameter.
1360///
1361/// Returns an error code in case if transaction succeeded failed:
1362/// - **0**: success
1363/// - `ERR_CODE_IO` (**1**): couldn't read data from input stream.
1364/// - `ERR_CODE_VAR_INT` (**2**): decoded variable integer outside of the expected integer size bounds.
1365/// - `ERR_CODE_EOS` (**3**): end of stream found when more data was expected.
1366/// - `ERR_CODE_UNEXPECTED_VALUE` (**4**): decoded enum tag value was not among known cases.
1367/// - `ERR_CODE_INVALID_JSON` (**5**): failure when trying to decode JSON content.
1368/// - `ERR_CODE_OTHER` (**6**): other error type than the one specified.
1369#[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
1394/// Error code: couldn't read data from input stream.
1395pub const ERR_CODE_IO: u8 = 1;
1396
1397/// Error code: decoded variable integer outside of the expected integer size bounds.
1398pub const ERR_CODE_VAR_INT: u8 = 2;
1399
1400/// Error code: end of stream found when more data was expected.
1401pub const ERR_CODE_EOS: u8 = 3;
1402
1403/// Error code: decoded enum tag value was not among known cases.
1404pub const ERR_CODE_UNEXPECTED_VALUE: u8 = 4;
1405
1406/// Error code: failure when trying to decode JSON content.
1407pub const ERR_CODE_INVALID_JSON: u8 = 5;
1408
1409/// Error code: other error type than the one specified.
1410pub const ERR_CODE_OTHER: u8 = 6;
1411
1412/// Error code: not enough memory to perform an operation.
1413pub const ERR_NOT_ENOUGH_MEMORY: u8 = 7;
1414
1415/// Error code: conversion attempt to specific Rust type was not possible.
1416pub const ERR_TYPE_MISMATCH: u8 = 8;
1417
1418/// Error code: miscellaneous error coming from serde, not covered by other error codes.
1419pub const ERR_CUSTOM: u8 = 9;
1420
1421/// Error code: malformed update.
1422pub const ERR_MALFORMED: u8 = 10;
1423
1424/// Error code: update block assigned to parent that is not a valid shared ref of deleted block.
1425pub 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/// Returns the length of the `YText` string content in bytes (without the null terminator character)
1446#[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/// Returns a null-terminated UTF-8 encoded string content of a current `YText` shared data type.
1455///
1456/// Generated string resources should be released using [ystring_destroy] function.
1457#[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/// Inserts a null-terminated UTF-8 encoded string a given `index`. `index` value must be between
1468/// 0 and a length of a `YText` (inclusive, accordingly to [ytext_len] return value), otherwise this
1469/// function will panic.
1470///
1471/// A `str` parameter must be a null-terminated UTF-8 encoded string. This function doesn't take
1472/// ownership over a passed value - it will be copied and therefore a string parameter must be
1473/// released by the caller.
1474///
1475/// A nullable pointer with defined `attrs` will be used to wrap provided text with
1476/// a formatting blocks. `attrs` must be a map-like type.
1477#[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/// Wraps an existing piece of text within a range described by `index`-`len` parameters with
1508/// formatting blocks containing provided `attrs` metadata. `attrs` must be a map-like type.
1509#[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/// Inserts an embed content given `index`. `index` value must be between 0 and a length of a
1536/// `YText` (inclusive, accordingly to [ytext_len] return value), otherwise this
1537/// function will panic.
1538///
1539/// A `str` parameter must be a null-terminated UTF-8 encoded string. This function doesn't take
1540/// ownership over a passed value - it will be copied and therefore a string parameter must be
1541/// released by the caller.
1542///
1543/// A nullable pointer with defined `attrs` will be used to wrap provided text with
1544/// a formatting blocks. `attrs` must be a map-like type.
1545#[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/// Performs a series of changes over the given `YText` shared ref type, described by the `delta`
1576/// parameter:
1577///
1578/// - Deltas constructed with `ydelta_input_retain` will move cursor position by the given number
1579///   of elements. If formatting attributes were defined, all elements skipped over this way will be
1580///   wrapped by given formatting attributes.
1581/// - Deltas constructed with `ydelta_input_delete` will tell cursor to remove a corresponding
1582///   number of elements.
1583/// - Deltas constructed with `ydelta_input_insert` will tell cursor to insert given elements into
1584///   current cursor position. While these elements can be of any type (used for embedding ie.
1585///   shared types or binary payload like images), for the text insertion a `yinput_string`
1586///   is expected. If formatting attributes were specified, inserted elements will be wrapped by
1587///   given formatting attributes.
1588#[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/// Creates a parameter for `ytext_insert_delta` function. This parameter will move cursor position
1610/// by the `len` of elements. If formatting `attrs` were defined, all elements skipped over this
1611/// way will be wrapped by given formatting attributes.
1612#[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/// Creates a parameter for `ytext_insert_delta` function. This parameter will tell cursor to remove
1623/// a corresponding number of elements, starting from current cursor position.
1624#[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/// Creates a parameter for `ytext_insert_delta` function. This parameter will tell cursor to insert
1635/// given elements into current cursor position. While these elements can be of any type (used for
1636/// embedding ie. shared types or binary payload like images), for the text insertion a `yinput_string`
1637/// is expected. If formatting attributes were specified, inserted elements will be wrapped by
1638/// given formatting attributes.
1639#[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/// Removes a range of characters, starting a a given `index`. This range must fit within the bounds
1665/// of a current `YText`, otherwise this function call will fail.
1666///
1667/// An `index` value must be between 0 and the length of a `YText` (exclusive, accordingly to
1668/// [ytext_len] return value).
1669///
1670/// A `length` must be lower or equal number of characters (counted as UTF chars depending on the
1671/// encoding configured by `YDoc`) from `index` position to the end of of the string.
1672#[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/// Returns a number of elements stored within current instance of `YArray`.
1691#[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/// Returns a pointer to a `YOutput` value stored at a given `index` of a current `YArray`.
1700/// If `index` is outside the bounds of an array, a null pointer will be returned.
1701///
1702/// A value returned should be eventually released using [youtput_destroy] function.
1703#[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/// Returns a UTF-8 encoded, NULL-terminated JSON string representing a value stored in a current
1722/// YArray under a given index.
1723///
1724/// This method will return `NULL` pointer if value was outside the bound of an array or couldn't be
1725/// serialized into JSON string.
1726///
1727/// This method will also try to serialize complex types that don't have native JSON representation
1728/// like YMap, YArray, YText etc. in such cases their contents will be materialized into JSON values.
1729///
1730/// A string returned should be eventually released using [ystring_destroy] function.
1731#[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/// Inserts a range of `items` into current `YArray`, starting at given `index`. An `items_len`
1755/// parameter is used to determine the size of `items` array - it can also be used to insert
1756/// a single element given its pointer.
1757///
1758/// An `index` value must be between 0 and (inclusive) length of a current array (use [yarray_len]
1759/// to determine its length), otherwise it will panic at runtime.
1760///
1761/// `YArray` doesn't take ownership over the inserted `items` data - their contents are being copied
1762/// into array structure - therefore caller is responsible for freeing all memory associated with
1763/// input params.
1764#[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        // try read as many values a JSON-like primitives and insert them at once
1790        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/// Removes a `len` of consecutive range of elements from current `array` instance, starting at
1815/// a given `index`. Range determined by `index` and `len` must fit into boundaries of an array,
1816/// otherwise it will panic at runtime.
1817#[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/// Returns an iterator, which can be used to traverse over all elements of an `array` (`array`'s
1837/// length can be determined using [yarray_len] function).
1838///
1839/// Use [yarray_iter_next] function in order to retrieve a consecutive array elements.
1840/// Use [yarray_iter_destroy] function in order to close the iterator and release its resources.
1841#[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/// Releases all of an `YArray` iterator resources created by calling [yarray_iter].
1855#[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/// Moves current `YArray` iterator over to a next element, returning a pointer to it. If an iterator
1863/// comes to an end of an array, a null pointer will be returned.
1864///
1865/// Returned values should be eventually released using [youtput_destroy] function.
1866#[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/// Returns an iterator, which can be used to traverse over all key-value pairs of a `map`.
1880///
1881/// Use [ymap_iter_next] function in order to retrieve a consecutive (**unordered**) map entries.
1882/// Use [ymap_iter_destroy] function in order to close the iterator and release its resources.
1883#[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/// Releases all of an `YMap` iterator resources created by calling [ymap_iter].
1893#[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/// Moves current `YMap` iterator over to a next entry, returning a pointer to it. If an iterator
1901/// comes to an end of a map, a null pointer will be returned. Yrs maps are unordered and so are
1902/// their iterators.
1903///
1904/// Returned values should be eventually released using [ymap_entry_destroy] function.
1905#[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/// Returns a number of entries stored within a `map`.
1919#[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/// Inserts a new entry (specified as `key`-`value` pair) into a current `map`. If entry under such
1930/// given `key` already existed, its corresponding value will be replaced.
1931///
1932/// A `key` must be a null-terminated UTF-8 encoded string, which contents will be copied into
1933/// a `map` (therefore it must be freed by the function caller).
1934///
1935/// A `value` content is being copied into a `map`, therefore any of its content must be freed by
1936/// the function caller.
1937#[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/// Removes a `map` entry, given its `key`. Returns `1` if the corresponding entry was successfully
1962/// removed or `0` if no entry with a provided `key` has been found inside of a `map`.
1963///
1964/// A `key` must be a null-terminated UTF-8 encoded string.
1965#[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/// Returns a value stored under the provided `key`, or a null pointer if no entry with such `key`
1991/// has been found in a current `map`. A returned value is allocated by this function and therefore
1992/// should be eventually released using [youtput_destroy] function.
1993///
1994/// A `key` must be a null-terminated UTF-8 encoded string.
1995#[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/// Returns a value stored under the provided `key` as UTF-8 encoded, NULL-terminated JSON string.
2019/// Once not needed that string should be deallocated using `ystring_destroy`.
2020///
2021/// This method will return `NULL` pointer if value was not found or value couldn't be serialized
2022/// into JSON string.
2023///
2024/// This method will also try to serialize complex types that don't have native JSON representation
2025/// like YMap, YArray, YText etc. in such cases their contents will be materialized into JSON values.
2026#[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/// Removes all entries from a current `map`.
2053#[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/// Return a name (or an XML tag) of a current `YXmlElement`. Root-level XML nodes use "UNDEFINED" as
2068/// their tag names.
2069///
2070/// Returned value is a null-terminated UTF-8 string, which must be released using [ystring_destroy]
2071/// function.
2072#[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/// Converts current `YXmlElement` together with its children and attributes into a flat string
2084/// representation (no padding) eg. `<UNDEFINED><title key="value">sample text</title></UNDEFINED>`.
2085///
2086/// Returned value is a null-terminated UTF-8 string, which must be released using [ystring_destroy]
2087/// function.
2088#[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/// Inserts an XML attribute described using `attr_name` and `attr_value`. If another attribute with
2104/// the same name already existed, its value will be replaced with a provided one.
2105///
2106/// Both `attr_name` and `attr_value` must be a null-terminated UTF-8 encoded strings. Their
2107/// contents are being copied, therefore it's up to a function caller to properly release them.
2108#[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/// Removes an attribute from a current `YXmlElement`, given its name.
2132///
2133/// An `attr_name`must be a null-terminated UTF-8 encoded string.
2134#[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/// Returns the value of a current `YXmlElement`, given its name, or a null pointer if not attribute
2155/// with such name has been found. Returned pointer is a null-terminated UTF-8 encoded string, which
2156/// should be released using [ystring_destroy] function.
2157///
2158/// An `attr_name` must be a null-terminated UTF-8 encoded string.
2159#[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/// Returns an iterator over the `YXmlElement` attributes.
2182///
2183/// Use [yxmlattr_iter_next] function in order to retrieve a consecutive (**unordered**) attributes.
2184/// Use [yxmlattr_iter_destroy] function in order to close the iterator and release its resources.
2185#[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/// Returns an iterator over the `YXmlText` attributes.
2199///
2200/// Use [yxmlattr_iter_next] function in order to retrieve a consecutive (**unordered**) attributes.
2201/// Use [yxmlattr_iter_destroy] function in order to close the iterator and release its resources.
2202#[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/// Releases all of attributes iterator resources created by calling [yxmlelem_attr_iter]
2216/// or [yxmltext_attr_iter].
2217#[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/// Returns a next XML attribute from an `iterator`. Attributes are returned in an unordered
2225/// manner. Once `iterator` reaches the end of attributes collection, a null pointer will be
2226/// returned.
2227///
2228/// Returned value should be eventually released using [yxmlattr_destroy].
2229#[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/// Returns a next sibling of a current XML node, which can be either another `YXmlElement`
2246/// or a `YXmlText`. Together with [yxmlelem_first_child] it may be used to iterate over the direct
2247/// children of an XML node (in order to iterate over the nested XML structure use
2248/// [yxmlelem_tree_walker]).
2249///
2250/// If current `YXmlElement` is the last child, this function returns a null pointer.
2251/// A returned value should be eventually released using [youtput_destroy] function.
2252#[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/// Returns a previous sibling of a current XML node, which can be either another `YXmlElement`
2276/// or a `YXmlText`.
2277///
2278/// If current `YXmlElement` is the first child, this function returns a null pointer.
2279/// A returned value should be eventually released using [youtput_destroy] function.
2280#[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/// Returns a parent `YXmlElement` of a current node, or null pointer when current `YXmlElement` is
2304/// a root-level shared data type.
2305#[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/// Returns a number of child nodes (both `YXmlElement` and `YXmlText`) living under a current XML
2320/// element. This function doesn't count a recursive nodes, only direct children of a current node.
2321#[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/// Returns a first child node of a current `YXmlElement`, or null pointer if current XML node is
2333/// empty. Returned value could be either another `YXmlElement` or `YXmlText`.
2334///
2335/// A returned value should be eventually released using [youtput_destroy] function.
2336#[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/// Returns an iterator over a nested recursive structure of a current `YXmlElement`, starting from
2354/// first of its children. Returned values can be either `YXmlElement` or `YXmlText` nodes.
2355///
2356/// Use [yxmlelem_tree_walker_next] function in order to iterate over to a next node.
2357/// Use [yxmlelem_tree_walker_destroy] function to release resources used by the iterator.
2358#[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/// Releases resources associated with a current XML tree walker iterator.
2372#[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/// Moves current `iterator` to a next value (either `YXmlElement` or `YXmlText`), returning its
2380/// pointer or a null, if an `iterator` already reached the last successor node.
2381///
2382/// Values returned by this function should be eventually released using [youtput_destroy].
2383#[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/// Inserts an `YXmlElement` as a child of a current node at the given `index` and returns its
2401/// pointer. Node created this way will have a given `name` as its tag (eg. `p` for `<p></p>` node).
2402///
2403/// An `index` value must be between 0 and (inclusive) length of a current XML element (use
2404/// [yxmlelem_child_len] function to determine its length).
2405///
2406/// A `name` must be a null-terminated UTF-8 encoded string, which will be copied into current
2407/// document. Therefore `name` should be freed by the function caller.
2408#[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/// Inserts an `YXmlText` as a child of a current node at the given `index` and returns its
2431/// pointer.
2432///
2433/// An `index` value must be between 0 and (inclusive) length of a current XML element (use
2434/// [yxmlelem_child_len] function to determine its length).
2435#[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/// Removes a consecutive range of child elements (of specified length) from the current
2454/// `YXmlElement`, starting at the given `index`. Specified range must fit into boundaries of current
2455/// XML node children, otherwise this function will panic at runtime.
2456#[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/// Returns an XML child node (either a `YXmlElement` or `YXmlText`) stored at a given `index` of
2476/// a current `YXmlElement`. Returns null pointer if `index` was outside of the bound of current XML
2477/// node children.
2478///
2479/// Returned value should be eventually released using [youtput_destroy].
2480#[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/// Returns the length of the `YXmlText` string content in bytes (without the null terminator
2504/// character)
2505#[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/// Returns a null-terminated UTF-8 encoded string content of a current `YXmlText` shared data type.
2517///
2518/// Generated string resources should be released using [ystring_destroy] function.
2519#[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/// Inserts a null-terminated UTF-8 encoded string a a given `index`. `index` value must be between
2535/// 0 and a length of a `YXmlText` (inclusive, accordingly to [yxmltext_len] return value), otherwise
2536/// this function will panic.
2537///
2538/// A `str` parameter must be a null-terminated UTF-8 encoded string. This function doesn't take
2539/// ownership over a passed value - it will be copied and therefore a string parameter must be
2540/// released by the caller.
2541///
2542/// A nullable pointer with defined `attrs` will be used to wrap provided text with
2543/// a formatting blocks. `attrs` must be a map-like type.
2544#[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/// Inserts an embed content given `index`. `index` value must be between 0 and a length of a
2575/// `YXmlText` (inclusive, accordingly to [ytext_len] return value), otherwise this
2576/// function will panic.
2577///
2578/// A `str` parameter must be a null-terminated UTF-8 encoded string. This function doesn't take
2579/// ownership over a passed value - it will be copied and therefore a string parameter must be
2580/// released by the caller.
2581///
2582/// A nullable pointer with defined `attrs` will be used to wrap provided text with
2583/// a formatting blocks. `attrs` must be a map-like type.
2584#[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/// Wraps an existing piece of text within a range described by `index`-`len` parameters with
2615/// formatting blocks containing provided `attrs` metadata. `attrs` must be a map-like type.
2616#[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/// Removes a range of characters, starting a a given `index`. This range must fit within the bounds
2643/// of a current `YXmlText`, otherwise this function call will fail.
2644///
2645/// An `index` value must be between 0 and the length of a `YXmlText` (exclusive, accordingly to
2646/// [yxmltext_len] return value).
2647///
2648/// A `length` must be lower or equal number of characters (counted as UTF chars depending on the
2649/// encoding configured by `YDoc`) from `index` position to the end of of the string.
2650#[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/// Inserts an XML attribute described using `attr_name` and `attr_value`. If another attribute with
2669/// the same name already existed, its value will be replaced with a provided one.
2670///
2671/// Both `attr_name` and `attr_value` must be a null-terminated UTF-8 encoded strings. Their
2672/// contents are being copied, therefore it's up to a function caller to properly release them.
2673#[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/// Removes an attribute from a current `YXmlText`, given its name.
2697///
2698/// An `attr_name`must be a null-terminated UTF-8 encoded string.
2699#[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/// Returns the value of a current `YXmlText`, given its name, or a null pointer if not attribute
2720/// with such name has been found. Returned pointer is a null-terminated UTF-8 encoded string, which
2721/// should be released using [ystring_destroy] function.
2722///
2723/// An `attr_name` must be a null-terminated UTF-8 encoded string.
2724#[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/// Returns a collection of chunks representing pieces of `YText` rich text string grouped together
2747/// by the same formatting rules and type. `chunks_len` is used to inform about a number of chunks
2748/// generated this way.
2749///
2750/// Returned array needs to be eventually deallocated using `ychunks_destroy`.
2751#[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/// Deallocates result of `ytext_chunks` method.
2771#[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/// A chunk of text contents formatted with the same set of attributes.
2781#[repr(C)]
2782pub struct YChunk {
2783    /// Piece of YText formatted using the same `fmt` rules. It can be a string, embedded object
2784    /// or another y-type.
2785    pub data: YOutput,
2786    /// Number of formatting attributes attached to current chunk of text.
2787    pub fmt_len: u32,
2788    /// The formatting attributes attached to the current chunk of text.
2789    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); //TODO: test if we don't drop memory here
2801                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/// A data structure that is used to pass input values of various types supported by Yrs into a
2823/// shared document store.
2824///
2825/// `YInput` constructor function don't allocate any resources on their own, neither they take
2826/// ownership by pointers to memory blocks allocated by user - for this reason once an input cell
2827/// has been used, its content should be freed by the caller.
2828#[repr(C)]
2829pub struct YInput {
2830    /// Tag describing, which `value` type is being stored by this input cell. Can be one of:
2831    ///
2832    /// - [Y_JSON] for a UTF-8 encoded, NULL-terminated JSON string.
2833    /// - [Y_JSON_BOOL] for boolean flags.
2834    /// - [Y_JSON_NUM] for 64-bit floating point numbers.
2835    /// - [Y_JSON_INT] for 64-bit signed integers.
2836    /// - [Y_JSON_STR] for null-terminated UTF-8 encoded strings.
2837    /// - [Y_JSON_BUF] for embedded binary data.
2838    /// - [Y_JSON_ARR] for arrays of JSON-like values.
2839    /// - [Y_JSON_MAP] for JSON-like objects build from key-value pairs.
2840    /// - [Y_JSON_NULL] for JSON-like null values.
2841    /// - [Y_JSON_UNDEF] for JSON-like undefined values.
2842    /// - [Y_ARRAY] for cells which contents should be used to initialize a `YArray` shared type.
2843    /// - [Y_MAP] for cells which contents should be used to initialize a `YMap` shared type.
2844    /// - [Y_DOC] for cells which contents should be used to nest a `YDoc` sub-document.
2845    /// - [Y_WEAK_LINK] for cells which contents should be used to nest a `YWeakLink` sub-document.
2846    pub tag: i8,
2847
2848    /// Length of the contents stored by current `YInput` cell.
2849    ///
2850    /// For [Y_JSON_NULL] and [Y_JSON_UNDEF] its equal to `0`.
2851    ///
2852    /// For [Y_JSON_ARR], [Y_JSON_MAP], [Y_ARRAY] and [Y_MAP] it describes a number of passed
2853    /// elements.
2854    ///
2855    /// For other types it's always equal to `1`.
2856    pub len: u32,
2857
2858    /// Union struct which contains a content corresponding to a provided `tag` field.
2859    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                _ => { /* do nothing */ }
3026            }
3027        }
3028    }
3029}
3030
3031/// An output value cell returned from yrs API methods. It describes a various types of data
3032/// supported by yrs shared data types.
3033///
3034/// Since `YOutput` instances are always created by calling the corresponding yrs API functions,
3035/// they eventually should be deallocated using [youtput_destroy] function.
3036#[repr(C)]
3037pub struct YOutput {
3038    /// Tag describing, which `value` type is being stored by this input cell. Can be one of:
3039    ///
3040    /// - [Y_JSON_BOOL] for boolean flags.
3041    /// - [Y_JSON_NUM] for 64-bit floating point numbers.
3042    /// - [Y_JSON_INT] for 64-bit signed integers.
3043    /// - [Y_JSON_STR] for null-terminated UTF-8 encoded strings.
3044    /// - [Y_JSON_BUF] for embedded binary data.
3045    /// - [Y_JSON_ARR] for arrays of JSON-like values.
3046    /// - [Y_JSON_MAP] for JSON-like objects build from key-value pairs.
3047    /// - [Y_JSON_NULL] for JSON-like null values.
3048    /// - [Y_JSON_UNDEF] for JSON-like undefined values.
3049    /// - [Y_TEXT] for pointers to `YText` data types.
3050    /// - [Y_ARRAY] for pointers to `YArray` data types.
3051    /// - [Y_MAP] for pointers to `YMap` data types.
3052    /// - [Y_XML_ELEM] for pointers to `YXmlElement` data types.
3053    /// - [Y_XML_TEXT] for pointers to `YXmlText` data types.
3054    /// - [Y_DOC] for pointers to nested `YDocRef` data types.
3055    pub tag: i8,
3056
3057    /// Length of the contents stored by a current `YOutput` cell.
3058    ///
3059    /// For [Y_JSON_NULL] and [Y_JSON_UNDEF] its equal to `0`.
3060    ///
3061    /// For [Y_JSON_ARR], [Y_JSON_MAP] it describes a number of passed elements.
3062    ///
3063    /// For other types it's always equal to `1`.
3064    pub len: u32,
3065
3066    /// Union struct which contains a content corresponding to a provided `tag` field.
3067    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                    // while we were using Box<[u8]>, for deallocation this should work
3167                    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                _ => { /* ignore */ }
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/// Releases all resources related to a corresponding `YOutput` cell.
3458#[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/// Function constructor used to create JSON-like NULL `YInput` cell.
3466/// This function doesn't allocate any heap resources.
3467#[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/// Function constructor used to create JSON-like undefined `YInput` cell.
3477/// This function doesn't allocate any heap resources.
3478#[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/// Function constructor used to create JSON-like boolean `YInput` cell.
3488/// This function doesn't allocate any heap resources.
3489#[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/// Function constructor used to create JSON-like 64-bit floating point number `YInput` cell.
3499/// This function doesn't allocate any heap resources.
3500#[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/// Function constructor used to create JSON-like 64-bit signed integer `YInput` cell.
3510/// This function doesn't allocate any heap resources.
3511#[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/// Function constructor used to create a string `YInput` cell. Provided parameter must be
3521/// a null-terminated UTF-8 encoded string. This function doesn't allocate any heap resources,
3522/// and doesn't release any on its own, therefore its up to a caller to free resources once
3523/// a structure is no longer needed.
3524#[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/// Function constructor used to create aa `YInput` cell representing any JSON-like object.
3536/// Provided parameter must be a null-terminated UTF-8 encoded JSON string.
3537///
3538/// This function doesn't allocate any heap resources and doesn't release any on its own, therefore
3539/// its up to a caller to free resources once a structure is no longer needed.
3540#[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/// Function constructor used to create a binary `YInput` cell of a specified length.
3552/// This function doesn't allocate any heap resources and doesn't release any on its own, therefore
3553/// its up to a caller to free resources once a structure is no longer needed.
3554#[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/// Function constructor used to create a JSON-like array `YInput` cell of other JSON-like values of
3566/// a given length. This function doesn't allocate any heap resources and doesn't release any on its
3567/// own, therefore its up to a caller to free resources once a structure is no longer needed.
3568#[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/// Function constructor used to create a JSON-like map `YInput` cell of other JSON-like key-value
3578/// pairs. These pairs are build from corresponding indexes of `keys` and `values`, which must have
3579/// the same specified length.
3580///
3581/// This function doesn't allocate any heap resources and doesn't release any on its own, therefore
3582/// its up to a caller to free resources once a structure is no longer needed.
3583#[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/// Function constructor used to create a nested `YArray` `YInput` cell prefilled with other
3599/// values of a given length. This function doesn't allocate any heap resources and doesn't release
3600/// any on its own, therefore its up to a caller to free resources once a structure is no longer
3601/// needed.
3602#[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/// Function constructor used to create a nested `YMap` `YInput` cell prefilled with other key-value
3612/// pairs. These pairs are build from corresponding indexes of `keys` and `values`, which must have
3613/// the same specified length.
3614///
3615/// This function doesn't allocate any heap resources and doesn't release any on its own, therefore
3616/// its up to a caller to free resources once a structure is no longer needed.
3617#[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/// Function constructor used to create a nested `YText` `YInput` cell prefilled with a specified
3633/// string, which must be a null-terminated UTF-8 character pointer.
3634///
3635/// This function doesn't allocate any heap resources and doesn't release any on its own, therefore
3636/// its up to a caller to free resources once a structure is no longer needed.
3637#[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/// Function constructor used to create a nested `YXmlElement` `YInput` cell with a specified
3647/// tag name, which must be a null-terminated UTF-8 character pointer.
3648///
3649/// This function doesn't allocate any heap resources and doesn't release any on its own, therefore
3650/// its up to a caller to free resources once a structure is no longer needed.
3651#[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/// Function constructor used to create a nested `YXmlText` `YInput` cell prefilled with a specified
3661/// string, which must be a null-terminated UTF-8 character pointer.
3662///
3663/// This function doesn't allocate any heap resources and doesn't release any on its own, therefore
3664/// its up to a caller to free resources once a structure is no longer needed.
3665#[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/// Function constructor used to create a nested `YDoc` `YInput` cell.
3675///
3676/// This function doesn't allocate any heap resources and doesn't release any on its own, therefore
3677/// its up to a caller to free resources once a structure is no longer needed.
3678#[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/// Function constructor used to create a string `YInput` cell with weak reference to another
3688/// element(s) living inside of the same document.
3689#[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/// Attempts to read the value for a given `YOutput` pointer as a `YDocRef` reference to a nested
3699/// document.
3700#[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/// Attempts to read the value for a given `YOutput` pointer as a boolean flag, which can be either
3711/// `1` for truthy case and `0` otherwise. Returns a null pointer in case when a value stored under
3712/// current `YOutput` cell is not of a boolean type.
3713#[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/// Attempts to read the value for a given `YOutput` pointer as a 64-bit floating point number.
3724///
3725/// Returns a null pointer in case when a value stored under current `YOutput` cell
3726/// is not a floating point number.
3727#[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/// Attempts to read the value for a given `YOutput` pointer as a 64-bit signed integer.
3738///
3739/// Returns a null pointer in case when a value stored under current `YOutput` cell
3740/// is not a signed integer.
3741#[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/// Attempts to read the value for a given `YOutput` pointer as a null-terminated UTF-8 encoded
3752/// string.
3753///
3754/// Returns a null pointer in case when a value stored under current `YOutput` cell
3755/// is not a string. Underlying string is released automatically as part of [youtput_destroy]
3756/// destructor.
3757#[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/// Attempts to read the value for a given `YOutput` pointer as a binary payload (which length is
3768/// stored within `len` filed of a cell itself).
3769///
3770/// Returns a null pointer in case when a value stored under current `YOutput` cell
3771/// is not a binary type. Underlying binary is released automatically as part of [youtput_destroy]
3772/// destructor.
3773#[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/// Attempts to read the value for a given `YOutput` pointer as a JSON-like array of `YOutput`
3784/// values (which length is stored within `len` filed of a cell itself).
3785///
3786/// Returns a null pointer in case when a value stored under current `YOutput` cell
3787/// is not a JSON-like array. Underlying heap resources are released automatically as part of
3788/// [youtput_destroy] destructor.
3789#[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/// Attempts to read the value for a given `YOutput` pointer as a JSON-like map of key-value entries
3800/// (which length is stored within `len` filed of a cell itself).
3801///
3802/// Returns a null pointer in case when a value stored under current `YOutput` cell
3803/// is not a JSON-like map. Underlying heap resources are released automatically as part of
3804/// [youtput_destroy] destructor.
3805#[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/// Attempts to read the value for a given `YOutput` pointer as an `YArray`.
3816///
3817/// Returns a null pointer in case when a value stored under current `YOutput` cell
3818/// is not an `YArray`. Underlying heap resources are released automatically as part of
3819/// [youtput_destroy] destructor.
3820#[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/// Attempts to read the value for a given `YOutput` pointer as an `YXmlElement`.
3831///
3832/// Returns a null pointer in case when a value stored under current `YOutput` cell
3833/// is not an `YXmlElement`. Underlying heap resources are released automatically as part of
3834/// [youtput_destroy] destructor.
3835#[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/// Attempts to read the value for a given `YOutput` pointer as an `YMap`.
3846///
3847/// Returns a null pointer in case when a value stored under current `YOutput` cell
3848/// is not an `YMap`. Underlying heap resources are released automatically as part of
3849/// [youtput_destroy] destructor.
3850#[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/// Attempts to read the value for a given `YOutput` pointer as an `YText`.
3861///
3862/// Returns a null pointer in case when a value stored under current `YOutput` cell
3863/// is not an `YText`. Underlying heap resources are released automatically as part of
3864/// [youtput_destroy] destructor.
3865#[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/// Attempts to read the value for a given `YOutput` pointer as an `YXmlText`.
3876///
3877/// Returns a null pointer in case when a value stored under current `YOutput` cell
3878/// is not an `YXmlText`. Underlying heap resources are released automatically as part of
3879/// [youtput_destroy] destructor.
3880#[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/// Attempts to read the value for a given `YOutput` pointer as an `YWeakRef`.
3891///
3892/// Returns a null pointer in case when a value stored under current `YOutput` cell
3893/// is not an `YWeakRef`. Underlying heap resources are released automatically as part of
3894/// [youtput_destroy] destructor.
3895#[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/// Unsubscribes a shallow observer callback registered under a given `key` on any shared type.
3906/// Returns 1 if a callback was removed, 0 otherwise.
3907#[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/// Unsubscribes a deep observer callback registered under a given `key` on any shared type.
3916/// Returns 1 if a callback was removed, 0 otherwise.
3917#[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/// Subscribes a given callback function `cb` under a `key` to changes made by this `YText`
3930/// instance. Callbacks are triggered whenever a `ytransaction_commit` is called.
3931/// Use `yunobserve` with the same key to unsubscribe.
3932#[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/// Subscribes a given callback function `cb` under a `key` to changes made by this `YMap`
3951/// instance. Callbacks are triggered whenever a `ytransaction_commit` is called.
3952/// Use `yunobserve` with the same key to unsubscribe.
3953#[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/// Subscribes a given callback function `cb` under a `key` to changes made by this `YArray`
3972/// instance. Callbacks are triggered whenever a `ytransaction_commit` is called.
3973/// Use `yunobserve` with the same key to unsubscribe.
3974#[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/// Subscribes a given callback function `cb` under a `key` to changes made by this `YXmlElement`
3993/// instance. Callbacks are triggered whenever a `ytransaction_commit` is called.
3994/// Use `yunobserve` with the same key to unsubscribe.
3995#[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/// Subscribes a given callback function `cb` under a `key` to changes made by this `YXmlText`
4014/// instance. Callbacks are triggered whenever a `ytransaction_commit` is called.
4015/// Use `yunobserve` with the same key to unsubscribe.
4016#[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/// Subscribes a given callback function `cb` under a `key` to changes made by this shared type
4035/// instance as well as all nested shared types living within it. Callbacks are triggered whenever
4036/// a `ytransaction_commit` is called. Use `yunobserve_deep` with the same key to unsubscribe.
4037#[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/// Event generated for callbacks subscribed using `ytransaction_observe_after_transaction`. It contains
4058/// snapshot of changes made within any committed transaction.
4059#[repr(C)]
4060pub struct YAfterTransactionEvent {
4061    /// Descriptor of a document state at the moment of creating the transaction.
4062    pub before_state: YStateVector,
4063    /// Descriptor of a document state at the moment of committing the transaction.
4064    pub after_state: YStateVector,
4065    /// Information about all items deleted within the scope of a transaction.
4066    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/// Struct representing a state of a document. It contains the last seen clocks for blocks submitted
4132/// per any of the clients collaborating on document updates.
4133#[repr(C)]
4134pub struct YStateVector {
4135    /// Number of clients. It describes a length of both `client_ids` and `clocks` arrays.
4136    pub entries_count: u32,
4137    /// Array of unique client identifiers (length is given in `entries_count` field). Each client
4138    /// ID has corresponding clock attached, which can be found in `clocks` field under the same
4139    /// index.
4140    pub client_ids: *mut u64,
4141    /// Array of clocks (length is given in `entries_count` field) known for each client. Each clock
4142    /// has a corresponding client identifier attached, which can be found in `client_ids` field
4143    /// under the same index.
4144    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/// Delete set is a map of `(ClientID, Range[])` entries. Length of a map is stored in
4174/// `entries_count` field. ClientIDs reside under `client_ids` and their corresponding range
4175/// sequences can be found under the same index of `ranges` field.
4176#[repr(C)]
4177pub struct YIdSet {
4178    /// Number of client identifier entries.
4179    pub entries_count: u32,
4180    /// Array of unique client identifiers (length is given in `entries_count` field). Each client
4181    /// ID has corresponding sequence of ranges attached, which can be found in `ranges` field under
4182    /// the same index.
4183    pub client_ids: *mut u64,
4184    /// Array of range sequences (length is given in `entries_count` field). Each sequence has
4185    /// a corresponding client ID attached, which can be found in `client_ids` field under
4186    /// the same index.
4187    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/// Fixed-length sequence of ID ranges. Each range is a pair of [start, end) values, describing the
4228/// range of items identified by clock values, that this range refers to.
4229#[repr(C)]
4230pub struct YIdRangeSeq {
4231    /// Number of ranges stored in this sequence.
4232    pub len: u32,
4233    /// Array (length is stored in `len` field) or ranges. Each range is a pair of [start, end)
4234    /// values, describing continuous collection of items produced by the same client, identified
4235    /// by clock values, that this range refers to.
4236    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    /// Tag describing, which shared type emitted this event.
4255    ///
4256    /// - [Y_TEXT] for pointers to `YText` data types.
4257    /// - [Y_ARRAY] for pointers to `YArray` data types.
4258    /// - [Y_MAP] for pointers to `YMap` data types.
4259    /// - [Y_XML_ELEM] for pointers to `YXmlElement` data types.
4260    /// - [Y_XML_TEXT] for pointers to `YXmlText` data types.
4261    pub tag: i8,
4262
4263    /// A nested event type, specific for a shared data type that triggered it. Type of an
4264    /// event can be verified using `tag` field.
4265    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/// Event pushed into callbacks registered with `ytext_observe` function. It contains delta of all
4326/// text changes made within a scope of corresponding transaction (see: `ytext_event_delta`) as
4327/// well as navigation data used to identify a `YText` instance which triggered this event.
4328#[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/// Event pushed into callbacks registered with `yarray_observe` function. It contains delta of all
4357/// content changes made within a scope of corresponding transaction (see: `yarray_event_delta`) as
4358/// well as navigation data used to identify a `YArray` instance which triggered this event.
4359#[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/// Event pushed into callbacks registered with `ymap_observe` function. It contains all
4388/// key-value changes made within a scope of corresponding transaction (see: `ymap_event_keys`) as
4389/// well as navigation data used to identify a `YMap` instance which triggered this event.
4390#[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/// Event pushed into callbacks registered with `yxmlelem_observe` function. It contains
4419/// all attribute changes made within a scope of corresponding transaction
4420/// (see: `yxmlelem_event_keys`) as well as child XML nodes changes (see: `yxmlelem_event_delta`)
4421/// and navigation data used to identify a `YXmlElement` instance which triggered this event.
4422#[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/// Event pushed into callbacks registered with `yxmltext_observe` function. It contains
4451/// all attribute changes made within a scope of corresponding transaction
4452/// (see: `yxmltext_event_keys`) as well as text edits (see: `yxmltext_event_delta`)
4453/// and navigation data used to identify a `YXmlText` instance which triggered this event.
4454#[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/// Event pushed into callbacks registered with `yweak_observe` function. It contains
4483/// all an event changes of the underlying transaction.
4484#[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/// Returns a pointer to a shared collection, which triggered passed event `e`.
4509#[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/// Returns a pointer to a shared collection, which triggered passed event `e`.
4517#[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/// Returns a pointer to a shared collection, which triggered passed event `e`.
4525#[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/// Returns a pointer to a shared collection, which triggered passed event `e`.
4533#[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/// Returns a pointer to a shared collection, which triggered passed event `e`.
4545#[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/// Returns a path from a root type down to a current shared collection (which can be obtained using
4553/// `ytext_event_target` function). It can consist of either integer indexes (used by sequence
4554/// components) or *char keys (used by map components). `len` output parameter is used to provide
4555/// information about length of the path.
4556///
4557/// Path returned this way should be eventually released using `ypath_destroy`.
4558#[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/// Returns a path from a root type down to a current shared collection (which can be obtained using
4572/// `ymap_event_target` function). It can consist of either integer indexes (used by sequence
4573/// components) or *char keys (used by map components). `len` output parameter is used to provide
4574/// information about length of the path.
4575///
4576/// Path returned this way should be eventually released using `ypath_destroy`.
4577#[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/// Returns a path from a root type down to a current shared collection (which can be obtained using
4588/// `yxmlelem_event_path` function). It can consist of either integer indexes (used by sequence
4589/// components) or *char keys (used by map components). `len` output parameter is used to provide
4590/// information about length of the path.
4591///
4592/// Path returned this way should be eventually released using `ypath_destroy`.
4593#[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/// Returns a path from a root type down to a current shared collection (which can be obtained using
4607/// `yxmltext_event_path` function). It can consist of either integer indexes (used by sequence
4608/// components) or *char keys (used by map components). `len` output parameter is used to provide
4609/// information about length of the path.
4610///
4611/// Path returned this way should be eventually released using `ypath_destroy`.
4612#[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/// Returns a path from a root type down to a current shared collection (which can be obtained using
4626/// `yarray_event_target` function). It can consist of either integer indexes (used by sequence
4627/// components) or *char keys (used by map components). `len` output parameter is used to provide
4628/// information about length of the path.
4629///
4630/// Path returned this way should be eventually released using `ypath_destroy`.
4631#[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/// Releases allocated memory used by objects returned from path accessor functions of shared type
4645/// events.
4646#[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/// Returns a sequence of changes produced by sequence component of shared collections (such as
4654/// `YText`, `YXmlText` and XML nodes added to `YXmlElement`). `len` output parameter is used to
4655/// provide information about number of changes produced.
4656///
4657/// Delta returned from this function should eventually be released using `ytext_delta_destroy`
4658/// function.
4659#[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/// Returns a sequence of changes produced by sequence component of shared collections (such as
4671/// `YText`, `YXmlText` and XML nodes added to `YXmlElement`). `len` output parameter is used to
4672/// provide information about number of changes produced.
4673///
4674/// Delta returned from this function should eventually be released using `ytext_delta_destroy`
4675/// function.
4676#[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/// Returns a sequence of changes produced by sequence component of shared collections (such as
4691/// `YText`, `YXmlText` and XML nodes added to `YXmlElement`). `len` output parameter is used to
4692/// provide information about number of changes produced.
4693///
4694/// Delta returned from this function should eventually be released using `yevent_delta_destroy`
4695/// function.
4696#[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/// Returns a sequence of changes produced by sequence component of shared collections (such as
4715/// `YText`, `YXmlText` and XML nodes added to `YXmlElement`). `len` output parameter is used to
4716/// provide information about number of changes produced.
4717///
4718/// Delta returned from this function should eventually be released using `yevent_delta_destroy`
4719/// function.
4720#[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/// Releases memory allocated by the object returned from `ytext_delta` function.
4739#[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/// Releases memory allocated by the object returned from `yevent_delta` function.
4748#[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/// Returns a sequence of changes produced by map component of shared collections (such as
4757/// `YMap` and `YXmlText`/`YXmlElement` attribute changes). `len` output parameter is used to
4758/// provide information about number of changes produced.
4759///
4760/// Delta returned from this function should eventually be released using `yevent_keys_destroy`
4761/// function.
4762#[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/// Returns a sequence of changes produced by map component of shared collections.
4781/// `len` output parameter is used to provide information about number of changes produced.
4782///
4783/// Delta returned from this function should eventually be released using `yevent_keys_destroy`
4784/// function.
4785#[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/// Returns a sequence of changes produced by map component of shared collections.
4804/// `len` output parameter is used to provide information about number of changes produced.
4805///
4806/// Delta returned from this function should eventually be released using `yevent_keys_destroy`
4807/// function.
4808#[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/// Releases memory allocated by the object returned from `yxml_event_keys` and `ymap_event_keys`
4827/// functions.
4828#[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// TODO [LSViana] Maybe rename this to `yundo_manager_new_with_options` to match `ydoc_new_with_options`?
4843/// Creates a new instance of undo manager bound to a current `doc`. It can be used to track
4844/// specific shared refs via `yundo_manager_add_scope` and updates coming from specific origin
4845/// - like ability to undo/redo operations originating only at the local peer - by using
4846/// `yundo_manager_add_origin`.
4847///
4848/// This object can be deallocated via `yundo_manager_destroy`.
4849#[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/// Deallocated undo manager instance created via `yundo_manager`.
4862#[no_mangle]
4863pub unsafe extern "C" fn yundo_manager_destroy(mgr: *mut YUndoManager) {
4864    drop(Box::from_raw(mgr));
4865}
4866
4867/// Adds an origin to be tracked by current undo manager. This way only changes made within context
4868/// of transactions created with specific origin will be subjects of undo/redo operations. This is
4869/// useful when you want to be able to revert changed done by specific user without reverting
4870/// changes made by other users that were applied in the meantime.
4871#[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/// Removes an origin previously added to undo manager via `yundo_manager_add_origin`.
4883#[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/// Add specific shared type to be tracked by this instance of an undo manager.
4895#[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/// Removes all the undo/redo stack changes tracked by current undo manager. This also cleans up
4908/// all the items that couldn't be deallocated / garbage collected for the sake of possible
4909/// undo/redo operations.
4910///
4911/// Keep in mind that this function call requires that underlying document store is not concurrently
4912/// modified by other read-write transaction. This is done by acquiring the read-only transaction
4913/// itself. If such transaction could be acquired (because of another read-write transaction is in
4914/// progress, this function will hold current thread until acquisition is possible.
4915#[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/// Cuts off tracked changes, producing a new stack item on undo stack.
4922///
4923/// By default, undo manager gathers undergoing changes together into undo stack items on periodic
4924/// basis (defined by `YUndoManagerOptions.capture_timeout_millis`). By calling this function, we're
4925/// explicitly creating a new stack item will all the changes registered since last stack item was
4926/// created.
4927#[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/// Performs an undo operations, reverting all the changes defined by the last undo stack item.
4934/// These changes can be then reapplied again by calling `yundo_manager_redo` function.
4935///
4936/// Returns `Y_TRUE` if successfully managed to do an undo operation.
4937/// Returns `Y_FALSE` if undo stack was empty or if undo couldn't be performed (because another
4938/// transaction is in progress).
4939#[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/// Performs a redo operations, reapplying changes undone by `yundo_manager_undo` operation.
4951///
4952/// Returns `Y_TRUE` if successfully managed to do a redo operation.
4953/// Returns `Y_FALSE` if redo stack was empty or if redo couldn't be performed (because another
4954/// transaction is in progress).
4955#[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/// Returns number of elements stored on undo stack.
4966#[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/// Returns number of elements stored on redo stack.
4973#[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/// Subscribes a `callback` function pointer under a `key` to a given undo manager event. This event
4980/// will be triggered every time a new undo/redo stack item is added.
4981/// Use `yundo_manager_unobserve_added` with the same key to unsubscribe.
4982#[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/// Unsubscribes a callback registered under a given `key` via `yundo_manager_observe_added`.
5003/// Returns 1 if a callback was removed, 0 otherwise.
5004#[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/// Subscribes a `callback` function pointer under a `key` to a given undo manager event. This event
5015/// will be triggered every time a undo/redo operation was called.
5016/// Use `yundo_manager_unobserve_popped` with the same key to unsubscribe.
5017#[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/// Unsubscribes a callback registered under a given `key` via `yundo_manager_observe_popped`.
5038/// Returns 1 if a callback was removed, 0 otherwise.
5039#[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/// Event type related to `UndoManager` observer operations, such as `yundo_manager_observe_popped`
5053/// and `yundo_manager_observe_added`. It contains various informations about the context in which
5054/// undo/redo operations are executed.
5055#[repr(C)]
5056pub struct YUndoEvent {
5057    /// Informs if current event is related to executed undo (`Y_KIND_UNDO`) or redo (`Y_KIND_REDO`)
5058    /// operation.
5059    pub kind: c_char,
5060    /// Origin assigned to a transaction, in context of which this event is being executed.
5061    /// Transaction origin is specified via `ydoc_write_transaction(doc, origin_len, origin)`.
5062    pub origin: *const c_char,
5063    /// Length of an `origin` field assigned to a transaction, in context of which this event is
5064    /// being executed.
5065    /// Transaction origin is specified via `ydoc_write_transaction(doc, origin_len, origin)`.
5066    pub origin_len: u32,
5067    /// Pointer to a custom metadata object that can be passed between
5068    /// `yundo_manager_observe_popped` and `yundo_manager_observe_added`. It's useful for passing
5069    /// around custom user data ie. cursor position, that needs to be remembered and restored as
5070    /// part of undo/redo operations.
5071    ///
5072    /// This field always starts with no value (`NULL`) assigned to it and can be set/unset in
5073    /// corresponding callback calls. In such cases it's up to a programmer to handle allocation
5074    /// and deallocation of memory that this pointer will point to. Not releasing it properly may
5075    /// lead to memory leaks.
5076    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/// Returns a value informing what kind of Yrs shared collection given `branch` represents.
5102/// Returns either 0 when `branch` is null or one of values: `Y_ARRAY`, `Y_TEXT`, `Y_MAP`,
5103/// `Y_XML_ELEM`, `Y_XML_TEXT`.
5104#[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
5124/// Tag used to identify `YPathSegment` storing a *char parameter.
5125pub const Y_EVENT_PATH_KEY: c_char = 1;
5126
5127/// Tag used to identify `YPathSegment` storing an int parameter.
5128pub const Y_EVENT_PATH_INDEX: c_char = 2;
5129
5130/// A single segment of a path returned from `yevent_path` function. It can be one of two cases,
5131/// recognized by it's `tag` field:
5132///
5133/// 1. `Y_EVENT_PATH_KEY` means that segment value can be accessed by `segment.value.key` and is
5134/// referring to a string key used by map component (eg. `YMap` entry).
5135/// 2. `Y_EVENT_PATH_INDEX` means that segment value can be accessed by `segment.value.index` and is
5136/// referring to an int index used by sequence component (eg. `YArray` item or `YXmlElement` child).
5137#[repr(C)]
5138pub struct YPathSegment {
5139    /// Tag used to identify which case current segment is referring to:
5140    ///
5141    /// 1. `Y_EVENT_PATH_KEY` means that segment value can be accessed by `segment.value.key` and is
5142    /// referring to a string key used by map component (eg. `YMap` entry).
5143    /// 2. `Y_EVENT_PATH_INDEX` means that segment value can be accessed by `segment.value.index`
5144    /// and is referring to an int index used by sequence component (eg. `YArray` item or
5145    /// `YXmlElement` child).
5146    pub tag: c_char,
5147
5148    /// Union field containing either `key` or `index`. A particular case can be recognized by using
5149    /// segment's `tag` field.
5150    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
5189/// Tag used to identify `YEventChange` (see: `yevent_delta` function) case, when a new element
5190/// has been added to an observed collection.
5191pub const Y_EVENT_CHANGE_ADD: u8 = 1;
5192
5193/// Tag used to identify `YEventChange` (see: `yevent_delta` function) case, when an existing
5194/// element has been removed from an observed collection.
5195pub const Y_EVENT_CHANGE_DELETE: u8 = 2;
5196
5197/// Tag used to identify `YEventChange` (see: `yevent_delta` function) case, when no changes have
5198/// been detected for a particular range of observed collection.
5199pub const Y_EVENT_CHANGE_RETAIN: u8 = 3;
5200
5201/// A data type representing a single change detected over an observed shared collection. A type
5202/// of change can be detected using a `tag` field:
5203///
5204/// 1. `Y_EVENT_CHANGE_ADD` marks a new elements added to a collection. In this case `values` field
5205/// contains a pointer to a list of newly inserted values, while `len` field informs about their
5206/// count.
5207/// 2. `Y_EVENT_CHANGE_DELETE` marks an existing elements removed from the collection. In this case
5208/// `len` field informs about number of removed elements.
5209/// 3. `Y_EVENT_CHANGE_RETAIN` marks a number of elements that have not been changed, counted from
5210/// the previous element. `len` field informs about number of retained elements.
5211///
5212/// A list of changes returned by `yarray_event_delta`/`yxml_event_delta` enables to locate a
5213/// position of all changes within an observed collection by using a combination of added/deleted
5214/// change structs separated by retained changes (marking eg. number of elements that can be safely
5215/// skipped, since they remained unchanged).
5216#[repr(C)]
5217pub struct YEventChange {
5218    /// Tag field used to identify particular type of change made:
5219    ///
5220    /// 1. `Y_EVENT_CHANGE_ADD` marks a new elements added to a collection. In this case `values`
5221    /// field contains a pointer to a list of newly inserted values, while `len` field informs about
5222    /// their count.
5223    /// 2. `Y_EVENT_CHANGE_DELETE` marks an existing elements removed from the collection. In this
5224    /// case `len` field informs about number of removed elements.
5225    /// 3. `Y_EVENT_CHANGE_RETAIN` marks a number of elements that have not been changed, counted
5226    /// from the previous element. `len` field informs about number of retained elements.
5227    pub tag: u8,
5228
5229    /// Number of element affected by current type of a change. It can refer to a number of
5230    /// inserted `values`, number of deleted element or a number of retained (unchanged) values.
5231    pub len: u32,
5232
5233    /// Used in case when current change is of `Y_EVENT_CHANGE_ADD` type. Contains a list (of
5234    /// length stored in `len` field) of newly inserted values.
5235    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/// A data type representing a single change detected over an observed `YText`/`YXmlText`. A type
5283/// of change can be detected using a `tag` field:
5284///
5285/// 1. `Y_EVENT_CHANGE_ADD` marks a new characters added to a collection. In this case `insert`
5286/// field contains a pointer to a list of newly inserted values, while `len` field informs about
5287/// their count. Additionally `attributes_len` and `attributes` carry information about optional
5288/// formatting attributes applied to edited blocks.
5289/// 2. `Y_EVENT_CHANGE_DELETE` marks an existing elements removed from the collection. In this case
5290/// `len` field informs about number of removed elements.
5291/// 3. `Y_EVENT_CHANGE_RETAIN` marks a number of characters that have not been changed, counted from
5292/// the previous element. `len` field informs about number of retained elements. Additionally
5293/// `attributes_len` and `attributes` carry information about optional formatting attributes applied
5294/// to edited blocks.
5295///
5296/// A list of changes returned by `ytext_event_delta`/`yxmltext_event_delta` enables to locate
5297/// a position of all changes within an observed collection by using a combination of added/deleted
5298/// change structs separated by retained changes (marking eg. number of elements that can be safely
5299/// skipped, since they remained unchanged).
5300#[repr(C)]
5301pub struct YDeltaOut {
5302    /// Tag field used to identify particular type of change made:
5303    ///
5304    /// 1. `Y_EVENT_CHANGE_ADD` marks a new elements added to a collection. In this case `values`
5305    /// field contains a pointer to a list of newly inserted values, while `len` field informs about
5306    /// their count.
5307    /// 2. `Y_EVENT_CHANGE_DELETE` marks an existing elements removed from the collection. In this
5308    /// case `len` field informs about number of removed elements.
5309    /// 3. `Y_EVENT_CHANGE_RETAIN` marks a number of elements that have not been changed, counted
5310    /// from the previous element. `len` field informs about number of retained elements.
5311    pub tag: u8,
5312
5313    /// Number of element affected by current type of change. It can refer to a number of
5314    /// inserted `values`, number of deleted element or a number of retained (unchanged) values.
5315    pub len: u32,
5316
5317    /// A number of formatting attributes assigned to an edited area represented by this delta.
5318    pub attributes_len: u32,
5319
5320    /// A nullable pointer to a list of formatting attributes assigned to an edited area represented
5321    /// by this delta.
5322    pub attributes: *mut YDeltaAttr,
5323
5324    /// Used in case when current change is of `Y_EVENT_CHANGE_ADD` type. Contains a list (of
5325    /// length stored in `len` field) of newly inserted values.
5326    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/// A single instance of formatting attribute stored as part of `YDelta` instance.
5404#[repr(C)]
5405pub struct YDeltaAttr {
5406    /// A null-terminated UTF-8 encoded string containing a unique formatting attribute name.
5407    pub key: *const c_char,
5408    /// A value assigned to a formatting attribute.
5409    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/// A data type representing a single change to be performed in sequence of changes defined
5427/// as parameter to a `ytext_insert_delta` function. A type of change can be detected using
5428/// a `tag` field:
5429///
5430/// 1. `Y_EVENT_CHANGE_ADD` marks a new characters added to a collection. In this case `insert`
5431/// field contains a pointer to a list of newly inserted values, while `len` field informs about
5432/// their count. Additionally `attributes_len` and `attributes` carry information about optional
5433/// formatting attributes applied to edited blocks.
5434/// 2. `Y_EVENT_CHANGE_DELETE` marks an existing elements removed from the collection. In this case
5435/// `len` field informs about number of removed elements.
5436/// 3. `Y_EVENT_CHANGE_RETAIN` marks a number of characters that have not been changed, counted from
5437/// the previous element. `len` field informs about number of retained elements. Additionally
5438/// `attributes_len` and `attributes` carry information about optional formatting attributes applied
5439/// to edited blocks.
5440#[repr(C)]
5441pub struct YDeltaIn {
5442    /// Tag field used to identify particular type of change made:
5443    ///
5444    /// 1. `Y_EVENT_CHANGE_ADD` marks a new elements added to a collection. In this case `values`
5445    /// field contains a pointer to a list of newly inserted values, while `len` field informs about
5446    /// their count.
5447    /// 2. `Y_EVENT_CHANGE_DELETE` marks an existing elements removed from the collection. In this
5448    /// case `len` field informs about number of removed elements.
5449    /// 3. `Y_EVENT_CHANGE_RETAIN` marks a number of elements that have not been changed, counted
5450    /// from the previous element. `len` field informs about number of retained elements.
5451    pub tag: u8,
5452
5453    /// Number of element affected by current type of change. It can refer to a number of
5454    /// inserted `values`, number of deleted element or a number of retained (unchanged) values.
5455    pub len: u32,
5456
5457    /// A nullable pointer to a list of formatting attributes assigned to an edited area represented
5458    /// by this delta.
5459    pub attributes: *const YInput,
5460
5461    /// Used in case when current change is of `Y_EVENT_CHANGE_ADD` type. Contains a list (of
5462    /// length stored in `len` field) of newly inserted values.
5463    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
5494/// Tag used to identify `YEventKeyChange` (see: `yevent_keys` function) case, when a new entry has
5495/// been inserted into a map component of shared collection.
5496pub const Y_EVENT_KEY_CHANGE_ADD: c_char = 4;
5497
5498/// Tag used to identify `YEventKeyChange` (see: `yevent_keys` function) case, when an existing
5499/// entry has been removed from a map component of shared collection.
5500pub const Y_EVENT_KEY_CHANGE_DELETE: c_char = 5;
5501
5502/// Tag used to identify `YEventKeyChange` (see: `yevent_keys` function) case, when an existing
5503/// entry has been overridden with a new value within a map component of shared collection.
5504pub const Y_EVENT_KEY_CHANGE_UPDATE: c_char = 6;
5505
5506/// A data type representing a single change made over a map component of shared collection types,
5507/// such as `YMap` entries or `YXmlText`/`YXmlElement` attributes. A `key` field provides a
5508/// corresponding unique key string of a changed entry, while `tag` field informs about specific
5509/// type of change being done:
5510///
5511/// 1. `Y_EVENT_KEY_CHANGE_ADD` used to identify a newly added entry. In this case an `old_value`
5512/// field is NULL, while `new_value` field contains an inserted value.
5513/// 1. `Y_EVENT_KEY_CHANGE_DELETE` used to identify an existing entry being removed. In this case
5514/// an `old_value` field contains the removed value.
5515/// 1. `Y_EVENT_KEY_CHANGE_UPDATE` used to identify an existing entry, which value has been changed.
5516/// In this case `old_value` field contains replaced value, while `new_value` contains a newly
5517/// inserted one.
5518#[repr(C)]
5519pub struct YEventKeyChange {
5520    /// A UTF8-encoded null-terminated string containing a key of a changed entry.
5521    pub key: *const c_char,
5522    /// Tag field informing about type of change current struct refers to:
5523    ///
5524    /// 1. `Y_EVENT_KEY_CHANGE_ADD` used to identify a newly added entry. In this case an
5525    /// `old_value` field is NULL, while `new_value` field contains an inserted value.
5526    /// 1. `Y_EVENT_KEY_CHANGE_DELETE` used to identify an existing entry being removed. In this
5527    /// case an `old_value` field contains the removed value.
5528    /// 1. `Y_EVENT_KEY_CHANGE_UPDATE` used to identify an existing entry, which value has been
5529    /// changed. In this case `old_value` field contains replaced value, while `new_value` contains
5530    /// a newly inserted one.
5531    pub tag: c_char,
5532
5533    /// Contains a removed entry's value or replaced value of an updated entry.
5534    pub old_value: *const YOutput,
5535
5536    /// Contains a value of newly inserted entry or an updated entry's new value.
5537    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/// A sticky index is based on the Yjs model and is not affected by document changes.
5598/// E.g. If you place a sticky index before a certain character, it will always point to this character.
5599/// If you place a sticky index at the end of a type, it will always point to the end of the type.
5600///
5601/// A numeric position is often unsuited for user selections, because it does not change when content is inserted
5602/// before or after.
5603///
5604/// ```Insert(0, 'x')('a.bc') = 'xa.bc'``` Where `.` is the sticky index position.
5605///
5606/// Instances of `YStickyIndex` can be freed using `ysticky_index_destroy`.
5607#[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/// Releases resources allocated by `YStickyIndex` pointers.
5618#[no_mangle]
5619pub unsafe extern "C" fn ysticky_index_destroy(pos: *mut YStickyIndex) {
5620    drop(Box::from_raw(pos))
5621}
5622
5623/// Returns association of current `YStickyIndex`.
5624/// If association is **after** the referenced inserted character, returned number will be >= 0.
5625/// If association is **before** the referenced inserted character, returned number will be < 0.
5626#[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/// Retrieves a `YStickyIndex` corresponding to a given human-readable `index` pointing into
5636/// the shared y-type `branch`. Unlike standard indexes sticky one enables to track
5637/// the location inside of a shared y-types, even in the face of concurrent updates.
5638///
5639/// If association is >= 0, the resulting position will point to location **after** the referenced index.
5640/// If association is < 0, the resulting position will point to location **before** the referenced index.
5641#[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/// Serializes `YStickyIndex` into binary representation. `len` parameter is updated with byte
5672/// length of the generated binary. Returned binary can be free'd using `ybinary_destroy`.
5673#[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/// Serializes `YStickyIndex` into JSON representation. `len` parameter is updated with byte
5685/// length of the generated binary. Returned binary can be free'd using `ybinary_destroy`.
5686#[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/// Serialize `YStickyIndex` into null-terminated UTF-8 encoded JSON string, that's compatible with
5700/// Yjs RelativePosition serialization format. The `len` parameter is updated with byte length of
5701/// of the output JSON string. This string can be freed using `ystring_destroy`.
5702#[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/// Deserializes `YStickyIndex` from the payload previously serialized using `ysticky_index_to_json`.
5713/// The input `json` parameter is a NULL-terminated UTF-8 encoded string containing a JSON
5714/// compatible with Yjs RelativePosition serialization format.
5715///
5716/// Returns null pointer if deserialization failed.
5717///
5718/// This function DOESN'T release the `json` parameter: it needs to be done manually - if JSON
5719/// string was created using `ysticky_index_to_json` function, it can be freed using `ystring_destroy`.
5720#[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/// Given `YStickyIndex` and transaction reference, if computes a human-readable index in a
5734/// context of the referenced shared y-type.
5735///
5736/// `out_branch` is getting assigned with a corresponding shared y-type reference.
5737/// `out_index` will be used to store computed human-readable index.
5738#[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        // Assoc must be After to get the same values back
5793        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); // both
5806                                        // unforunately no Branch in this case?
5807        *out_start_index = 0; // empty text
5808        *out_end_index = 0; // empty text
5809    }
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/// Subscribes a given callback function `cb` under a `key` to changes made by this `YWeakRef`
5875/// instance. Callbacks are triggered whenever a `ytransaction_commit` is called.
5876/// Use `yunobserve` with the same key to unsubscribe.
5877#[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/// A structure representing logical identifier of a specific shared collection.
6009/// Can be obtained by `ybranch_id` executed over alive `Branch`.
6010///
6011/// Use `ybranch_get` to resolve a `Branch` pointer from this branch ID.
6012///
6013/// This structure doesn't need to be destroyed. It's internal pointer reference is valid through
6014/// a lifetime of a document, which collection this branch ID has been created from.
6015#[repr(C)]
6016pub struct YBranchId {
6017    /// If positive: Client ID of a creator of a nested shared type, this identifier points to.
6018    /// If negative: a negated Length of a root-level shared collection name.
6019    pub client_or_len: i64,
6020    pub variant: YBranchIdVariant,
6021}
6022
6023#[repr(C)]
6024pub union YBranchIdVariant {
6025    /// Clock number timestamp when the creator of a nested shared type created it.
6026    pub clock: u32,
6027    /// Pointer to UTF-8 encoded string representing root-level type name. This pointer is valid
6028    /// as long as document - in which scope it was created in - was not destroyed. As usually
6029    /// root-level type names are statically allocated strings, it can also be supplied manually
6030    /// from the outside.
6031    pub name: *const u8,
6032}
6033
6034/// Returns a logical identifier for a given shared collection. That collection must be alive at
6035/// the moment of function call.
6036#[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/// Given a logical identifier, returns a physical pointer to a shared collection.
6057/// Returns null if collection was not found - either because it was not defined or not synchronized
6058/// yet.
6059/// Returned pointer may still point to deleted collection. In such case a subsequent `ybranch_alive`
6060/// function call is required.
6061#[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/// Check if current branch is still alive (returns `Y_TRUE`, otherwise `Y_FALSE`).
6086/// If it was deleted, this branch pointer is no longer a valid pointer and cannot be used to
6087/// execute any functions using it.
6088#[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/// Returns a UTF-8 encoded, NULL-terminated JSON string representation of the current branch
6103/// contents. Once no longer needed, this string must be explicitly deallocated by user using
6104/// `ystring_destroy`.
6105///
6106/// If branch type couldn't be resolved (which usually happens for root-level types that were not
6107/// initialized locally) or doesn't have JSON representation a NULL pointer can be returned.
6108#[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}