### Example Search Queries for Type Signatures Source: https://docs.rs/autosurgeon/latest/src/autosurgeon/lib.rs_search= These are example search queries demonstrating how to find type signatures within the documentation. They cover searching for standard library types, simple type conversions, and more complex generic transformations. ```text std::vec u32 -> bool Option, (T -> U) -> Option ``` -------------------------------- ### Example Search Patterns in Rust Source: https://docs.rs/autosurgeon/latest/autosurgeon/reconcile/struct.StaleHeads_search= Demonstrates common search patterns used within the project for exploring Rust types and functionalities. These examples illustrate how to search for standard library types, type signatures, and generic function transformations. ```text * std::vec * u32 -> bool * Option, (T -> U) -> Option ``` -------------------------------- ### Slice Starts With API Source: https://docs.rs/autosurgeon/latest/autosurgeon/bytes/struct.ByteVec Determines if a slice begins with a specified prefix slice. An empty prefix is always considered to be at the start. ```APIDOC ## GET /slice/starts_with ### Description Returns `true` if the slice starts with the given `needle` slice or is equal to it. ### Method GET ### Endpoint `/slice/starts_with` ### Parameters #### Query Parameters - **needle** (array[T]) - Required - The slice to check as a prefix. ### Request Example (No request body for this operation) ### Response #### Success Response (200) - **result** (boolean) - `true` if the slice starts with the `needle`, `false` otherwise. #### Response Example ```json { "result": true } ``` ``` -------------------------------- ### Slice Starts With Source: https://docs.rs/autosurgeon/latest/autosurgeon/bytes/struct.ByteVec_search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Checks if a slice starts with a given prefix slice. ```APIDOC ## GET /slice/starts_with ### Description Returns `true` if `needle` is a prefix of the slice or equal to the slice. ### Method GET ### Endpoint `/slice/starts_with` #### Query Parameters - **needle** (array) - Required - The slice to check if it's a prefix. ### Request Example ```json { "needle": [10, 40] } ``` ### Response #### Success Response (200) - **starts_with** (boolean) - `true` if the slice starts with the needle, `false` otherwise. #### Response Example ```json { "starts_with": true } ``` **Note:** Always returns `true` if `needle` is an empty slice. ``` -------------------------------- ### Slice Starts With Source: https://docs.rs/autosurgeon/latest/autosurgeon/bytes/struct.ByteVec_search= Checks if a slice starts with a given prefix slice. ```APIDOC ## GET /slice/starts-with ### Description Checks if a slice starts with a given prefix slice. Always returns `true` if the prefix is empty. ### Method GET ### Endpoint `/slice/starts-with` ### Parameters #### Query Parameters - **prefix** (array) - Required - The prefix slice to check against. ### Request Example ```json { "prefix": [10, 40] } ``` ### Response #### Success Response (200) - **result** (boolean) - `true` if the slice starts with the prefix, `false` otherwise. #### Response Example ```json { "result": true } ``` ``` -------------------------------- ### Rust Autosurgeon Text Example: Concurrent Edits and Merging Source: https://docs.rs/autosurgeon/latest/src/autosurgeon/text.rs_search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Demonstrates how to use the Text type to perform concurrent edits on forked Automerge documents and merge the results. It shows creating an initial document, forking it, applying different text updates to each fork, and then merging them to achieve a combined result. This example highlights the power of Autosurgeon in managing collaborative text editing. ```rust # use autosurgeon::{Hydrate, Reconcile, Text}; #[derive(Hydrate, Reconcile)] struct TextDoc { content: Text, } let start = TextDoc { content: Text::with_value("some value"), }; // Create the initial document let mut doc = automerge::AutoCommit::new(); autosurgeon::reconcile(&mut doc, &start).unwrap(); // Fork the document so we can make concurrent changes let mut doc2 = doc.fork(); // On one fork replace 'value' with 'day' let mut start2 = autosurgeon::hydrate::<_, TextDoc>(&doc).unwrap(); // Note the use of `update` to replace the entire content instead of `splice` start2.content.update("some day"); autosurgeon::reconcile(&mut doc, &start2).unwrap(); // On the other fork replace 'some' with 'another' let mut start3 = autosurgeon::hydrate::<_, TextDoc>(&doc2).unwrap(); start3.content.update("another value"); autosurgeon::reconcile(&mut doc2, &start3).unwrap(); // Merge the two forks doc.merge(&mut doc2).unwrap(); // The result is 'another day' let start3 = autosurgeon::hydrate::<_, TextDoc>(&doc).unwrap(); assert_eq!(start3.content.as_str(), "another day"); ``` -------------------------------- ### CloneToUninit Source: https://docs.rs/autosurgeon/latest/autosurgeon/bytes/struct.ByteArray_search=std%3A%3Avec Documentation for the experimental `clone_to_uninit` method available only on nightly Rust. ```APIDOC ## unsafe fn clone_to_uninit(&self, dest: *mut u8) ### Description This is a nightly-only experimental API. Performs copy-assignment from `self` to `dest`. ### Method `unsafe fn` ### Endpoint N/A (method on a trait) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```rust // Example usage requires nightly Rust and unsafe blocks // let mut buffer = [0u8; SIZE]; // unsafe { my_data.clone_to_uninit(buffer.as_mut_ptr()); } ``` ### Response #### Success Response None (modifies memory in place) #### Response Example None ``` -------------------------------- ### Rust Automerge Derive Macro Representation Examples Source: https://docs.rs/autosurgeon/latest/autosurgeon/index_search=u32+-%3E+bool Illustrates how the 'autosurgeon' derive macros map different Rust data structures (structs, tuples, enums) to automerge's underlying representation. This shows how simple structs become JSON objects, tuples become arrays, and enums are represented with variants as keys. It serves as a guide to understanding the automerge output generated by the macros. ```rust struct W { a: i32, b: i32, } let w = W { a: 0, b: 0 }; // Represented as `{"a":0,"b":0}` struct X(i32, i32); let x = X(0, 0); // Represented as `[0,0]` struct Y(i32); let y = Y(0); // Represented as just the inner value `0` enum E { W { a: i32, b: i32 }, X(i32, i32), Y(i32), Z, } let w = E::W { a: 0, b: 0 }; // Represented as `{"W":{"a":0,"b":0}}` let x = E::X(0, 0); // Represented as `{"X":[0,0]}` let y = E::Y(0); // Represented as `{"Y":0}` let z = E::Z; // Represented as `"Z"` ``` -------------------------------- ### Rust Example: Concurrent Catalog Changes with Automerge Source: https://docs.rs/autosurgeon/latest/src/autosurgeon/lib.rs Demonstrates how concurrent changes to a `Catalog` containing `Product`s are managed using Automerge and the rs_autosurgeon crate. It shows branching, modifying, merging, and asserting the final state of the document. ```rust # use automerge_test::{assert_doc, map, list}; # use autosurgeon::{reconcile, Reconcile, Hydrate}; # #[derive(Reconcile, Hydrate, Clone, Debug, Eq, PartialEq)] # struct Product { # #[key] # id: u64, # name: String, # } # #[derive(Reconcile, Hydrate, Clone, Debug, Eq, PartialEq)] # struct Catalog { # products: Vec, # } # let mut catalog = Catalog { # products: vec![ # Product { # id: 1, # name: "Lawnmower".to_string(), # }, # Product { # id: 2, # name: "Strimmer".to_string(), # } # ] # }; # let mut doc = automerge::AutoCommit::new(); # reconcile(&mut doc, &catalog).unwrap(); # let mut doc2 = doc.fork().with_actor(automerge::ActorId::random()); # let mut catalog2 = catalog.clone(); # catalog2.products.insert(0, Product { # id: 3, # name: "Leafblower".to_string(), # }); # reconcile(&mut doc2, &catalog2).unwrap(); # catalog.products.remove(0); # reconcile(&mut doc, &catalog).unwrap(); # doc.merge(&mut doc2).unwrap(); assert_doc!( doc.document(), map! { "products" => { list! { { map! { "id" => { 3_u64 }, "name" => { "Leafblower" }, }}, { map! { "id" => { 2_u64 }, "name" => { "Strimmer" }, }} }} } ); ``` -------------------------------- ### ByteVec Core Methods Source: https://docs.rs/autosurgeon/latest/autosurgeon/bytes/struct.ByteVec_search=u32+-%3E+bool Provides documentation for fundamental methods of the ByteVec type, such as cloning and clone_from. ```APIDOC ## ByteVec Core Methods ### clone - **Description**: Returns a duplicate of the value. - **Method**: N/A (method of the type) - **Endpoint**: N/A ### clone_from - **Description**: Performs copy-assignment from `source`. - **Method**: N/A (method of the type) - **Endpoint**: N/A ``` -------------------------------- ### Reconcile Example for User Struct Source: https://docs.rs/autosurgeon/latest/autosurgeon/reconcile/trait.Reconcile_search=u32+-%3E+bool An example implementation of the `Reconcile` trait for a `User` struct, demonstrating how to define the key and implement the `reconcile` method. ```APIDOC ## Example Implementation ```rust use std::borrow::Cow; struct User { id: String, name: String } impl Reconcile for User { type Key<'a> = Cow<'a, String>; fn reconcile(&self, mut reconciler: R) -> Result<(), R::Error> { let mut m = reconciler.map()?; m.put("id", &self.id)?; m.put("name", &self.id)?; Ok(()) } fn hydrate_key<'a, D: ReadDoc>( doc: &D, obj: &automerge::ObjId, prop: Prop<'_>, ) -> Result>, ReconcileError> { hydrate_key(doc, obj, prop, "id".into()) } fn key(&self) -> LoadKey> { LoadKey::Found(Cow::Borrowed(&self.id)) } } ``` ``` -------------------------------- ### Rust: Counter Struct Initialization and Usage Example Source: https://docs.rs/autosurgeon/latest/autosurgeon/struct.Counter Demonstrates how to initialize a Counter, use it within a struct that implements Reconcile and Hydrate, fork a document, concurrently increment the counter in different branches, and merge them to observe the summed result. ```Rust use autosurgeon::{Counter, Reconcile, Hydrate, ActorId}; use automerge::{AutoCommit, ScalarValue, ObjId, Prop, Reconciler, HydrateError, ReadDoc}; use std::borrow::Cow; #[derive(Debug, Reconcile, Hydrate)] struct Stats { num_clicks: Counter, } fn main() -> Result<(), Box> { let mut doc = AutoCommit::new(); let mut stats = Stats { num_clicks: Counter::default() }; autosurgeon::reconcile(&mut doc, &stats)?; // Fork the doc and increment the counter let mut doc2 = doc.fork().with_actor(ActorId::random()); let mut stats2: Stats = autosurgeon::hydrate(&doc)?; stats2.num_clicks.increment(5); autosurgeon::reconcile(&mut doc2, &stats2)?; // Concurrently increment in the original doc let mut stats: Stats = autosurgeon::hydrate(&doc)?; stats.num_clicks.increment(3); autosurgeon::reconcile(&mut doc, &stats)?; // Merge the two docs doc.merge(&mut doc2)?; // Observe that `num_clicks` is the sum of the concurrent increments let stats: Stats = autosurgeon::hydrate(&doc)?; assert_eq!(stats.num_clicks.value(), 8); Ok(()) } ``` -------------------------------- ### Example Usage of Reconcile Trait Source: https://docs.rs/autosurgeon/latest/autosurgeon/trait.Reconcile_search= An example demonstrating how to implement the `Reconcile` trait for a `User` struct, including defining the key and implementing the `reconcile`, `hydrate_key`, and `key` methods. ```APIDOC ## Example ```rust use std::borrow::Cow; struct User { id: String, name: String } impl Reconcile for User { type Key<'a> = Cow<'a, String>; fn reconcile(&self, mut reconciler: R) -> Result<(), R::Error> { let mut m = reconciler.map()?; m.put("id", &self.id)?; m.put("name", &self.id)?; Ok(()) } fn hydrate_key<'a, D: ReadDoc>( doc: &D, obj: &automerge::ObjId, prop: Prop<'_>, ) -> Result>, ReconcileError> { hydrate_key(doc, obj, prop, "id".into()) } fn key(&self) -> LoadKey> { LoadKey::Found(Cow::Borrowed(&self.id)) } } ``` ``` -------------------------------- ### Get Underlying Array Reference (Rust) Source: https://docs.rs/autosurgeon/latest/autosurgeon/bytes/struct.ByteVec_search= Attempts to get a reference to the underlying array if the requested size `N` exactly matches the slice length. Returns `None` otherwise. ```rust pub fn as_array(&self) -> Option<&[T; N]> ``` -------------------------------- ### Rust: Text struct initialization and usage example Source: https://docs.rs/autosurgeon/latest/src/autosurgeon/text.rs_search= Demonstrates how to initialize a `Text` struct, reconcile it with an automerge document, fork the document, make concurrent modifications to the text, and merge the changes. It highlights the use of `hydrate`, `reconcile`, `fork`, `splice`, and `merge`. ```rust use automerge::ActorId; use autosurgeon::{reconcile, hydrate, Text, Reconcile, Hydrate}; #[derive(Debug, Reconcile, Hydrate)] struct Quote { text: Text, } let mut doc = automerge::AutoCommit::new(); let quote = Quote { text: "glimmers".into() }; reconcile(&mut doc, "e).unwrap(); // Fork and make changes to the text let mut doc2 = doc.fork().with_actor(ActorId::random()); let mut quote2: Quote = hydrate(&doc2).unwrap(); quote2.text.splice(0, 0, "All that "); let end_index = quote2.text.as_str().char_indices().last().unwrap().0; quote2.text.splice(end_index + 1, 0, " is not gold"); reconcile(&mut doc2, "e2).unwrap(); // Concurrently modify the text in the original doc let mut quote: Quote = hydrate(&doc).unwrap(); let m_index = quote.text.as_str().char_indices().nth(3).unwrap().0; quote.text.splice(m_index, 2, "tt"); reconcile(&mut doc, quote).unwrap(); // Merge the changes doc.merge(&mut doc2).unwrap(); let quote: Quote = hydrate(&doc).unwrap(); assert_eq!(quote.text.as_str(), "All that glitters is not gold"); ``` -------------------------------- ### Rust: Initializing and Merging Catalog Data with Automerge Source: https://docs.rs/autosurgeon/latest/autosurgeon_search= Demonstrates initializing a `Catalog` with products, committing it to an `automerge` document, forking the document, and then performing concurrent modifications and merging. This showcases potential merge conflicts when list order is not explicitly handled. ```rust let mut catalog = Catalog { products: vec![ Product { id: 1, name: "Lawnmower".to_string(), }, Product { id: 2, name: "Strimmer".to_string(), } ] }; // Put the catalog into the document let mut doc = automerge::AutoCommit::new(); reconcile(&mut doc, &catalog).unwrap(); // Fork the document and insert a new product at the start of the catalog let mut doc2 = doc.fork().with_actor(automerge::ActorId::random()); let mut catalog2 = catalog.clone(); catalog2.products.insert(0, Product { id: 3, name: "Leafblower".to_string(), }); reconcile(&mut doc2, &catalog2).unwrap(); // Concurrenctly remove a product from the catalog in the original doc catalog.products.remove(0); reconcile(&mut doc, &catalog).unwrap(); // Merge the two changes doc.merge(&mut doc2).unwrap(); assert_doc!( doc.document(), map! { "products" => { list! { // This first item is conflicted, we expected it to be the leafblower { map! { "id" => { 2_u64, 3_u64 }, // Conflict on the ID "name" => { "Strimmer", "Leafblower" }, // Conflict on the name }}, { map! { "id" => { 2_u64 }, "name" => { "Strimmer" }, }} }} } ); ``` -------------------------------- ### Get Mutable Underlying Array Reference (Rust) Source: https://docs.rs/autosurgeon/latest/autosurgeon/bytes/struct.ByteVec_search= Attempts to get a mutable reference to the underlying array if the requested size `N` exactly matches the slice length. Returns `None` otherwise. ```rust pub fn as_mut_array(&mut self) -> Option<&mut [T; N]> ``` -------------------------------- ### Get Target Value from Automerge Object Source: https://docs.rs/autosurgeon/latest/src/autosurgeon/reconcile.rs_search=u32+-%3E+bool Retrieves the target value and its ObjId from an Automerge object based on a PropAction. It handles 'get' operations for existing properties and returns None if creation is intended. ```rust impl PropAction<'_> { fn get_target<'b, D: Doc>( &self, doc: &'b D, obj: &automerge::ObjId, ) -> Result, automerge::ObjId)>, automerge::AutomergeError> { match self { Self::Put { prop, create: false, } => doc.get(obj, prop), Self::Put { prop: _, create: true, } => Ok(None), Self::Insert(_idx) => Ok(None), } } ``` -------------------------------- ### Check if a slice starts with a given prefix (Rust) Source: https://docs.rs/autosurgeon/latest/autosurgeon/bytes/struct.ByteVec_search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E The `starts_with` method verifies if a slice begins with the elements of another slice (`needle`). It returns `true` if `needle` is an empty slice, as an empty slice is considered a prefix of any slice. The comparison requires elements to implement `PartialEq`. ```rust let v = [10, 40, 30]; assert!(v.starts_with(&[10])); assert!(v.starts_with(&[10, 40])); assert!(v.starts_with(&v)); assert!(!v.starts_with(&[50])); assert!(!v.starts_with(&[10, 50])); ``` ```rust let v = &[10, 40, 30]; assert!(v.starts_with(&[])); let v: &[u8] = &[]; assert!(v.starts_with(&[])); ``` -------------------------------- ### Rust: Hydrate, Reconcile, and update Text with AutoCommit Source: https://docs.rs/autosurgeon/latest/src/autosurgeon/text.rs This example demonstrates how to use the `autosurgeon` crate with `automerge::AutoCommit` to manage text documents. It shows initializing a document, forking it for concurrent edits, updating text content using the `update` method, and merging the changes. The final result verifies that concurrent edits are correctly merged. ```rust use autosurgeon::{Hydrate, Reconcile, Text}; #[derive(Hydrate, Reconcile)] struct TextDoc { content: Text, } let start = TextDoc { content: Text::with_value("some value"), }; // Create the initial document let mut doc = automerge::AutoCommit::new(); autosurgeon::reconcile(&mut doc, &start).unwrap(); // Fork the document so we can make concurrent changes let mut doc2 = doc.fork(); // On one fork replace 'value' with 'day' let mut start2 = autosurgeon::hydrate::<_, TextDoc>(&doc).unwrap(); // Note the use of `update` to replace the entire content instead of `splice` start2.content.update("some day"); autosurgeon::reconcile(&mut doc, &start2).unwrap(); // On the other fork replace 'some' with 'another' let mut start3 = autosurgeon::hydrate::<_, TextDoc>(&doc2).unwrap(); start3.content.update("another value"); autosurgeon::reconcile(&mut doc2, &start3).unwrap(); // Merge the two forks doc.merge(&mut doc2).unwrap(); // The result is 'another day' let start3 = autosurgeon::hydrate::<_, TextDoc>(&doc).unwrap(); assert_eq!(start3.content.as_str(), "another day"); ``` -------------------------------- ### Get Mutable Element or Subslice by Index (Rust) Source: https://docs.rs/autosurgeon/latest/autosurgeon/bytes/struct.ByteVec_search= Safely retrieves a mutable reference to an element or a subslice. Similar to `get`, but allows modification. Returns `Some` with a mutable reference if the index is valid, otherwise `None`. ```rust pub fn get_mut(&mut self, index: I) -> Option<&mut >::Output> where I: SliceIndex<[T]> { // Implementation details here } // Example usage: let mut x = &mut [0, 1, 2]; if let Some(elem) = x.get_mut(1) { *elem = 42; } assert_eq!(x, &[0, 42, 2]); ``` -------------------------------- ### Initialize Text with Value in Rust Source: https://docs.rs/autosurgeon/latest/autosurgeon/struct.Text_search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Shows how to create a new Text object with an initial string value using the `with_value` constructor. This is the primary method for instantiating a Text object with pre-existing content. ```rust let mut value = Text::with_value("some value"); ``` -------------------------------- ### ByteVec Core Methods Source: https://docs.rs/autosurgeon/latest/autosurgeon/bytes/struct.ByteVec_search=std%3A%3Avec Provides information on core methods for ByteVec, such as cloning and comparison. ```APIDOC ## ByteVec Core Methods ### clone() - **Description**: Returns a duplicate of the value. - **Method**: N/A (inherent method) - **Endpoint**: N/A ### clone_from() - **Description**: Performs copy-assignment from `source`. - **Method**: N/A (inherent method) - **Endpoint**: N/A ### fmt() - **Description**: Formats the value using the given formatter. - **Method**: N/A (inherent method) - **Endpoint**: N/A ### deref() - **Description**: Dereferences the value. Returns a `Vec`. - **Method**: N/A (inherent method) - **Endpoint**: N/A ### from(ByteVec) -> Vec - **Description**: Converts a `ByteVec` into a `Vec`. - **Method**: N/A (inherent method) - **Endpoint**: N/A ### from(Vec) -> ByteVec - **Description**: Converts a `Vec` into a `ByteVec`. - **Method**: N/A (inherent method) - **Endpoint**: N/A ### hash() - **Description**: Feeds this value into the given `Hasher`. - **Method**: N/A (inherent method) - **Endpoint**: N/A ### hash_slice() - **Description**: Feeds a slice of this type into the given `Hasher`. - **Method**: N/A (inherent method) - **Endpoint**: N/A ### cmp() - **Description**: Compares `self` and `other` and returns an `Ordering`. - **Method**: N/A (inherent method) - **Endpoint**: N/A ### max() - **Description**: Compares and returns the maximum of two values. - **Method**: N/A (inherent method) - **Endpoint**: N/A ### min() - **Description**: Compares and returns the minimum of two values. - **Method**: N/A (inherent method) - **Endpoint**: N/A ### clamp() - **Description**: Restricts a value to a certain interval. - **Method**: N/A (inherent method) - **Endpoint**: N/A ### eq() - **Description**: Tests if `self` and `other` values are equal. - **Method**: N/A (inherent method) - **Endpoint**: N/A ### ne() - **Description**: Tests if `self` and `other` values are not equal. - **Method**: N/A (inherent method) - **Endpoint**: N/A ### partial_cmp() - **Description**: Returns an `Option` between `self` and `other` if one exists. - **Method**: N/A (inherent method) - **Endpoint**: N/A ### lt() - **Description**: Tests if `self` is less than `other`. - **Method**: N/A (inherent method) - **Endpoint**: N/A ### le() - **Description**: Tests if `self` is less than or equal to `other`. - **Method**: N/A (inherent method) - **Endpoint**: N/A ### gt() - **Description**: Tests if `self` is greater than `other`. - **Method**: N/A (inherent method) - **Endpoint**: N/A ### ge() - **Description**: Tests if `self` is greater than or equal to `other`. - **Method**: N/A (inherent method) - **Endpoint**: N/A ### reconcile() - **Description**: Reconciles this item with the document. - **Method**: N/A (inherent method) - **Endpoint**: N/A ### hydrate_key() - **Description**: Hydrates the key for this Object. - **Method**: N/A (inherent method) - **Endpoint**: N/A ### key() - **Description**: Gets the key from an instance of `Self`. - **Method**: N/A (inherent method) - **Endpoint**: N/A ### type_id() - **Description**: Gets the `TypeId` of `self`. - **Method**: N/A (inherent method) - **Endpoint**: N/A ``` -------------------------------- ### Concurrent Updates and Merging with AutoSurgeon (Rust) Source: https://docs.rs/autosurgeon/latest/src/autosurgeon/lib.rs This example outlines the process of handling concurrent changes in Automerge documents using the `autosurgeon` library. It involves forking a document, making independent modifications to each fork, and then merging them back together. The provided code snippet sets up the initial state for this scenario, demonstrating the creation and reconciliation of contact data into an Automerge document, preparing for subsequent divergent edits and merges. ```rust # use autosurgeon::{Reconcile, Hydrate, reconcile, hydrate}; # #[derive(Debug, Clone, Reconcile, Hydrate, PartialEq)] # struct Contact { # name: String, # address: Address, # } # #[derive(Debug, Clone, Reconcile, Hydrate, PartialEq)] # struct Address { # line_one: String, # line_two: Option, # city: String, # } # # let mut contact = Contact { # name: "Sherlock Holmes".to_string(), # address: Address{ # line_one: "221B Baker St".to_string(), # line_two: None, # city: "London".to_string(), # }, # }; # # let mut doc = automerge::AutoCommit::new(); # reconcile(&mut doc, &contact).unwrap(); ``` -------------------------------- ### Counter Struct Definition and Usage Example Source: https://docs.rs/autosurgeon/latest/autosurgeon/struct.Counter_search=std%3A%3Avec Defines the `Counter` struct, which reconciles to an `automerge::ScalarValue::Counter`. The example demonstrates initializing a `Counter`, forking a document, incrementing the counter concurrently in two forks, merging them, and asserting the sum of increments. ```rust pub struct Counter(/* private fields */); #[derive(Debug, Reconcile, Hydrate)] struct Stats { num_clicks: Counter, } // Example usage: let mut doc = automerge::AutoCommit::new(); let mut stats = Stats { num_clicks: Counter::default() }; reconcile(&mut doc, &stats).unwrap(); // Fork the doc and increment the counter let mut doc2 = doc.fork().with_actor(ActorId::random()); let mut stats2: Stats = hydrate(&doc).unwrap(); stats2.num_clicks.increment(5); reconcile(&mut doc2, &stats2).unwrap(); // Concurrently increment in the original doc let mut stats: Stats = hydrate(&doc).unwrap(); stats.num_clicks.increment(3); reconcile(&mut doc, &stats).unwrap(); // Merge the two docs doc.merge(&mut doc2).unwrap(); // Observe that `num_clicks` is the sum of the concurrent increments let stats: Stats = hydrate(&doc).unwrap(); assert_eq!(stats.num_clicks.value(), 8); ``` -------------------------------- ### Rust: Generic Type Conversions (From, Into, TryFrom, TryInto) Source: https://docs.rs/autosurgeon/latest/autosurgeon/hydrate/enum.MaybeMissing_search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Demonstrates common Rust type conversion patterns using From, Into, TryFrom, and TryInto traits. These are fundamental for flexible data manipulation and error handling during conversions. ```rust impl From for T { fn from(t: T) -> T { // Implementation: Returns the argument unchanged. t } } impl Into for T where U: From, { fn into(self) -> U { // Implementation: Calls U::from(self). U::from(self) } } impl TryFrom for T where U: Into, { type Error = Infallible; fn try_from(value: U) -> Result { // Implementation: Performs the conversion. Ok(value.into()) } } impl TryInto for T where U: TryFrom, { type Error = >::Error; fn try_into(self) -> Result { // Implementation: Performs the conversion. U::try_from(self) } } ``` -------------------------------- ### Get Slice as Array Reference (Rust) Source: https://docs.rs/autosurgeon/latest/autosurgeon/bytes/struct.ByteVec_search=u32+-%3E+bool Attempts to get a reference to the underlying array of the slice. Returns `Some(&[T; N])` if the slice's length exactly matches `N`, otherwise returns `None`. Useful for direct array access when the size is known and verified. ```rust let data: &[i32] = &[1, 2, 3]; let array_ref: Option<&[i32; 3]> = data.as_array(); // array_ref will be Some(&[1, 2, 3]) let short_slice: &[i32] = &[1, 2]; let array_ref_mismatch: Option<&[i32; 3]> = short_slice.as_array(); // array_ref_mismatch will be None ``` -------------------------------- ### Generic Blanket Implementations (Any, Borrow, BorrowMut, CloneToUninit) Source: https://docs.rs/autosurgeon/latest/autosurgeon/bytes/struct.ByteArray_search= Demonstrates blanket implementations for generic types, applicable to ByteArray and others. This includes implementations for Any, Borrow, BorrowMut, and CloneToUninit, providing foundational functionalities like type identification and borrowing. ```rust impl Any for T where T: 'static + ?Sized fn type_id(&self) -> TypeId impl Borrow for T where T: ?Sized fn borrow(&self) -> &T impl BorrowMut for T where T: ?Sized fn borrow_mut(&mut self) -> &mut T impl CloneToUninit for T where T: Clone ``` -------------------------------- ### Unsafe Get Element or Subslice by Index (Rust) Source: https://docs.rs/autosurgeon/latest/autosurgeon/bytes/struct.ByteVec_search= Retrieves a reference to an element or subslice without performing bounds checking. This method is unsafe and requires the caller to guarantee the index is within bounds to avoid undefined behavior. It is generally faster than `get`. ```rust pub unsafe fn get_unchecked(&self, index: I) -> &>::Output where I: SliceIndex<[T]> { // Implementation details here } // Example usage: let x = &[1, 2, 4]; unsafe { assert_eq!(x.get_unchecked(1), &2); } ``` -------------------------------- ### Rust: Get Underlying Array (Option) Source: https://docs.rs/autosurgeon/latest/autosurgeon/bytes/struct.ByteVec_search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E This method attempts to get a reference to the underlying array of the slice. It returns `Some` if the provided size matches the slice's length; otherwise, it returns `None`. Useful for interacting with the array directly when the size is known. ```rust #### pub fn as_array(&self) -> Option<&[T; N]> ``` -------------------------------- ### Implement From<&Prop> for Prop in Rust Source: https://docs.rs/autosurgeon/latest/autosurgeon/enum.Prop_search=u32+-%3E+bool Provides implementations for converting from a reference to a Prop to an owned Prop, and from a string slice to a Prop. ```rust impl From<&Prop<'_>> for Prop { fn from(p: &Prop<'_>) -> Self { // ... implementation ... } } impl<'a> From<&'a Prop> for Prop<'a> { fn from(p: &'a Prop) -> Self { // ... implementation ... } } impl<'a> From<&'a str> for Prop<'a> { fn from(s: &'a str) -> Self { // ... implementation ... } } impl<'a> From> for Prop<'a> { fn from(v: Cow<'a, str>) -> Self { // ... implementation ... } } impl From for Prop<'_> { fn from(p: Prop) -> Self { // ... implementation ... } } impl From for Prop<'static> { fn from(v: u32) -> Self { // ... implementation ... } } impl From for Prop<'static> { fn from(v: usize) -> Self { // ... implementation ... } } ``` -------------------------------- ### Rust: Safely Get Mutable Element or Subslice by Index Source: https://docs.rs/autosurgeon/latest/autosurgeon/bytes/struct.ByteVec_search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Safely retrieves a mutable reference to an element or subslice using various index types. Returns None if the index is out of bounds. Similar to `get`, but allows modification of the slice's contents. ```rust pub fn get_mut( &mut self, index: I, ) -> Option<&mut >::Output> let x = &mut [0, 1, 2]; if let Some(elem) = x.get_mut(1) { *elem = 42; } assert_eq!(x, &[0, 42, 2]); ``` -------------------------------- ### ByteVec Blanket Implementations Source: https://docs.rs/autosurgeon/latest/autosurgeon/bytes/struct.ByteVec_search=u32+-%3E+bool Details blanket implementations, such as the Any trait, for ByteVec. ```APIDOC ## ByteVec Blanket Implementations ### Any - **Description**: Provides dynamic type information. - **Method**: `type_id` - **Description**: Gets the `TypeId` of `self`. - **Returns**: `TypeId` ``` -------------------------------- ### Counter Struct Definition and Usage Example - Rust Source: https://docs.rs/autosurgeon/latest/autosurgeon/struct.Counter_search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Defines the Counter struct, which reconciles to an automerge::ScalarValue::Counter. The example demonstrates initializing a Counter, performing concurrent increments in forked documents, merging them, and asserting the summed value. It requires the 'reconcile' and 'automerge' crates. ```rust pub struct Counter(/* private fields */); #[derive(Debug, Reconcile, Hydrate)] struct Stats { num_clicks: Counter, } let mut doc = automerge::AutoCommit::new(); let mut stats = Stats {num_clicks: Counter::default() }; reconcile(&mut doc, &stats).unwrap(); // Fork the doc and increment the counter let mut doc2 = doc.fork().with_actor(ActorId::random()); let mut stats2: Stats = hydrate(&doc).unwrap(); stats2.num_clicks.increment(5); reconcile(&mut doc2, &stats2).unwrap(); // Concurrently increment in the original doc let mut stats: Stats = hydrate(&doc).unwrap(); stats.num_clicks.increment(3); reconcile(&mut doc, &stats).unwrap(); // Merge the two docs doc.merge(&mut doc2).unwrap(); // Observe that `num_clicks` is the sum of the concurrent increments let stats: Stats = hydrate(&doc).unwrap(); assert_eq!(stats.num_clicks.value(), 8); ``` -------------------------------- ### Generic Rust Trait Implementations (Any, Borrow, CloneToUninit) Source: https://docs.rs/autosurgeon/latest/autosurgeon/bytes/struct.ByteArray_search=u32+-%3E+bool Demonstrates blanket implementations of generic traits for `ByteArray` and other types. This includes implementations for `Any` (allowing runtime type identification), `Borrow` and `BorrowMut` (for accessing underlying data), and `CloneToUninit` (for efficient cloning to uninitialized memory). ```rust impl Any for T where T: 'static + ?Sized, fn type_id(&self) -> TypeId impl Borrow for T where T: ?Sized, fn borrow(&self) -> &T impl BorrowMut for T where T: ?Sized, fn borrow_mut(&mut self) -> &mut T impl CloneToUninit for T where T: Clone, ``` -------------------------------- ### unsafe fn clone_to_uninit Source: https://docs.rs/autosurgeon/latest/autosurgeon/bytes/struct.ByteArray_search= This is a nightly-only experimental API that performs copy-assignment from `self` to `dest`. ```APIDOC ## unsafe fn clone_to_uninit ### Description This is a nightly-only experimental API. (`clone_to_uninit`) Performs copy-assignment from `self` to `dest`. ### Method `unsafe fn` ### Endpoint N/A (Standard Library Function) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (N/A) This function does not return a value in the traditional sense; it modifies the `dest` pointer. #### Response Example None ``` -------------------------------- ### Rust MaybeMissing Usage Example with Automerge Source: https://docs.rs/autosurgeon/latest/autosurgeon/enum.MaybeMissing_search= Demonstrates how to use the `MaybeMissing` enum with the `automerge` library in Rust. The example shows how `MaybeMissing` correctly identifies when a value is absent from the document versus when it is present. It also illustrates how to hydrate values from an `automerge` document. ```rust let mut doc = automerge::AutoCommit::new(); let name = MaybeMissing::::hydrate(&doc, &automerge::ROOT, "name".into()).unwrap(); assert_eq!(name, MaybeMissing::Missing); doc.put(&automerge::ROOT, "name", "Moist von Lipwig").unwrap(); let name = MaybeMissing::::hydrate(&doc, &automerge::ROOT, "name".into()).unwrap(); assert_eq!(name, MaybeMissing::Present("Moist von Lipwig".to_string())); ``` -------------------------------- ### Rust: Get Mutable Underlying Array (Option) Source: https://docs.rs/autosurgeon/latest/autosurgeon/bytes/struct.ByteVec_search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E This method attempts to get a mutable reference to the slice's underlying array. It returns `Some` if the provided size matches the slice's length; otherwise, it returns `None`. Useful for modifying the array when the size is known. ```rust #### pub fn as_mut_array(&mut self) -> Option<&mut [T; N]> ``` -------------------------------- ### ByteVec Partial Ordering Implementation Source: https://docs.rs/autosurgeon/latest/autosurgeon/bytes/struct.ByteVec_search=u32+-%3E+bool Details the PartialOrd trait implementation for ByteVec, enabling partial ordering comparisons. ```APIDOC ## ByteVec Partial Ordering Implementation ### partial_cmp - **Description**: Returns an `Option` between `self` and `other` if one exists. - **Method**: N/A (method of the trait implementation) - **Endpoint**: N/A - **Parameters**: - **other** (&ByteVec) - Required - The other ByteVec to compare. - **Returns**: `Option` ### lt - **Description**: Tests if `self` is less than `other`. - **Method**: N/A (method of the trait implementation) - **Endpoint**: N/A - **Parameters**: - **other**: &Rhs - The other value. - **Returns**: `bool` ### le - **Description**: Tests if `self` is less than or equal to `other`. - **Method**: N/A (method of the trait implementation) - **Endpoint**: N/A - **Parameters**: - **other**: &Rhs - The other value. - **Returns**: `bool` ### gt - **Description**: Tests if `self` is greater than `other`. - **Method**: N/A (method of the trait implementation) - **Endpoint**: N/A - **Parameters**: - **other**: &Rhs - The other value. - **Returns**: `bool` ### ge - **Description**: Tests if `self` is greater than or equal to `other`. - **Method**: N/A (method of the trait implementation) - **Endpoint**: N/A - **Parameters**: - **other**: &Rhs - The other value. - **Returns**: `bool` ``` -------------------------------- ### ByteVec Conversion Implementations Source: https://docs.rs/autosurgeon/latest/autosurgeon/bytes/struct.ByteVec_search=u32+-%3E+bool Documents the conversion traits for ByteVec, allowing conversion to and from Vec. ```APIDOC ## ByteVec Conversion Implementations ### From for Vec - **Description**: Converts a `ByteVec` into a `Vec`. - **Method**: `from` ### From> for ByteVec - **Description**: Converts a `Vec` into a `ByteVec`. - **Method**: `from` ``` -------------------------------- ### Slice Starts With Source: https://docs.rs/autosurgeon/latest/autosurgeon/bytes/struct.ByteVec_search=u32+-%3E+bool Checks if a slice begins with a given prefix. ```APIDOC ## GET /slice/starts_with ### Description Returns `true` if `needle` is a prefix of the slice or equal to the slice. Always returns `true` if `needle` is an empty slice. ### Method GET ### Endpoint `/slice/starts_with` #### Query Parameters - **needle** (array of T) - Required - The slice to check as a prefix. ### Response #### Success Response (200) - **result** (boolean) - `true` if the slice starts with the needle, `false` otherwise. #### Response Example ```json { "result": true } ``` ``` -------------------------------- ### Rust: Initialize Text struct Source: https://docs.rs/autosurgeon/latest/autosurgeon/struct.Text_search=std%3A%3Avec Shows how to create a new 'Text' object, either with an initial string value or using the default empty value. ```rust let mut value = autosurgeon::Text::with_value("some value"); // or let default_text = autosurgeon::Text::default(); ``` -------------------------------- ### Rust: Reconcile Trait - hydrate_key Method Example Source: https://docs.rs/autosurgeon/latest/autosurgeon/trait.Reconcile_search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Provides an example implementation of the `hydrate_key` method for the `Reconcile` trait. This method is crucial for the autosurgeon library to determine if existing data in a document matches an instance of the type implementing `Reconcile`, using a specified key. ```rust fn hydrate_key<'a, D: ReadDoc>( doc: &D, obj: &automerge::ObjId, prop: Prop<'_>, ) -> Result>, ReconcileError> { hydrate_key(doc, obj, prop, "id".into()) } ``` -------------------------------- ### Rust: Create Text with Initial Value Source: https://docs.rs/autosurgeon/latest/src/autosurgeon/text.rs_search=std%3A%3Avec Shows how to create a new `Text` instance with an initial string value. This is typically used when first populating the text content before it's integrated into an Automerge document. ```rust pub fn with_value>(value: S) -> Text { Self(State::Fresh(value.as_ref().to_string())) } ``` -------------------------------- ### Sequence Reconciliation Methods (Rust) Source: https://docs.rs/autosurgeon/latest/src/autosurgeon/reconcile.rs_search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Defines traits for reconciling data within an Automerge list. Includes iterating over items, getting items by index, hydrating item keys, inserting, setting, deleting, and getting the length. Requires `Reconcile` trait and `StaleHeads` error. ```rust /// A node in the document which is an `automerge::List` pub trait SeqReconciler { type Error: std::error::Error + From; type ItemIter<'a>: Iterator> where Self: 'a; /// An iterator over the items currently in this node in the document fn items(&self) -> Self::ItemIter<'_>; /// Get a single item from the document fn get(&self, index: usize) -> Result>, Self::Error>; /// For some `R`, hydrate the key at the given index /// /// This is used to determine if some data in the document matches the data we are reconciling. /// Suppose we have some type `R: Reconcile`, we pass `R` as a type parameter to /// `hydrate_item_key` and we will get back a `LoadKey`, we can then compare this to /// the key of the data we are reconciling using `R::key` to determine if this index represents /// the same identity as the item we are reconciling. fn hydrate_item_key<'a, R: Reconcile>( &self, index: usize, ) -> Result>, Self::Error>; /// Insert the given value at the given index in the document fn insert(&mut self, index: usize, value: R) -> Result<(), Self::Error>; /// Reconcile the value of an index with some `R` fn set(&mut self, index: usize, value: R) -> Result<(), Self::Error>; /// Delete an index from the sequence fn delete(&mut self, index: usize) -> Result<(), Self::Error>; /// Get the current length of the sequence fn len(&self) -> Result; fn is_empty(&self) -> Result { Ok(self.len()? == 0) } } ```