### Example usage of MapTransaction Source: https://docs.rs/dson/latest/dson/transaction/struct.MapTransaction.html Demonstrates the basic workflow of creating a transaction, making mutations, and committing the changes to get a delta. ```rust use dson::{CausalDotStore, Identifier, OrMap, transaction::MapTransaction}; let mut store = CausalDotStore::>::default(); let id = Identifier::new(0, 0); let mut tx = MapTransaction::new(&mut store, id); // Make mutations... let delta = tx.commit(); ``` -------------------------------- ### Demonstrate Simple Conflict Resolution with DSON Transactions Source: https://docs.rs/dson/latest/dson/index.html This example shows how two replicas concurrently edit the same data, creating a conflict that DSON resolves using its transaction API. It covers setup, initial state, syncing, concurrent edits, merging, and verifying the conflict resolution. ```rust use dson:: crdts::{mvreg::MvRegValue, snapshot::ToValue}, CausalDotStore, Identifier, OrMap, ; // 1. SETUP: TWO REPLICAS // Create two replicas, Alice and Bob, each with a unique ID. let alice_id = Identifier::new(0, 0); let mut alice_store = CausalDotStore::>::default(); let bob_id = Identifier::new(1, 0); let mut bob_store = CausalDotStore::>::default(); // 2. INITIAL STATE // Alice creates an initial value using the transaction API. let key = "document".to_string(); let delta_from_alice = { let mut tx = alice_store.transact(alice_id); tx.write_register(&key, MvRegValue::String("initial value".to_string())); tx.commit() }; // 3. SYNC // Bob receives Alice's initial change. bob_store.join_or_replace_with(delta_from_alice.0.store, &delta_from_alice.0.context); assert_eq!(alice_store, bob_store); // 4. CONCURRENT EDITS // Now Alice and Bob make changes without syncing. // Alice updates the value to "from Alice". let delta_alice_edit = { let mut tx = alice_store.transact(alice_id); tx.write_register(&key, MvRegValue::String("from Alice".to_string())); tx.commit() }; // Concurrently, Bob updates the value to "from Bob". let delta_bob_edit = { let mut tx = bob_store.transact(bob_id); tx.write_register(&key, MvRegValue::String("from Bob".to_string())); tx.commit() }; // 5. MERGE // The replicas exchange their changes. alice_store.join_or_replace_with(delta_bob_edit.0.store, &delta_bob_edit.0.context); bob_store.join_or_replace_with(delta_alice_edit.0.store, &delta_alice_edit.0.context); // After merging, both stores are identical. assert_eq!(alice_store, bob_store); // 6. VERIFY CONFLICT // The concurrent writes are preserved as a conflict in the register. // The transaction API exposes this through the CrdtValue enum. use dson::transaction::CrdtValue; let tx = alice_store.transact(alice_id); match tx.get(&key) { Some(CrdtValue::Register(reg)) => { // Read all concurrent values let values: Vec<_> = reg.values().into_iter().collect(); assert_eq!(values.len(), 2); assert!(values.contains(&&MvRegValue::String("from Alice".to_string()))); assert!(values.contains(&&MvRegValue::String("from Bob".to_string()))); } _ => panic!("Expected register with conflict"), } ``` -------------------------------- ### KeySentinel Implementation for DummySentinel Source: https://docs.rs/dson/latest/dson/sentinel/trait.KeySentinel.html Example implementation of the KeySentinel trait for the DummySentinel type. ```rust impl KeySentinel for DummySentinel ``` -------------------------------- ### OrArray Usage Example Source: https://docs.rs/dson/latest/dson/crdts/orarray/struct.OrArray.html Demonstrates how to create, insert into, and read from an OrArray using CausalDotStore and the api::array module. ```APIDOC ### Usage Like `OrMap`, an `OrArray` is typically wrapped in a `CausalDotStore`. Modifications are performed by creating a “delta” CRDT, which is then merged back into the original. ```rust // Create a new CausalDotStore containing an OrArray. let mut doc: CausalDotStore = CausalDotStore::new(); let id = Identifier::new(0, 0); // Create a delta to insert a value at the beginning of the array. let delta = dson::api::array::insert( |cc, id| MvReg::default().write(MvRegValue::U64(42), cc, id).map_store(Value::Register), doc.store.len() )(&doc.store, &doc.context, id); // Merge the delta into the document. doc = doc.join(delta, &mut DummySentinel).unwrap(); // The value can now be read from the array. let array = doc.store.value().unwrap(); let val = doc.store.get(0).unwrap(); assert_eq!(val.reg.value().unwrap(), &MvRegValue::U64(42)); ``` You can find more convenient, higher-level APIs for manipulating `OrArray` in the `api::array` module. The methods on `OrArray` itself are low-level and useful when implementing custom CRDTs or when you need fine-grained control over delta creation. ``` -------------------------------- ### JSON without Conflicts Source: https://docs.rs/dson/latest/src/dson/json.rs.html Example of a simple JSON document without any value-level conflicts. ```json { "name": "John Doe", "age": 43, "phones": [ "+44 1234567", "+44 2345678" ] } ``` -------------------------------- ### DummySentinel Implementation of ValueSentinel Source: https://docs.rs/dson/latest/dson/sentinel/trait.ValueSentinel.html An example implementation of the ValueSentinel trait for DummySentinel. This shows how to integrate the trait with existing types. ```rust impl ValueSentinel for DummySentinel ``` -------------------------------- ### Create an Empty IntervalSet in Rust Source: https://docs.rs/dson/latest/src/dson/causal_context/interval.rs.html Initializes a new, empty IntervalSet. Useful for starting with no intervals. ```rust pub fn new() -> Self { Self(Vec::new()) } ``` -------------------------------- ### Basic DotMap Initialization and Checks Source: https://docs.rs/dson/latest/src/dson/dotstores.rs.html Demonstrates the initial state of a new DotMap, including checks for emptiness, bottom state, and length. It also shows initial checks for key presence and dot inclusion. ```rust let mut map = DotMap::default(); assert!(map.is_empty()); assert!(map.is_bottom()); assert_eq!(map.len(), 0); let key = "foo"; let dot = Dot::from(((0, 0), SEQ_1)); assert!(!map.has(key)); assert!(!map.dots().dot_in(dot)); assert_eq!(map.get(key), None); assert_eq!(map.get_mut_and_invalidate(key), None); assert_eq!(map.set(key, DotFun::default()), None); ``` -------------------------------- ### Get Interval Start Source: https://docs.rs/dson/latest/src/dson/causal_context/interval.rs.html Returns the start sequence number of the interval. ```rust pub fn start(&self) -> NonZeroU64 { self.start } ``` -------------------------------- ### CloneToUninit Implementation Source: https://docs.rs/dson/latest/dson/api/timestamp/struct.Timestamp.html Details the nightly-only experimental API for `CloneToUninit`. ```APIDOC ## impl CloneToUninit for T where T: Clone ### Description This is a nightly-only experimental API that provides a way to perform copy-assignment from `self` to a raw pointer `dest`. #### unsafe fn clone_to_uninit(&self, dest: *mut u8) ##### Description Performs copy-assignment from `self` to `dest`. ##### Source [Source code link or reference] ``` -------------------------------- ### Get Register from Array Transaction Source: https://docs.rs/dson/latest/src/dson/transaction/array_transaction.rs.html Use the get method within an ArrayTransaction to retrieve a CrdtValue at a specific index. This example demonstrates retrieving a register and asserting its string value. ```rust use crate::crdts::{NoExtensionTypes, mvreg::MvRegValue, snapshot::ToValue}; use crate::transaction::CrdtValue; let mut store = CausalDotStore::>::default(); let id = Identifier::new(0, 0); { let mut tx = ArrayTransaction::new(&mut store, id); tx.insert_register(0, MvRegValue::String("hello".to_string())); let _delta = tx.commit(); } { let tx = ArrayTransaction::new(&mut store, id); let value = tx.get(0).expect("should have item at 0"); match value { CrdtValue::Register(reg) => { assert_eq!( reg.value().unwrap(), &MvRegValue::String("hello".to_string()) ); } _ => panic!("Expected Register variant"), } } ``` -------------------------------- ### Get Interval Tuple Source: https://docs.rs/dson/latest/src/dson/causal_context/interval.rs.html Returns the interval as a tuple containing the start and optional end sequence numbers. ```rust pub fn interval(&self) -> (NonZeroU64, Option) { (self.start, self.end) } ``` -------------------------------- ### Basic MvReg Usage Example Source: https://docs.rs/dson/latest/src/dson/crdts/mvreg.rs.html Demonstrates creating a CausalDotStore with an MvReg, writing a value, merging a delta, and reading the value. Requires `dson` crate with necessary features. ```rust use dson::{CausalDotStore, MvReg, crdts::{mvreg::MvRegValue, snapshot::ToValue}, Identifier, sentinel::DummySentinel}; // Create a new CausalDotStore containing an MvReg. let mut doc: CausalDotStore = CausalDotStore::new(); let id = Identifier::new(0, 0); // Create a delta to write a value. let delta = doc.store.write(MvRegValue::U64(42), &doc.context, id); // Merge the delta into the document. doc = doc.join(delta, &mut DummySentinel).unwrap(); // The value can now be read from the register. assert_eq!(*doc.store.value().unwrap(), MvRegValue::U64(42)); ``` -------------------------------- ### Initialize and Update OrMap with CausalDotStore Source: https://docs.rs/dson/latest/src/dson/crdts/ormap.rs.html Demonstrates how to initialize a CausalDotStore with an OrMap, apply updates using a delta, and merge the delta back into the document. This pattern is useful for managing concurrent modifications. ```rust use dson::{CausalDotStore, OrMap, MvReg, crdts::{mvreg::MvRegValue, snapshot::{ToValue, CollapsedValue}}, Identifier, sentinel::DummySentinel}; // Create a new CausalDotStore containing an OrMap. let mut doc: CausalDotStore> = CausalDotStore::new(); let id = Identifier::new(0, 0); // Create a delta to insert a value. let delta = doc.store.apply_to_register( |reg, cc, id| reg.write(MvRegValue::U64(42), cc, id), "key".into(), &doc.context, id, ); // Merge the delta into the document. doc = doc.join(delta, &mut DummySentinel).unwrap(); // The value can now be read from the map. let val = doc.store.get("key").unwrap(); assert_eq!(val.reg.value().unwrap(), &MvRegValue::U64(42)); ``` -------------------------------- ### Get Interval End Source: https://docs.rs/dson/latest/src/dson/causal_context/interval.rs.html Retrieves the end sequence number of the interval. If the interval is a single point (no explicit end), it returns the start sequence number. ```rust pub fn end(&self) -> NonZeroU64 { self.end.unwrap_or(self.start) } ``` -------------------------------- ### Create and Commit a Transaction Source: https://docs.rs/dson/latest/dson/transaction/index.html Demonstrates creating a transaction, writing values to registers, and committing the changes. Remember to call `commit()` to save changes; otherwise, they will be lost. ```rust use dson::{CausalDotStore, Identifier, OrMap, crdts::mvreg::MvRegValue, transaction::CrdtValue}; use dson::crdts::snapshot::ToValue; let mut store = CausalDotStore::>::default(); let id = Identifier::new(0, 0); // Create a transaction let mut tx = store.transact(id); // Write values tx.write_register("name", MvRegValue::String("Alice".to_string())); tx.write_register("age", MvRegValue::U64(30)); // IMPORTANT: You must call commit() or changes are lost let delta = tx.commit(); // Read with explicit type handling let tx = store.transact(id); match tx.get(&"name".to_string()) { Some(CrdtValue::Register(reg)) => { println!("Name: {:?}", reg.value().unwrap()); } Some(CrdtValue::Conflicted(conflicts)) => { println!("Type conflict!"); } None => { println!("Key not found"); } _ => {} } ``` -------------------------------- ### Get Next Sequence Number Source: https://docs.rs/dson/latest/src/dson/causal_context/interval.rs.html Returns the next sequence number after the interval's end. If the interval has no explicit end, it returns the start number plus one. ```rust pub fn next_after(&self) -> NonZeroU64 { self.end.unwrap_or(self.start).saturating_add(1) } ``` -------------------------------- ### Usage Example: OrMap with CausalDotStore Source: https://docs.rs/dson/latest/dson/crdts/ormap/struct.OrMap.html Demonstrates how to use OrMap within a CausalDotStore for inserting and reading values. Requires a CausalDotStore and Identifier. ```rust // Create a new CausalDotStore containing an OrMap. let mut doc: CausalDotStore> = CausalDotStore::new(); let id = Identifier::new(0, 0); // Create a delta to insert a value. let delta = doc.store.apply_to_register( |reg, cc, id| reg.write(MvRegValue::U64(42), cc, id), "key".into(), &doc.context, id, ); // Merge the delta into the document. doc = doc.join(delta, &mut DummySentinel).unwrap(); // The value can now be read from the map. let val = doc.store.get("key").unwrap(); assert_eq!(val.reg.value().unwrap(), &MvRegValue::U64(42)); ``` -------------------------------- ### Macros Overview Source: https://docs.rs/dson/latest/dson/all.html Lists the available macros within the dson crate. ```APIDOC ## Macros - **causal_context** - **crdt_literal** - **crdt_map_literal** - **crdt_map_store** - **datetime** - **dot** ``` -------------------------------- ### Get Nonexistent Key from MapTransaction Source: https://docs.rs/dson/latest/src/dson/transaction/map_transaction.rs.html Demonstrates that calling `get` on a `MapTransaction` with a key that does not exist in the store returns `None`. ```rust let mut store = CausalDotStore::>::default(); let id = Identifier::new(0, 0); let tx = MapTransaction::::new(&mut store, id); assert!(tx.get(&"nonexistent".to_string()).is_none()); ``` -------------------------------- ### Implement Debug for Interval in Rust Source: https://docs.rs/dson/latest/src/dson/causal_context/interval.rs.html Provides a custom Debug implementation for the Interval struct, formatting it as 'start' or 'start..=end'. ```rust impl std::fmt::Debug for Interval { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "{}", self.start)?; if let Some(end) = &self.end { write!(f, "..={{end}}")?; } Ok(()) } } ``` -------------------------------- ### Transaction Management in CausalDotStore Source: https://docs.rs/dson/latest/src/dson/dotstores.rs.html Initializes a CausalDotStore and demonstrates the basic transaction process, including creating a transaction and committing it. This is a fundamental operation for modifying the store. ```rust use crate::{CausalDotStore, Identifier, OrMap}; let mut store = CausalDotStore::>::default(); let id = Identifier::new(0, 0); let tx = store.transact(id); let _delta = tx.commit(); ``` -------------------------------- ### CloneToUninit Source: https://docs.rs/dson/latest/dson/causal_context/struct.CausalContext.html Experimental API for cloning data to uninitialized memory. Requires nightly Rust. ```APIDOC ## unsafe POST /websites/rs_dson/clone_to_uninit ### Description Performs copy-assignment from `self` to `dest` in uninitialized memory. ### Method POST ### Endpoint /websites/rs_dson/clone_to_uninit ### Parameters #### Request Body - **dest** (*mut u8) - Required - A mutable pointer to the destination memory. ### Request Example ```json { "dest": "0x1234567890abcdef" } ``` ### Response #### Success Response (200) - **status** (string) - Indicates success. #### Response Example ```json { "status": "success" } ``` ``` -------------------------------- ### Get Value by Dot Source: https://docs.rs/dson/latest/src/dson/dotstores.rs.html Use `get()` with a `Dot` to retrieve an optional reference to the associated value. Returns `None` if the `Dot` is not found. ```rust pub fn get(&self, dot: &Dot) -> Option<&V> { self.get_index(dot).map(|idx| &self.state[idx].1) } ``` -------------------------------- ### Normalize Interval Set Starting at Index Source: https://docs.rs/dson/latest/src/dson/causal_context/interval.rs.html Merges overlapping or adjacent intervals starting from a given index to maintain the sorted and non-overlapping property of the interval set. ```rust fn normalize_starting_at(&mut self, i: usize) { let right_start = i + 1; for j in right_start..self.0.len() { if let Some(merged) = self.0[i].merge(&self.0[j]) { self.0[i] = merged; } else { if j != right_start { // this means there's a segment of merged intervals from // `i+1..j` of length n that needs to be shifted over to the // left. let n = j - i - 1; self.0[right_start..].rotate_left(n); } } } } ``` -------------------------------- ### Create and Access Delta Source: https://docs.rs/dson/latest/src/dson/transaction/delta.rs.html Demonstrates how to create a Delta instance and access its inner CausalDotStore. Ensure the Delta is applied or sent to other replicas. ```rust use dson::{Delta, CausalDotStore, OrMap}; # fn example(delta: Delta>>) { // Access inner value let store = delta.0; # } ``` -------------------------------- ### Get Map from Array Transaction Source: https://docs.rs/dson/latest/src/dson/transaction/array_transaction.rs.html Demonstrates retrieving a map from an array transaction using the get method. The retrieved value is matched against the CrdtValue::Map variant. ```rust use crate::crdts::{NoExtensionTypes, mvreg::MvRegValue, snapshot::ToValue}; use crate::transaction::CrdtValue; let mut store = CausalDotStore::>::default(); let id = Identifier::new(0, 0); { let mut tx = ArrayTransaction::new(&mut store, id); tx.insert_map(0, |map_tx| { map_tx.write_register("field", MvRegValue::U64(42)); }); let _delta = tx.commit(); } { let tx = ArrayTransaction::new(&mut store, id); let value = tx.get(0).expect("should have item at 0"); match value { CrdtValue::Map(map) => { ``` -------------------------------- ### CausalDotStore::new Source: https://docs.rs/dson/latest/dson/struct.CausalDotStore.html Constructs a new, empty CausalDotStore. ```APIDOC ## Constructor `new()` ### Description Constructs a new empty `CausalDotStore`. ### Method `pub fn new() -> Self` ### Constraints Requires `DS: Default`. ``` -------------------------------- ### Implement TryFrom> for Interval in Rust Source: https://docs.rs/dson/latest/src/dson/causal_context/interval.rs.html Converts a RangeInclusive to an Interval. Panics if start is not less than end. Returns an error if start or end are 0. ```rust impl TryFrom> for Interval { type Error = IntervalError; fn try_from(value: RangeInclusive) -> Result { assert!( value.start() < value.end(), "start must be < end: {value:?}" ); Ok(Self::span( NonZeroU64::new(*value.start()).ok_or(IntervalError("start must be > 0"))?, NonZeroU64::new(*value.end()).ok_or(IntervalError("end must be > 0"))?, )) } } ``` -------------------------------- ### Get Map Values with dson::api::map::value Source: https://docs.rs/dson/latest/dson/api/map/fn.value.html Use this function to get the values of a map when you are certain there are no conflicts. It assumes and asserts that element values are unique. ```rust pub fn value( m: &OrMap, ) -> Result>>, Box as ToValue>::LeafValue>>> where K: Hash + Eq + Debug + Display + Clone, C: ExtensionType, ``` -------------------------------- ### Insert Register Example Source: https://docs.rs/dson/latest/src/dson/crdts/orarray.rs.html Demonstrates inserting a register with a specific value. Used within a join harness for concurrent operations. ```rust m.insert_register( cc.next_dot_for(id).into(), |cc, id| MvReg::default().write(MvRegValue::U64(3), cc, id), Position::between(None, None), &cc, id, ) ``` ```rust cds.store.insert_register( uid, |cc, id| MvReg::default().write(MvRegValue::U64(1), cc, id), p, &cds.context, id, ) ``` -------------------------------- ### Create an Interval Span Source: https://docs.rs/dson/latest/src/dson/causal_context/interval.rs.html Constructs an interval from a start and an optional end sequence number. The start must be strictly less than the end. Use `Self::point` for single-point intervals. ```rust pub fn span(start: NonZeroU64, end: impl Into>) -> Self { let end = end.into(); if let Some(end) = end { assert!(start < end, "{start} < {end}"); } Self { start, end } } ``` -------------------------------- ### Implement TryFrom<(NonZeroU64, Option)> for Interval in Rust Source: https://docs.rs/dson/latest/src/dson/causal_context/interval.rs.html Allows creating an Interval from a tuple of start and optional end NonZeroU64 values. Returns an error if the end is less than the start. ```rust impl TryFrom<(NonZeroU64, Option)> for Interval { type Error = IntervalError; fn try_from((start, end): (NonZeroU64, Option)) -> Result { if let Some(end) = end { (end > start) .then_some(Self { start, end: Some(end), }) .ok_or(IntervalError("end must be > start")) } else { Ok(Self { start, end }) } } } ``` -------------------------------- ### Map Get Sees Uncommitted Writes (Eager Semantics) Source: https://docs.rs/dson/latest/src/dson/transaction/map_transaction.rs.html Illustrates eager map semantics in Rust CRDTs, where `get()` operations within the same transaction can see uncommitted writes. This requires importing `MvRegValue` and `ToValue`. ```rust use crate::crdts::mvreg::MvRegValue; use crate::crdts::snapshot::ToValue; let mut store = CausalDotStore::>::default(); let id = Identifier::new(0, 0); let mut tx = MapTransaction::::new(&mut store, id); tx.write_register("x", MvRegValue::U64(42)); // Should see uncommitted write (eager semantics) match tx.get(&"x".to_string()) { Some(CrdtValue::Register(reg)) => { assert_eq!(reg.value().unwrap(), &MvRegValue::U64(42)); } other => panic!("Expected to see uncommitted write, got {other:?}") } ``` -------------------------------- ### DotMap Methods (General) Source: https://docs.rs/dson/latest/dson/struct.DotMap.html General methods for interacting with DotMap instances. ```APIDOC ## impl DotMap ### `with_capacity(capacity: usize) -> Self` Constructs a `DotMap` with the given initial capacity. ### `iter(&self) -> impl ExactSizeIterator` Produces an iterator over the map’s keys and values. ### `iter_mut_and_invalidate(&mut self) -> impl ExactSizeIterator` Produces a mutable iterator over the map’s keys and values. Invalidates the dots cache for all the map’s entries, so calling `.dots()` on this collection after invoking this method may be quite slow (it has to call `.dots()` on all the entries). ### `keys(&self) -> impl ExactSizeIterator` Produces an iterator over the map’s keys. ### `values(&self) -> impl ExactSizeIterator` Produces an iterator over the map’s values. ### `len(&self) -> usize` Returns the number of keys in the map. ### `is_empty(&self) -> bool` Returns true if the map is empty. ``` -------------------------------- ### Get Priority Source: https://docs.rs/dson/latest/dson/causal_context/struct.Identifier.html Returns the priority component of the Identifier. ```rust pub const fn priority(&self) -> Priority ``` -------------------------------- ### Serialization Source: https://docs.rs/dson/latest/dson/struct.DotFun.html Implementation for serializing DotFun instances using Serde. ```APIDOC ## impl Serialize for DotFun ### Description Implementation for serializing DotFun instances. ### Method `serialize` ### Parameters - **__serializer** (`__S`) - Required - The Serde serializer. ### Response - **Result<__S::Ok, __S::Error>** - The result of the serialization process. ``` -------------------------------- ### Join DotStores (Formal Equation) Source: https://docs.rs/dson/latest/dson/struct.DotFun.html Implements the formal join operation for DotFun, combining two DotFun instances and their causal contexts according to Equation 4 from the DSON paper. ```rust fn join( (m1, cc1): (Self, &CausalContext), (m2, cc2): (Self, &CausalContext), on_dot_change: &mut dyn FnMut(DotChange), sentinel: &mut S, ) -> Result where S: Sentinel, ``` -------------------------------- ### Get NodeId Value Source: https://docs.rs/dson/latest/dson/causal_context/struct.NodeId.html Retrieves the u8 value of the NodeId. ```rust pub const fn value(self) -> u8 ``` -------------------------------- ### Structs Overview Source: https://docs.rs/dson/latest/dson/all.html Lists the available structs within the dson crate, categorized by their module. ```APIDOC ## Structs ### Core Structs - **CausalDotStore** - **ComputeDeletionsArg** - **DotFun** - **DotFunMap** - **DotFunValueIter** - **DotMap** - **DryJoinOutput** - **DsonRandomState** ### API Module Structs - **api::timestamp::Timestamp** ### Causal Context Module Structs - **causal_context::CausalContext** - **causal_context::Dot** - **causal_context::Identifier** - **causal_context::InvalidPriority** - **causal_context::NodeId** ### CRDTs Module Structs - **crdts::NoExtensionTypes** - **crdts::TypeVariantValue** - **crdts::mvreg::MvReg** - **crdts::orarray::OrArray** - **crdts::orarray::Position** - **crdts::orarray::Uid** - **crdts::ormap::OrMap** - **crdts::snapshot::MvReg** - **crdts::snapshot::OrArray** - **crdts::snapshot::OrMap** - **crdts::snapshot::SingleValueError** ### Sentinel Module Structs - **sentinel::DummySentinel** ### Transaction Module Structs - **transaction::ArrayTransaction** - **transaction::ConflictedValue** - **transaction::Delta** - **transaction::MapTransaction** ``` -------------------------------- ### iter Source: https://docs.rs/dson/latest/dson/crdts/snapshot/struct.OrArray.html Returns an iterator over the slice, yielding all items from start to end. ```APIDOC ## GET /slice/iter ### Description Returns an iterator over the slice, yielding all items from start to end. ### Method GET ### Endpoint /slice/iter ### Parameters None ### Response #### Success Response (200) - **iterator** (Iter<'_, T>) - An iterator yielding elements of the slice. #### Response Example ```json { "iterator": [ {"next": 1}, {"next": 2}, {"next": 4}, {"next": null} ] } ``` ``` -------------------------------- ### DotFunMap Construction Source: https://docs.rs/dson/latest/src/dson/dotstores.rs.html Methods for creating and initializing DotFunMap instances. ```APIDOC ## POST /from_iter ### Description Creates a new `DotFunMap` from an iterator of `(Dot, V)` pairs. ### Method POST ### Endpoint `/from_iter` ### Parameters #### Request Body - **iter** (Iterator<(Dot, V)>) - Required - An iterator yielding `(Dot, V)` tuples. ### Response #### Success Response (200) - **DotFunMap** (DotFunMap) - A new `DotFunMap` initialized with the provided pairs. ``` -------------------------------- ### Get Actor Identifier Source: https://docs.rs/dson/latest/dson/causal_context/struct.Dot.html Retrieves the Identifier of the actor that generated this Dot. ```rust pub fn actor(&self) -> Identifier ``` -------------------------------- ### Get Identifier Bits Source: https://docs.rs/dson/latest/dson/causal_context/struct.Identifier.html Returns the underlying 32-bit representation of the Identifier. ```rust pub const fn bits(&self) -> u32 ``` -------------------------------- ### Implement CloneToUninit for T Source: https://docs.rs/dson/latest/dson/crdts/enum.ValueType.html Nightly-only experimental API for copying data to uninitialized memory. Use with caution and ensure `T` implements `Clone`. ```rust unsafe impl CloneToUninit for T where T: Clone { unsafe fn clone_to_uninit(&self, dest: *mut u8) { // ... implementation details ... } } ``` -------------------------------- ### Get Node ID Source: https://docs.rs/dson/latest/dson/causal_context/struct.Identifier.html Returns the node identifier component of the Identifier. ```rust pub const fn node(&self) -> NodeId ``` -------------------------------- ### DotMap Conversions and Indexing Source: https://docs.rs/dson/latest/dson/struct.DotMap.html Information on creating DotMaps from iterators and accessing elements by index. ```APIDOC ## POST /websites/rs_dson/from_iter ### Description Creates a DotMap value from an iterator. ### Method POST ### Endpoint /websites/rs_dson/from_iter ### Parameters #### Request Body - **iter** (T: IntoIterator) - An iterator yielding key-value pairs. ### Response #### Success Response (200) - **dot_map** (Self) - The newly created DotMap. #### Response Example ```json { "dot_map": { ... } } ``` ``` ```APIDOC ## GET /websites/rs_dson/index/{key} ### Description Performs the indexing (`container[index]`) operation to retrieve a value by its key. ### Method GET ### Endpoint /websites/rs_dson/index/{key} ### Parameters #### Path Parameters - **key** (Q: Eq + Hash + ?Sized) - The key to index by. ### Response #### Success Response (200) - **value** (Self::Output) - The value associated with the key. #### Response Example ```json { "value": "retrieved_value" } ``` ``` -------------------------------- ### Constants Overview Source: https://docs.rs/dson/latest/dson/all.html Lists the available constants within the dson crate, categorized by their module. ```APIDOC ## Constants ### Causal Context Module Constants - **causal_context::MAX_APPLICATION_ID** - **causal_context::PRIORITY_MAX** - **causal_context::ROOT_APP_ID** ``` -------------------------------- ### Getting a Pointer Range for Slice Buffer Source: https://docs.rs/dson/latest/dson/crdts/snapshot/struct.OrArray.html Illustrates using `as_ptr_range` to get a half-open range of raw pointers spanning the slice's buffer. This is useful for interfacing with C-style APIs that use two pointers to define a range. The end pointer points one past the last element. ```rust let a = [1, 2, 3]; let x = &a[1] as *const _; let y = &5 as *const _; assert!(a.as_ptr_range().contains(&x)); assert!(!a.as_ptr_range().contains(&y)); ``` -------------------------------- ### Usage Example for MvReg Source: https://docs.rs/dson/latest/dson/crdts/mvreg/struct.MvReg.html Demonstrates how to use MvReg within a CausalDotStore to write and read values. Requires setting up a store, creating a delta for writing, merging the delta, and then reading the value. ```rust // Create a new CausalDotStore containing an MvReg. let mut doc: CausalDotStore = CausalDotStore::new(); let id = Identifier::new(0, 0); // Create a delta to write a value. let delta = doc.store.write(MvRegValue::U64(42), &doc.context, id); // Merge the delta into the document. doc = doc.join(delta, &mut DummySentinel).unwrap(); // The value can now be read from the register. assert_eq!(*doc.store.value().unwrap(), MvRegValue::U64(42)); ``` -------------------------------- ### Get Length of OrArray Source: https://docs.rs/dson/latest/src/dson/crdts/orarray.rs.html Returns the number of elements in the OrArray. This is an efficient operation. ```rust pub fn len(&self) -> usize { // NOTE: the original has to walk the fields to filter out alive, we don't \o/ self.0.len() } ``` -------------------------------- ### Example: Configuring Nested Map in ArrayTransaction Source: https://docs.rs/dson/latest/src/dson/transaction/array_transaction.rs.html Demonstrates how to use `insert_map` to add a map with specific key-value pairs to an array transaction. ```rust # use dson::{CausalDotStore, Identifier, OrArray, transaction::ArrayTransaction}; # use dson::crdts::mvreg::MvRegValue; # let mut store = CausalDotStore::::default(); # let id = Identifier::new(0, 0); let mut tx = ArrayTransaction::new(&mut store, id); tx.insert_map(0, |task_tx| { task_tx.write_register("title", MvRegValue::String("Write docs".to_string())); task_tx.write_register("done", MvRegValue::Bool(false)); }); let delta = tx.commit(); ``` -------------------------------- ### Get Dot Actor Identifier Source: https://docs.rs/dson/latest/src/dson/causal_context.rs.html Returns the `Identifier` of the actor that produced this `Dot`. ```rust pub fn actor(&self) -> Identifier { self.0 } ``` -------------------------------- ### Functions Overview Source: https://docs.rs/dson/latest/dson/all.html Lists the available functions within the dson crate, categorized by their module. ```APIDOC ## Functions ### API Array Module Functions - **api::array::apply** - **api::array::apply_to_array** - **api::array::apply_to_map** - **api::array::apply_to_register** - **api::array::clear** - **api::array::create** - **api::array::delete** - **api::array::insert** - **api::array::insert_array** - **api::array::insert_map** - **api::array::insert_register** - **api::array::mv** - **api::array::value** - **api::array::values** ### API Map Module Functions - **api::map::apply** - **api::map::apply_to_array** - **api::map::apply_to_map** - **api::map::apply_to_register** - **api::map::clear** - **api::map::create** - **api::map::remove** - **api::map::value** - **api::map::values** ### API Register Module Functions - **api::register::clear** - **api::register::value** - **api::register::values** - **api::register::write** ### Core Functions - **compute_deletions_unknown_to** ``` -------------------------------- ### Get OrMap Length Source: https://docs.rs/dson/latest/dson/crdts/ormap/struct.OrMap.html Returns the number of elements currently stored in the OrMap. ```rust pub fn len(&self) -> usize ``` -------------------------------- ### Get Application ID Source: https://docs.rs/dson/latest/dson/causal_context/struct.Identifier.html Returns the application identifier component (u16) of the Identifier. ```rust pub const fn app(&self) -> u16 ``` -------------------------------- ### From and Into Implementations Source: https://docs.rs/dson/latest/dson/api/timestamp/struct.Timestamp.html Details the `From` and `Into` trait implementations for type conversions. ```APIDOC ## impl From for T ### Description This implementation allows a type `T` to be converted from itself, returning the argument unchanged. #### fn from(t: T) -> T ##### Description Returns the argument unchanged. ##### Source [Source code link or reference] ``` ```APIDOC ## impl Into for T where U: From ### Description This implementation allows a type `T` to be converted into type `U`, provided that `U` implements `From`. #### fn into(self) -> U ##### Description Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From for U` chooses to do. ##### Source [Source code link or reference] ``` -------------------------------- ### Create an IntervalSet with Capacity in Rust Source: https://docs.rs/dson/latest/src/dson/causal_context/interval.rs.html Initializes an IntervalSet with a pre-allocated capacity for a given number of intervals. Optimizes for scenarios where the number of intervals is known beforehand. ```rust pub fn with_capacity(n: usize) -> Self { Self(Vec::with_capacity(n)) } ``` -------------------------------- ### Get DotMap Length Source: https://docs.rs/dson/latest/src/dson/dotstores.rs.html Returns the number of key-value pairs currently stored in the DotMap. ```rust pub fn len(&self) -> usize { ``` -------------------------------- ### DotFun Basic Operations Source: https://docs.rs/dson/latest/src/dson/dotstores.rs.html Illustrates basic operations on the DotFun data structure, including checking emptiness, bottom status, setting values, and retrieving values. ```APIDOC ## DotFun Operations ### Description Provides examples of basic operations on the DotFun data structure, such as checking its state and manipulating key-value pairs. ### Method N/A (Illustrative examples) ### Endpoint N/A ### Parameters N/A ### Request Example N/A ### Response #### Success Response (N/A) N/A #### Response Example ```rust // Example of setting a value let dot = Dot::from(((0, 0), SEQ_1)); map.set(dot, "foo"); // Example of getting a value let value = map.get(&dot); ``` ``` -------------------------------- ### Simulate DotStore Join Source: https://docs.rs/dson/latest/dson/struct.DotFun.html Simulates the `join` operation for DotFun without actually constructing the resulting DotFun. Useful for analyzing join outcomes. Part of the DotStoreJoin trait. ```rust fn dry_join( (m1, cc1): (&Self, &CausalContext), (m2, cc2): (&Self, &CausalContext), sentinel: &mut S, ) -> Result where Self: Sized, S: Sentinel, ``` -------------------------------- ### Get Slice Length Source: https://docs.rs/dson/latest/dson/crdts/snapshot/struct.OrArray.html Returns the number of elements in the slice. This is a common operation for collections. ```rust let a = [1, 2, 3]; assert_eq!(a.len(), 3); ``` -------------------------------- ### Get Inner DotMap Source: https://docs.rs/dson/latest/dson/crdts/ormap/struct.OrMap.html Returns a reference to the underlying DotMap structure within the OrMap. ```rust pub fn inner(&self) -> &DotMap> ``` -------------------------------- ### Get Minimum of Two Identifiers Source: https://docs.rs/dson/latest/dson/causal_context/struct.Identifier.html Compares two Identifiers and returns the minimum value. ```rust fn min(self, other: Self) -> Self where Self: Sized ``` -------------------------------- ### CausalDotStore Join Methods Source: https://docs.rs/dson/latest/src/dson/dotstores.rs.html Provides methods for joining `DotStore` and `CausalContext` pairs into a `CausalDotStore`, with options for tracking changes. ```APIDOC ## `CausalDotStore` Join Methods ### Description Methods for joining `DotStore` and `CausalContext` pairs into a `CausalDotStore`. ### `join_with` Joins the given [`DotStore`]-[`CausalContext`] pair into those in `self`. Prefer this method when you need to avoid cloning the [`CausalContext`]. ### Method `pub fn join_with(&mut self, store: DS, context: &CausalContext, sentinel: &mut S) -> Result<(), S::Error>` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) `Result<(), S::Error>` #### Response Example None ## `join_with_and_track` Joins the given [`DotStore`]-[`CausalContext`] pair into those in `self`. Prefer this method when you need to avoid cloning the [`CausalContext`]. ### Method `fn join_with_and_track(&mut self, store: DS, context: &CausalContext, on_dot_change: &mut dyn FnMut(DotChange), sentinel: &mut S) -> Result<(), S::Error>` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) `Result<(), S::Error>` #### Response Example None ## `test_join_with` Test method for joining. ### Method `pub fn test_join_with(&mut self, store: DS, context: &CausalContext)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) `()` #### Response Example None ``` -------------------------------- ### Create DotMap with Capacity Source: https://docs.rs/dson/latest/src/dson/dotstores.rs.html Constructs a new DotMap with a specified initial capacity for its internal state. This can help optimize performance by pre-allocating memory. ```rust pub fn with_capacity(capacity: usize) -> Self { Self { state: create_map_with_capacity(capacity), } } ``` -------------------------------- ### Get Maximum of Two Identifiers Source: https://docs.rs/dson/latest/dson/causal_context/struct.Identifier.html Compares two Identifiers and returns the maximum value. ```rust fn max(self, other: Self) -> Self where Self: Sized ``` -------------------------------- ### KeySentinel Trait Implementation for DummySentinel Source: https://docs.rs/dson/latest/dson/sentinel/struct.DummySentinel.html Implements the KeySentinel trait for DummySentinel, providing methods for key creation and deletion. ```APIDOC ### impl KeySentinel for DummySentinel #### fn create_key(&mut self) -> Result<(), Self::Error> Observe and validate the creation of a new entry under the current path. Read more #### fn delete_key(&mut self) -> Result<(), Self::Error> Observe and validate the deletion of the entry under the current path. ``` -------------------------------- ### Get Node Identifier Source: https://docs.rs/dson/latest/dson/causal_context/struct.NodeId.html Returns the main identifier for this node, specifically for application 0. ```rust pub fn identifier(self) -> Identifier ``` -------------------------------- ### Get Milliseconds from Timestamp Source: https://docs.rs/dson/latest/dson/api/timestamp/struct.Timestamp.html Returns the number of milliseconds since the UNIX epoch as an i64. ```rust pub fn as_millis(&self) -> i64 ``` -------------------------------- ### Generic Blanket Implementations Source: https://docs.rs/dson/latest/dson/causal_context/enum.ComparisonMode.html Demonstrates various blanket implementations for generic types, including Any, Borrow, BorrowMut, From, Into, TryFrom, TryInto, and VZip. ```rust impl Any for T where T: 'static + ?Sized, ``` ```rust fn type_id(&self) -> TypeId ``` ```rust impl Borrow for T where T: ?Sized, ``` ```rust fn borrow(&self) -> &T ``` ```rust impl BorrowMut for T where T: ?Sized, ``` ```rust fn borrow_mut(&mut self) -> &mut T ``` ```rust impl From for T ``` ```rust fn from(t: T) -> T ``` ```rust impl Into for T where U: From, ``` ```rust fn into(self) -> U ``` ```rust impl TryFrom for T where U: Into, ``` ```rust type Error = Infallible ``` ```rust fn try_from(value: U) -> Result>::Error> ``` ```rust impl TryInto for T where U: TryFrom, ``` ```rust type Error = >::Error ``` ```rust fn try_into(self) -> Result>::Error> ``` ```rust impl VZip for T where V: MultiLane, ``` ```rust fn vzip(self) -> V ``` -------------------------------- ### DotFun Methods Source: https://docs.rs/dson/latest/dson/struct.DotFun.html Provides methods for constructing, querying, and manipulating DotFun instances. ```APIDOC ## Implementations for DotFun ### `with_capacity(capacity: usize) -> Self` Constructs a `DotFun` with the given initial capacity. ### `iter(&self) -> impl ExactSizeIterator` Produces an iterator over the map’s keys and values. ### `keys(&self) -> impl ExactSizeIterator + '_` Produces an iterator over the map’s keys. ### `values(&self) -> DotFunValueIter<'_, V>` Produces an iterator over the map’s values. ### `len(&self) -> usize` Returns the number of keys in the map. ### `is_empty(&self) -> bool` Returns true if the map is empty. ### `get(&self, dot: &Dot) -> Option<&V>` Retrieves the associated value, if any, for the given `Dot`. ### `get_mut(&mut self, dot: &Dot) -> Option<&mut V>` Retrieves a mutable reference to the associated value, if any, for the given `Dot`. ### `has(&self, dot: &Dot) -> bool` Returns `true` if the given `Dot` has a value in this map. ### `set(&mut self, dot: Dot, value: V) -> Option` Associates the value with the given `Dot`. Returns the previous value if any. ### `remove(&mut self, dot: &Dot) -> Option` Removes and returns the value associated with a `Dot`, if the dot exists. ### `retain(&mut self, f: impl FnMut(&Dot, &mut V) -> bool)` Retains only the values for which a predicate is true. ```