### Example Searches Source: https://docs.rs/hdi/latest/hdi/prelude/builder/struct.OpenChain_search= Provides examples of common search queries that can be performed within the system, demonstrating various search patterns. ```APIDOC ## Example Searches ### Description Provides examples of common search queries that can be performed within the system, demonstrating various search patterns. ### Method Not Applicable (These are search examples, not API endpoints) ### Endpoint Not Applicable ### Parameters None ### Request Example ``` * std::vec * u32 -> bool * Option, (T -> U) -> Option ``` ### Response This section is not applicable as these are examples of search queries. ``` -------------------------------- ### Arc Examples Source: https://docs.rs/hdi/latest/hdi/prelude/type.MembraneProof_search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Examples demonstrating the behavior and use cases of Arc, including `into_inner` and manual drop implementations for linked lists. ```APIDOC ## Arc Examples ### Minimal Example: `Arc::into_inner` Guarantee This example shows that `Arc::into_inner` will return `Some(value)` for one thread and `None` for the other when called on cloned `Arc` instances. ```rust use std::sync::Arc; let x = Arc::new(3); let y = Arc::clone(&x); // Two threads calling `Arc::into_inner` on both clones of an `Arc`: let x_thread = std::thread::spawn(|| Arc::into_inner(x)); let y_thread = std::thread::spawn(|| Arc::into_inner(y)); let x_inner_value = x_thread.join().unwrap(); let y_inner_value = y_thread.join().unwrap(); // One of the threads is guaranteed to receive the inner value: assert!(matches!( (x_inner_value, y_inner_value), (None, Some(3)) | (Some(3), None) )); // Note: If `Arc::try_unwrap(x).ok()` was used instead, the result could be `(None, None)`. ``` ### Practical Example: Preventing Stack Overflow with `Arc::into_inner` This example demonstrates how `Arc::into_inner` can be used within a manual `Drop` implementation for a linked list to prevent stack overflows caused by deep recursion when dropping large lists. ```rust use std::sync::Arc; // Definition of a simple singly linked list using `Arc`: #[derive(Clone)] struct LinkedList(Option>>); struct Node(T, Option>>); // Manual `Drop` implementation to avoid stack overflow: impl Drop for LinkedList { fn drop(&mut self) { let mut link = self.0.take(); while let Some(arc_node) = link.take() { if let Some(Node(_value, next)) = Arc::into_inner(arc_node) { link = next; } } } } // Placeholder for omitted `new` and `push` methods impl LinkedList { fn new() -> Self { LinkedList(None) } // Example placeholder fn push(&mut self, _value: T) { /* ... */ } // Example placeholder } // Create a long list and clone it let mut x = LinkedList::new(); let size = 100000; for i in 0..size { x.push(i); // Adds i to the front of x } let y = x.clone(); // Drop the clones in parallel to demonstrate the manual Drop impl let x_thread = std::thread::spawn(|| drop(x)); let y_thread = std::thread::spawn(|| drop(y)); x_thread.join().unwrap(); y_thread.join().unwrap(); ``` ``` -------------------------------- ### HashSet: Default Implementation Example Source: https://docs.rs/hdi/latest/hdi/prelude/struct.HashSet Provides an example of creating an empty `HashSet` using the `default` method. This is useful when a `HashSet` is needed but its initial contents are not yet known, or when using it with structures that require a default value. ```rust use std::collections::HashSet; let default_set: HashSet = Default::default(); assert!(default_set.is_empty()); ``` -------------------------------- ### Rust: Example Type Signature Searches Source: https://docs.rs/hdi/latest/hdi/prelude/builder/struct.AgentValidationPkg_search= These are example search queries demonstrating how to find Rust type signatures. They cover common patterns like vector usage, primitive type conversions, and option transformations. ```rust * std::vec ``` ```rust * u32 -> bool ``` ```rust * Option, (T -> U) -> Option ``` -------------------------------- ### Example Usage of hash_entry with hdi_entry_helper Source: https://docs.rs/hdi/latest/hdi/hash/fn.hash_entry_search= This example demonstrates how to use the `hash_entry` function with a struct annotated by `#[hdk_entry_helper]`. The `hash_entry` function is called with an instance of the struct `Foo` to generate its corresponding hash. ```rust #[hdk_entry_helper] struct Foo; let foo_hash = hash_entry(Foo)?; ``` -------------------------------- ### Get Slice Iterator Source: https://docs.rs/hdi/latest/hdi/prelude/key_ref/struct.XSalsa20Poly1305KeyRef_search=u32+-%3E+bool Returns an iterator that yields all items of the slice from start to end. ```APIDOC ## POST /iter ### Description Returns an iterator over the slice, yielding all items from start to end. ### Method POST ### Endpoint `/iter` ### Parameters #### Request Body - **slice** (array) - Required - The input slice. ### Request Example ```json { "slice": [1, 2, 4] } ``` ### Response #### Success Response (200) - **iterator_id** (string) - An identifier for the iterator session. Subsequent calls will use this ID to fetch next elements. #### Response Example ```json { "iterator_id": "iter_abc123" } ``` ## GET /iter/{iterator_id} ### Description Fetches the next element from the provided iterator session. ### Method GET ### Endpoint `/iter/{iterator_id}` ### Parameters #### Path Parameters - **iterator_id** (string) - Required - The ID of the iterator session. ### Response #### Success Response (200) - **value** (any) - The next element in the iteration, or null if the iterator is exhausted. #### Response Example ```json { "value": 1 } ``` ``` -------------------------------- ### hdi::prelude Overview Source: https://docs.rs/hdi/latest/hdi/prelude/struct.HashSet_search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Provides a high-level overview of the hdi crate's prelude, including its modules, macros, structs, and enums. ```APIDOC ## hdi::prelude ### Modules * allocation * builder * conversions * data * encode * encrypted_data * hash_type * holochain_serialized_bytes * key_ref * nonce * result * serde_bytes * x25519 ### Macros * app_entry * assert_length * holochain_serial * host_externs * impl_hashable_content * paste * try_ptr * wasm_error ### Structs * AgentValidationPkg * AppEntryBytes * AppEntryDef * AppEntryName * BTreeSet * CapAccessInfo * CapClaim * CapSecret * ChainFilter * CloseChain * CloseChainInput * CompositeHashConversionError * CounterSigningAgentState * CounterSigningSessionData * CounterSigningSessionTimes * Create * CreateBase * CreateLink * Delete * DeleteLink * DesensitizedZomeCallCapGrant * Dna * DnaInfoV1 * DnaInfoV2 * DnaModifiers * DnaModifiersOpt * Ed25519XSalsa20Poly1305Decrypt * EntryDef * EntryDefIndex * EntryDefs * EntryHashes * EntryRateWeight * EphemeralSignatures * ExternIO * FunctionName * GenesisSelfCheckDataV1 * GenesisSelfCheckDataV2 * HashConversionError * HashSet * HoloHash * HoloHashB64 * HoloHashed * InclusiveTimestampInterval * InitZomesComplete * LinkTag * LinkType * MustGetActionInput * MustGetAgentActivityInput * MustGetEntryInput * MustGetValidRecordInput * OpenChain * OpenChainInput * PreflightBytes * PreflightRequest * PreflightResponse * RateWeight * Record * RegisterAgentActivity * RegisterCreateLink * RegisterDelete * RegisterDeleteLink * RegisterUpdate * RequiredValidations * Role * ScopedZomeType * ScopedZomeTypes * ScopedZomeTypesSet * SerializedBytes * Signature * SignedHashed * StoreEntry * StoreRecord * Timestamp * TraceMsg * UnsafeBytes * Update * UpdateBase * VerifySignature * WasmError * WrongActionError * X25519PubKey * X25519XSalsa20Poly1305Decrypt * XSalsa20Poly1305Data * XSalsa20Poly1305Decrypt * XSalsa20Poly1305EncryptedData * XSalsa20Poly1305KeyRef * ZomeCallCapGrant * ZomeDependencyIndex * ZomeIndex * ZomeInfo * ZomeName * ZomeTypesKey ### Enums * Action * ActionBase * ActionType * AnyDhtHashPrimitive * AnyLinkableHashPrimitive * CapAccess * CapGrant * CounterSigningError * Entry * EntryCreationAction * EntryDefId * EntryDefsCallbackResult * EntryError * EntryType * EntryVisibility * GrantedFunctions * HashableContentBytes * HoloHashError * Level * LimitConditions * LinkTypeFilter * MigrationTarget * Op * PreflightRequestAcceptance * RecordEntry * SerializedBytesError * TimestampError * UnitEnumEither * UnresolvedDependencies * ValidateCallbackResult * WasmErrorInner ``` -------------------------------- ### Rust HashSet Get Element Example Source: https://docs.rs/hdi/latest/hdi/prelude/struct.HashSet_search= Shows how to retrieve a reference to an element from a HashSet in Rust using the `get` method. It returns `Some(&element)` if found and `None` otherwise. Similar to `contains`, the input can be a borrowed form. ```rust use std::collections::HashSet; let set = HashSet::from([1, 2, 3]); assert_eq!(set.get(&2), Some(&2)); assert_eq!(set.get(&4), None); ``` -------------------------------- ### Rust: Get File Metadata with Result and and_then Source: https://docs.rs/hdi/latest/hdi/map_extern/type.ExternResult Illustrates using `Result` and `and_then` to handle potential errors when accessing file metadata. This example shows how to chain operations that might fail, such as getting metadata and then retrieving the modification time. ```rust use std::{io::ErrorKind, path::Path}; // Note: on Windows "/" maps to "C:\\" let root_modified_time = Path::new("/").metadata().and_then(|md| md.modified()); assert!(root_modified_time.is_ok()); let should_fail = Path::new("/bad/path").metadata().and_then(|md| md.modified()); assert!(should_fail.is_err()); assert_eq!(should_fail.unwrap_err().kind(), ErrorKind::NotFound); ``` -------------------------------- ### ZomeInfo Constructor Source: https://docs.rs/hdi/latest/hdi/prelude/struct.ZomeInfo Creates a new ZomeInfo instance. ```APIDOC ## `ZomeInfo::new` ### Description Create a new ZomeInfo. ### Method `pub fn new( name: ZomeName, id: ZomeIndex, properties: SerializedBytes, entry_defs: EntryDefs, extern_fns: Vec, zome_types: ScopedZomeTypesSet, ) -> ZomeInfo` ### Parameters - **name** (ZomeName) - The name of the zome. - **id** (ZomeIndex) - The index of the zome. - **properties** (SerializedBytes) - The serialized properties. - **entry_defs** (EntryDefs) - The entry definitions. - **extern_fns** (Vec) - A vector of external function names. - **zome_types** (ScopedZomeTypesSet) - The set of scoped zome types. ``` -------------------------------- ### Rust HashSet Get or Insert Example (Nightly) Source: https://docs.rs/hdi/latest/hdi/prelude/struct.HashSet_search= Demonstrates the `get_or_insert` method for HashSets, available on nightly Rust. This method inserts a value if it's not present and returns a reference to the value in the set. The example shows insertion and insertion preventing duplicates. ```rust #![feature(hash_set_entry)] use std::collections::HashSet; let mut set = HashSet::from([1, 2, 3]); assert_eq!(set.len(), 3); assert_eq!(set.get_or_insert(2), &2); assert_eq!(set.get_or_insert(100), &100); assert_eq!(set.len(), 4); // 100 was inserted ``` -------------------------------- ### TryInto Trait Implementation Source: https://docs.rs/hdi/latest/hdi/entry/examples/struct.Msg_search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Details on the TryInto trait implementation for type conversions, which is a companion to TryFrom. ```APIDOC ## TryInto Trait ### Description Provides a convenient way to perform conversions that are implemented via `TryFrom`. ### Method N/A (Trait Definition) ### Endpoint N/A (Trait Definition) ### Parameters N/A ### Request Example N/A ### Response #### Success Response (200) N/A #### Response Example N/A ### Associated Types #### type Error = >::Error Specifies the error type returned on conversion failure, derived from the corresponding `TryFrom` implementation. ``` -------------------------------- ### Get Slice Iterator Source: https://docs.rs/hdi/latest/hdi/prelude/key_ref/struct.XSalsa20Poly1305KeyRef_search=std%3A%3Avec The `iter` method returns an iterator over the slice, yielding all items from start to end. ```APIDOC ## POST /websites/rs_hdi/iter ### Description Returns an iterator over the slice. The iterator yields all items from start to end. ### Method POST ### Endpoint /websites/rs_hdi/iter ### Request Body - **slice** (array) - Required - The input slice. ### Request Example ```json { "slice": [1, 2, 4] } ``` ### Response #### Success Response (200) - **iterator** (iterator) - An iterator over the elements of the slice. #### Response Example ```json { "iterator": "" } ``` *Note: The actual response for an iterator would typically involve iterating through its elements, for example, by repeatedly calling `next()` on the iterator.* ``` -------------------------------- ### GET /websites/rs_hdi/entry_defs Source: https://docs.rs/hdi/latest/hdi/entry/examples/fn.entry_defs_search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Retrieves the entry definitions for the HDI project. This endpoint allows clients to fetch the predefined entry configurations. ```APIDOC ## GET /websites/rs_hdi/entry_defs ### Description Retrieves the entry definitions for the HDI project. This endpoint allows clients to fetch the predefined entry configurations. ### Method GET ### Endpoint /websites/rs_hdi/entry_defs ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) - **EntryDefsCallbackResult** (object) - An object containing the entry definitions. - **defs** (array) - An array of entry definitions. - **name** (string) - The name of the entry definition. - **file_path** (string) - The file path associated with the entry definition. - **id** (string) - The unique identifier for the entry definition. #### Response Example ```json { "defs": [ { "name": "example_entry", "file_path": "/path/to/entry/file.rs", "id": "entry_123" } ] } ``` ``` -------------------------------- ### clone_to_uninit Source: https://docs.rs/hdi/latest/hdi/prelude/struct.EntryRateWeight_search= Nightly-only experimental API for cloning data into uninitialized memory. ```APIDOC ## impl CloneToUninit for T ### Description 🔬 This is a nightly-only experimental API. It provides an unsafe method to perform copy-assignment from `self` to a raw pointer `dest`. ### Method `unsafe fn clone_to_uninit(&self, dest: *mut u8)` ### Endpoint N/A (Rust trait implementation) ``` -------------------------------- ### Rust BTreeSet Immutable lower_bound Cursor Example Source: https://docs.rs/hdi/latest/hdi/prelude/struct.BTreeSet_search= Demonstrates how to use the immutable `lower_bound` method on a `BTreeSet` to get a cursor pointing to the gap before the smallest element greater than or equal to a given bound. This example uses `Bound::Included`, `Bound::Excluded`, and `Bound::Unbounded`. ```rust #![feature(btree_cursors)] use std::collections::BTreeSet; use std::ops::Bound; let set = BTreeSet::from([1, 2, 3, 4]); let cursor = set.lower_bound(Bound::Included(&2)); assert_eq!(cursor.peek_prev(), Some(&1)); assert_eq!(cursor.peek_next(), Some(&2)); let cursor = set.lower_bound(Bound::Excluded(&2)); assert_eq!(cursor.peek_prev(), Some(&2)); assert_eq!(cursor.peek_next(), Some(&3)); let cursor = set.lower_bound(Bound::Unbounded); assert_eq!(cursor.peek_prev(), None); assert_eq!(cursor.peek_next(), Some(&1)); ``` -------------------------------- ### Rust Vec as_mut_ptr Example: Initializing Elements Source: https://docs.rs/hdi/latest/hdi/prelude/type.CounterSigningAgents_search=u32+-%3E+bool This example shows how to use `as_mut_ptr` to get a mutable raw pointer to a vector's buffer and initialize its elements directly. It then uses `set_len` to establish the vector's length, demonstrating a way to pre-allocate and fill a vector. ```rust // Allocate vector big enough for 4 elements. let size = 4; let mut x: Vec = Vec::with_capacity(size); let x_ptr = x.as_mut_ptr(); // Initialize elements via raw pointer writes, then set length. unsafe { for i in 0..size { *x_ptr.add(i) = i as i32; } x.set_len(size); } assert_eq!(&*x, &[0, 1, 2, 3]); ``` -------------------------------- ### Generic Blanket Implementations Source: https://docs.rs/hdi/latest/hdi/prelude/struct.PreflightRequest_search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E This section covers various blanket implementations for generic types, including `Any`, `Borrow`, `BorrowMut`, `CloneToUninit`, `Equivalent`, `From`, `Instrument`, `Into`, `Same`, `ToOwned`, `TryFrom`, `TryInto`, and `WithSubscriber`. ```APIDOC ### impl Any for T #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. ### impl Borrow for T #### fn borrow(&self) -> &T Immutably borrows from an owned value. ### impl BorrowMut for T #### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. ### impl CloneToUninit for T #### unsafe fn clone_to_uninit(&self, dest: *mut u8) Performs copy-assignment from `self` to `dest`. ### impl Equivalent for Q #### fn equivalent(&self, key: &K) -> bool Checks if this value is equivalent to the given key. ### impl Equivalent for Q #### fn equivalent(&self, key: &K) -> bool Compare self to `key` and return `true` if they are equal. ### impl From for T #### fn from(t: T) -> T Returns the argument unchanged. ### impl Instrument for T #### fn instrument(self, span: Span) -> Instrumented Instruments this type with the provided `Span`, returning an `Instrumented` wrapper. #### fn in_current_span(self) -> Instrumented Instruments this type with the current `Span`, returning an `Instrumented` wrapper. ### impl Into for T #### fn into(self) -> U Calls `U::from(self)`. ### impl Same for T #### type Output = T Should always be `Self` ### impl ToOwned for T #### type Owned = T The resulting type after obtaining ownership. #### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. #### fn clone_into(&self, target: &mut T) Uses borrowed data to replace owned data, usually by cloning. ### impl TryFrom for T #### type Error = Infallible The type returned in the event of a conversion error. #### fn try_from(value: U) -> Result>::Error> Performs the conversion. ### impl TryInto for T #### type Error = >::Error The type returned in the event of a conversion error. #### fn try_into(self) -> Result>::Error> Performs the conversion. ### impl WithSubscriber for T #### fn with_subscriber(self, subscriber: S) -> WithDispatch Attaches the provided `Subscriber` to this type, returning a `WithDispatch` wrapper. #### fn with_current_subscriber(self) -> WithDispatch Attaches the current default `Subscriber` to this type, returning a `WithDispatch` wrapper. ### Description These are generic blanket implementations providing common functionalities like type identification, borrowing, cloning, conversion, instrumentation, and subscriber management. ``` -------------------------------- ### Rust Vec as_ptr Example: Iterating with Raw Pointers Source: https://docs.rs/hdi/latest/hdi/prelude/type.CounterSigningAgents_search=u32+-%3E+bool This example demonstrates how to get a raw pointer to a vector's buffer using `as_ptr` and iterate over its elements using pointer arithmetic. It highlights the use of unsafe blocks for pointer operations and asserts the expected values based on bit shifts. ```rust let x = vec![1, 2, 4]; let x_ptr = x.as_ptr(); unsafe { for i in 0..x.len() { assert_eq!(*x_ptr.add(i), 1 << i); } } ``` -------------------------------- ### Wrapper Types Source: https://docs.rs/hdi/latest/hdi/prelude/serde_bytes/index_search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Overview of the primary wrapper types provided by the `serde_bytes` crate for optimized byte handling. ```APIDOC ## Wrapper Types ### Description The `serde_bytes` crate provides several wrapper types to facilitate optimized serialization and deserialization of byte data. ### Method N/A ### Endpoint N/A ### Parameters N/A ### Request Example N/A ### Response #### Structs - **ByteArray** (Wrapper around `[u8; N]`) - Enables efficient serialization and deserialization of fixed-size byte arrays. - **ByteBuf** (Wrapper around `Vec`) - Provides optimized handling for dynamic byte buffers. - **Bytes** (Wrapper around `&[u8]`) - Offers efficient serialization and deserialization for byte slices. #### Response Example N/A ``` -------------------------------- ### Retrieving an Element from HashSet (get) in Rust Source: https://docs.rs/hdi/latest/hdi/prelude/struct.HashSet_search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Illustrates the `get` method for Rust's HashSet, which returns an optional reference to a value if it exists in the set. Similar to `contains`, it accepts borrowed types that implement `Hash` and `Eq`. The example shows successful retrieval and cases where the element is not found. ```rust use std::collections::HashSet; let set = HashSet::from([1, 2, 3]); assert_eq!(set.get(&2), Some(&2)); assert_eq!(set.get(&4), None); ``` -------------------------------- ### TryFrom Trait Implementation Source: https://docs.rs/hdi/latest/hdi/entry/examples/struct.Msg_search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Details on the TryFrom trait implementation for type conversions. ```APIDOC ## TryFrom Trait ### Description Provides methods for converting one type into another, returning a `Result` to handle potential errors. ### Method N/A (Trait Definition) ### Endpoint N/A (Trait Definition) ### Parameters N/A ### Request Example N/A ### Response #### Success Response (200) N/A #### Response Example N/A ### Associated Types #### type Output = T Specifies the target type for the conversion. #### type Error = Infallible Specifies the error type returned on conversion failure. `Infallible` indicates that conversion errors do not occur. ### Methods #### fn try_from(value: U) -> Result>::Error> Performs the conversion from type `U` to type `T`. **Parameters** - **value** (U) - The value to convert. ``` -------------------------------- ### Get or Insert Element in HashSet (get_or_insert) in Rust (Nightly) Source: https://docs.rs/hdi/latest/hdi/prelude/struct.HashSet_search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E This example showcases the nightly-only `get_or_insert` method for Rust HashSets. It inserts a value if not present and returns a reference to the value in the set. The example demonstrates insertion of a new element and retrieving an existing one, along with checking the set's length. ```rust #![feature(hash_set_entry)] use std::collections::HashSet; let mut set = HashSet::from([1, 2, 3]); assert_eq!(set.len(), 3); assert_eq!(set.get_or_insert(2), &2); assert_eq!(set.get_or_insert(100), &100); assert_eq!(set.len(), 4); // 100 was inserted ``` -------------------------------- ### hdi Crate Overview Source: https://docs.rs/hdi/latest/hdi/prelude/holochain_serialized_bytes/prelude/index_search= Overview of the hdi crate, its modules, and core components like SerializedBytes and UnsafeBytes. ```APIDOC ## Module prelude hdi::prelude::holochain_serialized_bytes ## Macros ### `holochain_serial` - **Description**: Unidiomatic way to derive default trait implementations of `TryFrom` in/out of `SerializedBytes`. ## Structs ### `SerializedBytes` - **Description**: A Canonical Serialized Bytes representation for data. If you have a data structure that needs a canonical byte representation, use this. Always round-trip through `SerializedBytes` via a single `TryFrom` implementation. This ensures that the internal bytes of `SerializedBytes` are indeed canonical. The corollary is that if bytes are NOT wrapped in `SerializedBytes`, we can assume they are NOT canonical. Typically, we need a canonical serialization when data is to be handled at the byte level by independently implemented and maintained systems. ### `UnsafeBytes` - **Description**: The only way to implement a custom round trip through bytes for `SerializedBytes`. It is intended to be an internal implementation in `TryFrom` implementations. The assumption is that any code using `UnsafeBytes` is NOT valid messagepack data. This allows us to enforce that all data round-tripping through `SerializedBytes` is via `TryFrom` and also allow for custom non-messagepack canonical representations of data types. ## Enums ### `SerializedBytesError` - **Description**: Represents errors that can occur during serialization or deserialization processes. ## Traits ### `Deserialize` - **Description**: A data structure that can be deserialized from any data format supported by Serde. ### `Serialize` - **Description**: A data structure that can be serialized into any data format supported by Serde. ### `TryFrom` - **Description**: Simple and safe type conversions that may fail in a controlled way under some circumstances. It is the reciprocal of `TryInto`. ### `TryInto` - **Description**: An attempted conversion that consumes `self`, which may or may not be expensive. ## Functions ### `decode` - **Description**: Decodes data from a byte representation. ### `encode` - **Description**: Encodes data into a byte representation. ## Derive Macros ### `Deserialize` - **Description**: Derives the `Deserialize` trait for a struct or enum. ### `Serialize` - **Description**: Derives the `Serialize` trait for a struct or enum. ### `SerializedBytes` - **Description**: Derives traits related to `SerializedBytes` for a struct or enum. ``` -------------------------------- ### Get Element Offset in Slice (Rust) Source: https://docs.rs/hdi/latest/hdi/prelude/key_ref/struct.XSalsa20Poly1305KeyRef_search=std%3A%3Avec Returns the index an element reference points to within a slice. Returns None if the element is not at the start of an element in the slice. This API is nightly-only and experimental. ```rust #![feature(substr_range)] let nums: &[u32] = &[1, 7, 1, 1]; let num = &nums[2]; assert_eq!(num, &1); assert_eq!(nums.element_offset(num), Some(2)); ``` ```rust #![feature(substr_range)] let arr: &[[u32; 2]] = &[[0, 1], [2, 3]]; let flat_arr: &[u32] = arr.as_flattened(); let ok_elm: &[u32; 2] = flat_arr[0..2].try_into().unwrap(); let weird_elm: &[u32; 2] = flat_arr[1..3].try_into().unwrap(); assert_eq!(ok_elm, &[0, 1]); assert_eq!(weird_elm, &[1, 2]); assert_eq!(arr.element_offset(ok_elm), Some(0)); // Points to element 0 assert_eq!(arr.element_offset(weird_elm), None); // Points between element 0 and 1 ``` -------------------------------- ### HashSet Creation Source: https://docs.rs/hdi/latest/hdi/prelude/struct.HashSet_search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E This section covers different ways to create a HashSet, including in const contexts and with specified capacities. ```APIDOC ## HashSet Creation ### Usage in `const` and `static` `HashSet` is randomly seeded, meaning `HashSet::new` cannot be used in a `const` context. For `const` or `static` items, use a hasher that avoids random seeds. Note that `HashSet` constructed this way is not resistant to HashDoS. ```rust use std::collections::HashSet; use std::hash::{BuildHasherDefault, DefaultHasher}; use std::sync::Mutex; const EMPTY_SET: HashSet> = HashSet::with_hasher(BuildHasherDefault::new()); static SET: Mutex>> = Mutex::new(HashSet::with_hasher(BuildHasherDefault::new())); ``` ### `pub fn new() -> HashSet` Creates an empty `HashSet`. The set initially has a capacity of 0 and allocates memory only upon the first insertion. #### Examples ```rust use std::collections::HashSet; let set: HashSet = HashSet::new(); ``` ### `pub fn with_capacity(capacity: usize) -> HashSet` Creates an empty `HashSet` with at least the specified capacity. The set can hold at least `capacity` elements without reallocating. It might allocate for more. If `capacity` is zero, no allocation occurs. #### Examples ```rust use std::collections::HashSet; let set: HashSet = HashSet::with_capacity(10); assert!(set.capacity() >= 10); ``` ``` -------------------------------- ### Get HashSet Hasher Reference in Rust Source: https://docs.rs/hdi/latest/hdi/prelude/struct.HashSet_search= Demonstrates retrieving a reference to the `BuildHasher` used by a HashSet. This can be useful for introspection or if the hasher needs to be reused. The example creates a set with a hasher and then retrieves a reference to it. ```rust use std::collections::HashSet; use std::hash::RandomState; let hasher = RandomState::new(); let set: HashSet = HashSet::with_hasher(hasher); let hasher: &RandomState = set.hasher(); ``` -------------------------------- ### Get Element Offset in Slice (Rust) Source: https://docs.rs/hdi/latest/hdi/prelude/key_ref/struct.XSalsa20Poly1305KeyRef_search= Retrieves the byte index of an element within a slice using pointer arithmetic. Returns `None` if the element is not at the start of an element in the slice. This API is nightly-only and experimental. ```rust #![feature(substr_range)] let nums: &[u32] = &[1, 7, 1, 1]; let num = &nums[2]; assert_eq!(num, &1); assert_eq!(nums.element_offset(num), Some(2)); ``` ```rust #![feature(substr_range)] let arr: &[[u32; 2]] = &[[0, 1], [2, 3]]; let flat_arr: &[u32] = arr.as_flattened(); let ok_elm: &[u32; 2] = flat_arr[0..2].try_into().unwrap(); let weird_elm: &[u32; 2] = flat_arr[1..3].try_into().unwrap(); assert_eq!(ok_elm, &[0, 1]); assert_eq!(weird_elm, &[1, 2]); assert_eq!(arr.element_offset(ok_elm), Some(0)); // Points to element 0 assert_eq!(arr.element_offset(weird_elm), None); // Points between element 0 and 1 ``` -------------------------------- ### EntryDefs Blanket Implementations Source: https://docs.rs/hdi/latest/hdi/prelude/struct.EntryDefs_search= Information on blanket implementations applied to EntryDefs, such as Any, Borrow, BorrowMut, CloneToUninit, Equivalent, From, Instrument, Into, Same, ToOwned, and TryFrom. ```APIDOC ## Blanket Implementations for EntryDefs ### impl Any for T * `fn type_id(&self) -> TypeId`: Gets the `TypeId` of `self`. ### impl Borrow for T * `fn borrow(&self) -> &T`: Immutably borrows from an owned value. ### impl BorrowMut for T * `fn borrow_mut(&mut self) -> &mut T`: Mutably borrows from an owned value. ### impl CloneToUninit for T * `unsafe fn clone_to_uninit(&self, dest: *mut u8)`: Performs copy-assignment from `self` to `dest`. ### impl Equivalent for Q * `fn equivalent(&self, key: &K) -> bool`: Checks if this value is equivalent to the given key. ### impl From for T * `fn from(t: T) -> T`: Returns the argument unchanged. ### impl Instrument for T * `fn instrument(self, span: Span) -> Instrumented`: Instruments this type with the provided `Span`. * `fn in_current_span(self) -> Instrumented`: Instruments this type with the current `Span`. ### impl Into for T * `fn into(self) -> U`: Calls `U::from(self)`. ### impl Same for T * `type Output = T` ### impl ToOwned for T * `type Owned = T` * `fn to_owned(&self) -> T`: Creates owned data from borrowed data. * `fn clone_into(&self, target: &mut T)`: Uses borrowed data to replace owned data. ### impl TryFrom for T ``` -------------------------------- ### T: CloneToUninit Source: https://docs.rs/hdi/latest/hdi/prelude/struct.FunctionName_search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Provides methods for cloning data into uninitialized memory. This is an experimental, nightly-only API. ```APIDOC ## unsafe fn clone_to_uninit(&self, dest: *mut u8) ### Description Performs copy-assignment from `self` to `dest`. ### Method `unsafe fn clone_to_uninit` ### Endpoint N/A (This is a trait method within the Rust standard library) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) None (This is a method that modifies memory directly) #### Response Example None ``` -------------------------------- ### Rust HashSet Get or Insert With Example (Nightly) Source: https://docs.rs/hdi/latest/hdi/prelude/struct.HashSet Demonstrates the `get_or_insert_with` method for HashSets, another nightly-only experimental API. It allows inserting a computed value into the set if a given value is not present and returns a reference. ```rust use std::collections::HashSet; // Note: The actual implementation of get_or_insert_with requires a nightly compiler. // This is a conceptual example structure. // let mut set = HashSet::from([1, 2, 3]); // let value_ref = set.get_or_insert_with(&4, || 4); // assert_eq!(*value_ref, 4); // assert!(set.contains(&4)); ``` -------------------------------- ### Define HDI Entry Types in Rust Source: https://docs.rs/hdi/latest/src/hdi/entry/examples.rs This Rust code defines custom entry types for the HDI framework using macros. It includes examples for 'Post', 'Msg', and 'PrivMsg' entries, demonstrating how to specify required validations and visibility settings. ```rust use hdi::prelude::*; #[hdk_entry_helper] pub struct Post(pub String); #[hdk_entry_helper] pub struct Msg(pub String); #[hdk_entry_helper] pub struct PrivMsg(pub String); #[hdk_entry_types] #[unit_enum(UnitEntryTypes)] pub enum EntryTypes { Post(Post), #[entry_type(required_validations = 5)] Msg(Msg), #[entry_type(name = "hidden_msg", required_validations = 5, visibility = "private")] PrivMsg(PrivMsg), } ``` -------------------------------- ### hdi::prelude Module Source: https://docs.rs/hdi/latest/hdi/prelude/struct.HashSet_search=u32+-%3E+bool Provides a comprehensive set of modules, structs, enums, and macros for common Holochain development tasks. ```APIDOC ## hdi::prelude ### Modules * allocation * builder * conversions * data * encode * encrypted_data * hash_type * holochain_serialized_bytes * key_ref * nonce * result * serde_bytes * x25519 ### Macros * app_entry * assert_length * holochain_serial * host_externs * impl_hashable_content * paste * try_ptr * wasm_error ### Structs * AgentValidationPkg * AppEntryBytes * AppEntryDef * AppEntryName * BTreeSet * CapAccessInfo * CapClaim * CapSecret * ChainFilter * CloseChain * CloseChainInput * CompositeHashConversionError * CounterSigningAgentState * CounterSigningSessionData * CounterSigningSessionTimes * Create * CreateBase * CreateLink * Delete * DeleteLink * DesensitizedZomeCallCapGrant * Dna * DnaInfoV1 * DnaInfoV2 * DnaModifiers * DnaModifiersOpt * Ed25519XSalsa20Poly1305Decrypt * EntryDef * EntryDefIndex * EntryDefs * EntryHashes * EntryRateWeight * EphemeralSignatures * ExternIO * FunctionName * GenesisSelfCheckDataV1 * GenesisSelfCheckDataV2 * HashConversionError * HashSet * HoloHash * HoloHashB64 * HoloHashed * InclusiveTimestampInterval * InitZomesComplete * LinkTag * LinkType * MustGetActionInput * MustGetAgentActivityInput * MustGetEntryInput * MustGetValidRecordInput * OpenChain * OpenChainInput * PreflightBytes * PreflightRequest * PreflightResponse * RateWeight * Record * RegisterAgentActivity * RegisterCreateLink * RegisterDelete * RegisterDeleteLink * RegisterUpdate * RequiredValidations * Role * ScopedZomeType * ScopedZomeTypes * ScopedZomeTypesSet * SerializedBytes * Signature * SignedHashed * StoreEntry * StoreRecord * Timestamp * TraceMsg * UnsafeBytes * Update * UpdateBase * VerifySignature * WasmError * WrongActionError * X25519PubKey * X25519XSalsa20Poly1305Decrypt * XSalsa20Poly1305Data * XSalsa20Poly1305Decrypt * XSalsa20Poly1305EncryptedData * XSalsa20Poly1305KeyRef * ZomeCallCapGrant * ZomeDependencyIndex * ZomeIndex * ZomeInfo * ZomeName * ZomeTypesKey ### Enums * Action * ActionBase * ActionType * AnyDhtHashPrimitive * AnyLinkableHashPrimitive * CapAccess * CapGrant * CounterSigningError * Entry * EntryCreationAction * EntryDefId * EntryDefsCallbackResult * EntryError * EntryType * EntryVisibility * GrantedFunctions * HashableContentBytes * HoloHashError * Level * LimitConditions * LinkTypeFilter * MigrationTarget * Op * PreflightRequestAcceptance * RecordEntry * SerializedBytesError * TimestampError * UnitEnumEither * UnresolvedDependencies * ValidateCallbackResult * WasmErrorInner ### Constants * CAP_SECRET_BITS * CAP_SECRET_BYTES * ENTRY_SIZE_LIMIT * HOLO_HASH_CORE_LEN * HOLO_HASH_FULL_LEN * HOLO_HASH_LOC_LEN * HOLO_HASH_PREFIX_LEN * HOLO_HASH_UNTYPED_LEN * MAX_COUNTERSIGNING_AGENTS * MAX_HASHABLE_CONTENT_LEN * MIN_COUNTERSIGNING_AGENTS * POST_GENESIS_SEQ_THRESHOLD * SESSION_ACTION_TIME_OFFSET * SESSION_TIME_FUTURE_MAX * SIGNATURE_BYTES * X25519_PUB_KEY_BYTES ### Traits * ActionHashedContainer * ActionSequenceAndHash * ActionUnweighed * ActionWeighed * Deserialize * EntryDefRegistration * EntryTypesHelper * HasHash * HashType * HashableContent * HashableContentExtAsync * HashableContentExtSync * LinkTypesHelper * PrimitiveHashType * Serialize * TryFrom * TryFromDnaProperties * TryInto * U8Index * UnitEnum ``` -------------------------------- ### Rust HashSet Get or Insert With Example (Nightly) Source: https://docs.rs/hdi/latest/hdi/prelude/struct.HashSet_search= Illustrates the `get_or_insert_with` method for HashSets on nightly Rust. This method inserts a value generated by a closure if the specified value is not present, then returns a reference to the value in the set. ```rust #![feature(hash_set_entry)] use std::collections::HashSet; let mut set = HashSet::from([1, 2, 3]); let value_ref = set.get_or_insert_with(&100, |v| *v); assert_eq!(value_ref, &100); assert!(set.contains(&100)); ``` -------------------------------- ### Rust HashSet: Insert or Get Entry with `get_or_insert_with` Source: https://docs.rs/hdi/latest/hdi/prelude/struct.HashSet_search= Demonstrates using `get_or_insert_with` to retrieve an existing entry or insert a new one into a HashSet. This example requires the `hash_set_entry` feature and shows how to add a new element if it doesn't exist. ```rust #![feature(hash_set_entry)] use std::collections::HashSet; let mut set: HashSet = ["cat", "dog", "horse"] .iter().map(|&pet| pet.to_owned()).collect(); assert_eq!(set.len(), 3); for &pet in &["cat", "dog", "fish"] { let value = set.get_or_insert_with(pet, str::to_owned); assert_eq!(value, pet); } assert_eq!(set.len(), 4); // a new "fish" was inserted ``` -------------------------------- ### Entry Types Definition Source: https://docs.rs/hdi/latest/hdi/entry/examples/index_search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E This section demonstrates how to define various entry types for the hdi crate using the `hdk_entry_helper` and `hdk_entry_types` macros. It includes examples for 'Post', 'Msg', and 'PrivMsg' structs, along with their respective validation rules and visibility settings. ```APIDOC ## Module examples hdi::entry ## §Examples ```rust use hdi::prelude::*; #[hdk_entry_helper] pub struct Post(pub String); #[hdk_entry_helper] pub struct Msg(pub String); #[hdk_entry_helper] pub struct PrivMsg(pub String); #[hdk_entry_types] #[unit_enum(UnitEntryTypes)] pub enum EntryTypes { Post(Post), #[entry_type(required_validations = 5)] Msg(Msg), #[entry_type(name = "hidden_msg", required_validations = 5, visibility = "private")] PrivMsg(PrivMsg), } assert_eq!(__num_entry_types(), 3); ``` ### Structs - **Msg**: Represents a message entry. - **Post**: Represents a post entry. - **PrivMsg**: Represents a private message entry. ### Enums - **EntryTypes**: Enumerates the different types of entries available in the DHT. - **UnitEntryTypes**: Unit enum for entry types. ### Functions - **__num_entry_types()**: Returns the number of defined entry types. - **entry_defs()**: Defines the entry types for the DHT. ``` -------------------------------- ### Rust Example Using `#[serde(with = "serde_bytes")]` Source: https://docs.rs/hdi/latest/hdi/prelude/serde_bytes/fn.serialize_search=u32+-%3E+bool An example demonstrating how to use the `#[serde(with = "serde_bytes")]` attribute in Rust to serialize different byte-related types efficiently. This attribute leverages the `hdi::prelude::serde_bytes::serialize` function. ```rust use serde::Serialize; #[derive(Serialize)] struct Efficient<'a> { #[serde(with = "serde_bytes")] bytes: &'a [u8], #[serde(with = "serde_bytes")] byte_buf: Vec, #[serde(with = "serde_bytes")] byte_array: [u8; 314], } ``` -------------------------------- ### Component Methods Source: https://docs.rs/hdi/latest/hdi/hash_path/path/struct.Component_search=std%3A%3Avec Provides details on creating and manipulating Component instances. ```APIDOC ## Implementations for Component ### `fn new(v: Vec) -> Self` **Description:** Creates a new Component from a vector of bytes. **Method:** `pub fn new` **Endpoint:** N/A (Method) ``` -------------------------------- ### Get a Mutable Slice of Vec Data with as_mut_slice Source: https://docs.rs/hdi/latest/hdi/prelude/serde_bytes/struct.ByteBuf_search=u32+-%3E+bool Details the `as_mut_slice` method, which returns a mutable reference to the vector's data as a slice. This allows in-place modification of the vector's elements, for example, when reading data into it. ```rust use std::io::{self, Read};\nlet mut buffer = vec![0; 3];\nio::repeat(0b101).read_exact(buffer.as_mut_slice()).unwrap(); ```