### Rust BTreeSet: Entry Manipulation Example (Nightly) Source: https://docs.rs/hdk/latest/hdk/prelude/struct.BTreeSet_search= An experimental nightly-only API example for `entry` in BTreeSet. It demonstrates managing unique and duplicate characters from a string by utilizing the `Vacant` and `Occupied` entry states. ```rust #![feature(btree_set_entry)] use std::collections::BTreeSet; use std::collections::btree_set::Entry::*; let mut singles = BTreeSet::new(); let mut dupes = BTreeSet::new(); for ch in "a short treatise on fungi".chars() { if let Vacant(dupe_entry) = dupes.entry(ch) { // We haven't already seen a duplicate, so // check if we've at least seen it once. match singles.entry(ch) { Vacant(single_entry) => { // We found a new character for the first time. single_entry.insert() } Occupied(single_entry) => { // We've already seen this once, "move" it to dupes. single_entry.remove(); dupe_entry.insert(); } } } } assert!(!singles.contains(&'t') && dupes.contains(&'t')); assert!(singles.contains(&'u') && !dupes.contains(&'u')); assert!(!singles.contains(&'v') && !dupes.contains(&'v')); ``` -------------------------------- ### Get Mutable Reference with Arc in Rust Source: https://docs.rs/hdk/latest/hdk/prelude/genesis/type.MembraneProof This example demonstrates how to safely get a mutable reference to the data within an `Arc` using `Arc::get_mut`. It shows that it's only possible to get a mutable reference when there are no other `Arc` or `Weak` pointers to the same allocation. ```rust use std::sync::Arc; let mut x = Arc::new(3); *Arc::get_mut(&mut x).unwrap() = 4; assert_eq!(*x, 4); let _y = Arc::clone(&x); assert!(Arc::get_mut(&mut x).is_none()); ``` -------------------------------- ### Initialization Callback Source: https://docs.rs/hdk/latest/hdk/index_search= The `init` callback is executed when any Zome within a DNA is first called. It allows Zomes to perform necessary setup and defines the success or failure of the entire DNA's initialization. ```APIDOC ## `fn init() -> ExternResult` ### Description The `init` callback provides a mechanism for Zomes to perform initial setup tasks. It runs lazily, only when one of the Zomes in the DNA is accessed for the first time. All Zomes within a DNA initialize concurrently. ### Execution - **Lazy Execution**: Runs only upon the first call to any Zome within the DNA. - **Atomic Initialization**: All Zomes in a DNA attempt to initialize simultaneously. ### Result Handling - **Success/Failure**: The callback returns `InitCallbackResult`, which can indicate success, failure, or a retry. - **Failure Propagation**: If any Zome's `init` callback fails, the initialization of the entire DNA is considered failed. - **Retry Mechanism**: If any Zome's `init` callback indicates a retry (e.g., due to missing dependencies), the DNA initialization process will be retried. - **Precedence**: Failures override retries. If a Zome fails, the DNA initialization fails, regardless of other Zomes indicating a retry. ### Related Functions - `create_cap_grant`: Information on setting up capabilities during initialization can be found here. ``` -------------------------------- ### Rust HashSet Get Element Example Source: https://docs.rs/hdk/latest/hdk/prelude/struct.HashSet Shows the `get` method for Rust HashSets, which retrieves a reference to an element if it exists in the set. The input can be a borrowed form, and it returns an `Option`. ```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); ``` -------------------------------- ### Create Struct Documentation Source: https://docs.rs/hdk/latest/hdk/prelude/builder/struct.Create_search= Detailed documentation for the `Create` struct, including its fields, constructor, and available trait implementations. ```APIDOC ## Struct Create ### Description A struct representing the creation of an entry with its type and hash. ### Fields - **entry_type** (EntryType) - The type of the entry. - **entry_hash** (HoloHash) - The hash of the entry. ### Constructor #### `pub fn new(entry_type: EntryType, entry_hash: HoloHash) -> Create` Creates a new `Create` instance. ### Implementations This struct implements several traits, including `Clone`, `Debug`, `PartialEq`, `Eq`, `Freeze`, `RefUnwindSafe`, `Send`, `Sync`, `Unpin`, `UnwindSafe`, `Any`, `Borrow`, `BorrowMut`, `CloneToUninit`, `Equivalent`, `From`, `Instrument`, `Into`, `Same`, `ToOwned`, `TryFrom`, `TryInto`, and `WithSubscriber`. ``` -------------------------------- ### TypedPath Struct Definition and Usage Example (Rust) Source: https://docs.rs/hdk/latest/hdk/prelude/struct.TypedPath Defines the TypedPath struct, which represents a LinkType applied to a Path. It includes an example of how to get a typed path from a path and a link type. Dependencies: hdk::prelude. ```rust pub struct TypedPath { pub link_type: ScopedZomeType, pub path: Path, } // Get a typed path from a path and a link type: let typed_path = path.typed(LinkTypes::MyLink)?; ``` -------------------------------- ### Create Struct Documentation Source: https://docs.rs/hdk/latest/hdk/prelude/builder/struct.Create_search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E This section details the `Create` struct, its purpose, fields, and how to instantiate it using the `new` constructor. ```APIDOC ## Struct Create Represents a create action with an entry type and its hash. ### Fields - **entry_type** (EntryType) - The type of the entry being created. - **entry_hash** (HoloHash) - The hash of the entry being created. ### Constructor #### `pub fn new(entry_type: EntryType, entry_hash: HoloHash) -> Create` Creates a new `Create` struct with the specified entry type and entry hash. ``` -------------------------------- ### Rust BTreeSet: Get or Insert With Method Example (Nightly) Source: https://docs.rs/hdk/latest/hdk/prelude/struct.BTreeSet_search=std%3A%3Avec Illustrates the nightly-only `get_or_insert_with` method, which inserts a computed value if the key is not present. This example uses a closure to create `String` objects and adds 'fish' to the set. ```rust #![feature(btree_set_entry)] use std::collections::BTreeSet; let mut set: BTreeSet = ["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 ``` -------------------------------- ### ActionBuilderCommon::new Source: https://docs.rs/hdk/latest/hdk/prelude/builder/struct.ActionBuilderCommon_search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Constructor for creating a new instance of ActionBuilderCommon. ```APIDOC ## impl ActionBuilderCommon ### pub fn new #### Description Creates a new `ActionBuilderCommon` instance. #### Parameters - **author** (HoloHash) - The author of the action. - **timestamp** (Timestamp) - The timestamp of the action. - **action_seq** (u32) - The action sequence number. - **prev_action** (HoloHash) - The hash of the previous action. #### Returns An instance of `ActionBuilderCommon`. ``` -------------------------------- ### Get Raw Pointer Range Source: https://docs.rs/hdk/latest/hdk/prelude/key_ref/struct.XSalsa20Poly1305KeyRef Returns a pair of raw pointers representing the start and end of the slice's buffer. ```APIDOC ## POST /slice/as_ptr_range ### Description Returns a pair of raw pointers spanning the slice. The returned range is half-open (the end pointer points one past the last element). Useful for interacting with C-style APIs or checking pointer validity within the slice. ### Method POST ### Endpoint /slice/as_ptr_range #### Request Body - **slice** (array) - The input slice. ### Request Example ```json { "slice": [1, 2, 3] } ``` ### Response #### Success Response (200) - **start_pointer** (string) - Raw pointer to the start of the buffer. - **end_pointer** (string) - Raw pointer one past the end of the buffer. #### Response Example ```json { "start_pointer": "0x7ffc12345678", "end_pointer": "0x7ffc12345684" } ``` ``` -------------------------------- ### HDK Module Overview Source: https://docs.rs/hdk/latest/hdk/hdk/index_search=u32+-%3E+bool Provides an overview of the HDK module, its purpose, and how it manages the host-guest interface. ```APIDOC ## Module hdk ### Description The interface between the host and guest is implemented as an `HdkT` trait. The `set_hdk` function globally sets a `RefCell` to track the current HDK implementation. When the `mock` feature is set then this will default to an HDK that always errors, else a WASM host is assumed to exist. The `mockall` crate (in prelude with `mock` feature) can be used to generate compatible mocks for unit testing. See mocking examples in the test WASMs crate, such as `agent_info`. ### Structs * **ErrHdk**: Used as a placeholder before any other Hdk is registered. Generally only useful for testing but technically can be set any time. * **HostHdk**: The HDK implemented as externs provided by the host. ### Constants * **HDK** * **HDK_NOT_REGISTERED** ### Traits * **HdkT**: When mocking is enabled the mockall crate automatically builds a MockHdkT for us. ### Functions * **set_hdk**: At any time the global HDK can be set to a different hdk. Generally this is only useful during rust unit testing. When executing wasm without the `mock` feature, the host will be assumed. ``` -------------------------------- ### Rust HDK Example: Creating an Entry with hdk_entry_helper Source: https://docs.rs/hdk/latest/hdk/entry/fn.create_entry_search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Demonstrates how to use the `create_entry` function with the `hdk_entry_helper` macro in Rust. This example defines a simple struct `Foo`, registers it as an entry type, and then creates an instance of `Foo` using `create_entry`. ```rust #[hdk_entry_helper] pub struct Foo(u32); #[hdk_entry_types] pub enum EntryTypes { Foo(Foo) } create_entry(EntryTypes::Foo(Foo(50)))?; ``` -------------------------------- ### HashSet Get Source: https://docs.rs/hdk/latest/hdk/prelude/struct.HashSet_search=u32+-%3E+bool Retrieves a reference to a value in the HashSet if it exists. ```APIDOC ## get ### Description Returns a reference to the value in the set, if any, that is equal to the given value. ### Method GET ### Endpoint `/{self}/get/{value}` ### Parameters #### Path Parameters - **self** (HashSet) - Required - The HashSet to search within. - **value** (Q) - Required - The value to search for. ### Response #### Success Response (200) - **Option<&T>** - `Some(&T)` containing a reference to the value if found, `None` otherwise. ### Response Example ``` // Example usage in markdown format 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 BTreeSet Initialization and Operations Example Source: https://docs.rs/hdk/latest/hdk/prelude/struct.BTreeSet_search= Demonstrates how to create, insert elements into, check for containment, remove elements from, and iterate over a BTreeSet in Rust. It also shows initialization from an array. ```rust use std::collections::BTreeSet; // Type inference lets us omit an explicit type signature (which // would be `BTreeSet<&str>` in this example). let mut books = BTreeSet::new(); // Add some books. books.insert("A Dance With Dragons"); books.insert("To Kill a Mockingbird"); books.insert("The Odyssey"); books.insert("The Great Gatsby"); // Check for a specific one. if !books.contains("The Winds of Winter") { println!("We have {} books, but The Winds of Winter ain't one.", books.len()); } // Remove a book. books.remove("The Odyssey"); // Iterate over everything. for book in &books { println!("{book}"); } let set = BTreeSet::from([1, 2, 3]); ``` -------------------------------- ### Rust String to Byte Slice Conversion Example Source: https://docs.rs/hdk/latest/hdk/prelude/type.NetworkSeed Shows how to get a byte slice representation of a String's contents in Rust. The inverse operation can be performed using `from_utf8`. ```rust let s = String::from("hello"); assert_eq!(&[104, 101, 108, 108, 111], s.as_bytes()); ``` -------------------------------- ### HashSet Get or Insert (Experimental) Source: https://docs.rs/hdk/latest/hdk/prelude/struct.HashSet_search=u32+-%3E+bool Inserts a value if not present and returns a reference to it. This is a nightly-only experimental API. ```APIDOC ## get_or_insert (Experimental) ### Description Inserts the given `value` into the set if it is not present, then returns a reference to the value in the set. ### Method POST ### Endpoint `/{self}/get_or_insert` ### Parameters #### Path Parameters - **self** (mut HashSet) - Required - The mutable HashSet. #### Request Body - **value** (T) - Required - The value to insert if not present. ### Response #### Success Response (200) - **&T** - A reference to the value in the set. ### Response Example ``` // Example usage in markdown format #![feature(hash_set_entry)] use std::collections::HashSet; let mut set = HashSet::from([1, 2, 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 ``` ``` -------------------------------- ### AppEntryName Constructors Source: https://docs.rs/hdk/latest/hdk/prelude/struct.AppEntryName_search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Provides methods for creating new instances of AppEntryName. ```APIDOC ## AppEntryName Constructors ### `new(s: impl Into>) -> AppEntryName` **Description**: Create a new `AppEntryName` from a string or `&'static str`. ### `from_str(s: &'static str) -> AppEntryName` **Description**: Create a new `AppEntryName` from a `&'static str`. ``` -------------------------------- ### Rust Example Usage of update_entry Source: https://docs.rs/hdk/latest/hdk/entry/fn.update_entry_search=u32+-%3E+bool Provides a practical example of using the `update_entry` function. It first creates a new entry of type `Foo` and then updates it using `update_entry`, demonstrating the flow from creation to update with associated ActionHashes. ```rust #[hdk_entry_helper] pub struct Foo(u32); #[hdk_entry_types] pub enum EntryTypes { Foo(Foo) } let foo_zero_action_hash: ActionHash = create_entry(EntryTypes::Foo(Foo(0)))?; let foo_ten_update_action_hash: ActionHash = update_entry(foo_zero_action_hash, EntryTypes::Foo(Foo(10)))?; ``` -------------------------------- ### Get Mutable Reference Unchecked with Arc in Rust Source: https://docs.rs/hdk/latest/hdk/prelude/genesis/type.MembraneProof This example showcases `Arc::get_mut_unchecked`, an unsafe function. It retrieves a mutable reference to the inner data without checking for other references. It emphasizes the importance of ensuring no other `Arc` or `Weak` pointers exist to prevent undefined behavior. It also includes examples of how incorrect usage can lead to memory safety issues. ```rust #![feature(get_mut_unchecked)] use std::sync::Arc; let mut x = Arc::new(String::new()); unsafe { Arc::get_mut_unchecked(&mut x).push_str("foo") } assert_eq!(*x, "foo"); ``` ```rust #![feature(get_mut_unchecked)] use std::sync::Arc; let x: Arc = Arc::from("Hello, world!"); let mut y: Arc<[u8]> = x.clone().into(); unsafe { // this is Undefined Behavior, because x's inner type is str, not [u8] Arc::get_mut_unchecked(&mut y).fill(0xff); // 0xff is invalid in UTF-8 } println!("{}", &*x); // Invalid UTF-8 in a str ``` ```rust #![feature(get_mut_unchecked)] use std::sync::Arc; let x: Arc<&str> = Arc::new("Hello, world!"); { let s = String::from("Oh, no!"); let mut y: Arc<&str> = x.clone(); unsafe { // this is Undefined Behavior, because x's inner type // is &'long str, not &'short str *Arc::get_mut_unchecked(&mut y) = &s; } } println!("{}", &*x); // Use-after-free ``` -------------------------------- ### Initialization Callback Source: https://docs.rs/hdk/latest/hdk/index_search=u32+-%3E+bool The `init` callback allows guest code to control the initialization process of a zome or DNA. It supports passing, failing, or retrying initialization, with lazy execution and simultaneous DNA-wide initialization. ```APIDOC ## `init()` Callback ### Description Allows the guest to control the initialization of the zome or DNA. It supports passing, failing, or retrying initialization. ### Method `fn init() -> ExternResult` ### Endpoint N/A (Internal Callback) ### Parameters None ### Request Body None ### Request Example ```rust // Example of an init implementation pub fn init() -> ExternResult { // Perform initialization tasks, e.g., create capabilities // create_cap_grant(...) Ok(InitCallbackResult::Pass) } ``` ### Response #### Success Response - `InitCallbackResult`: Can be `Pass`, `Fail`, or `Retry`. ### Response Example ```json "Pass" ``` ### Notes - **Lazy Execution**: Only runs when any zome of the DNA is first called. - **Simultaneous Initialization**: All zomes in a DNA initialize at the same time. - **Failure Overrides Retry**: If any zome fails initialization, the entire DNA initialization fails. - **Retry Mechanism**: A retry result (e.g., due to missing dependencies) causes the DNA to retry initialization. ``` -------------------------------- ### HashSet Get or Insert With (Experimental) Source: https://docs.rs/hdk/latest/hdk/prelude/struct.HashSet_search=u32+-%3E+bool Inserts a computed value if not present and returns a reference to it. This is a nightly-only experimental API. ```APIDOC ## get_or_insert_with (Experimental) ### Description Inserts a value computed from `f` into the set if the given `value` is not present, then returns a reference to the value in the set. ### Method POST ### Endpoint `/{self}/get_or_insert_with` ### Parameters #### Path Parameters - **self** (mut HashSet) - Required - The mutable HashSet. #### Request Body - **value** (Q) - Required - The value to check for presence. - **f** (FnOnce(&Q) -> T) - Required - A function that computes the value to insert if `value` is not present. ### Response #### Success Response (200) - **&T** - A reference to the value in the set. ### Response Example ``` // Example usage in markdown format (conceptual, as actual function passing is complex in static docs) // Assuming a context where `f` can be defined and passed ``` ``` -------------------------------- ### HDK Prelude Functions Source: https://docs.rs/hdk/latest/hdk/prelude/trait.TryInto_search=std%3A%3Avec A comprehensive list of functions available in the HDK prelude, covering core operations like calls, data management, crypto, and system interactions. ```APIDOC ## HDK Prelude Functions This section lists the functions available in the HDK prelude. ### Functions * `__hc__agent_info_1()`: Retrieves agent information. * `__hc__call_1(call: SerializedBytes)`: Makes a call to another zome function. * `__hc__call_info_1()`: Retrieves information about the current call. * `__hc__call_remote_1(dna: DnaHash, capability: CallCap, fn_name: &str, payload: SerializedBytes)`: Calls a function in a remote DNA. * `__hc__capability_claims_1()`: Retrieves capability claims. * `__hc__capability_grants_1()`: Retrieves capability grants. * `__hc__capability_info_1()`: Retrieves capability information. * `__hc__close_chain_1()`: Closes the current chain. * `__hc__count_links_1(base: AnyLinkableHash, tag: Option)`: Counts links for a given base and tag. * `__hc__create_1(entry: SerializedBytes)`: Creates a new entry. * `__hc__create_clone_cell_1(clone_dna_def: SerializedBytes, clone_id: String)`: Creates a clone cell. * `__hc__create_link_1(base: AnyLinkableHash, link_type: LinkTag, target: AnyLinkableHash)`: Creates a link. * `__hc__create_x25519_keypair_1()`: Creates an X25519 keypair. * `__hc__delete_1(address: ActionHash)`: Deletes an entry. * `__hc__delete_clone_cell_1(clone_id: String)`: Deletes a clone cell. * `__hc__delete_link_1(link_hash: ActionHash)`: Deletes a link. * `__hc__disable_clone_cell_1(clone_id: String)`: Disables a clone cell. * `__hc__dna_info_1()`: Retrieves DNA information. * `__hc__ed_25519_x_salsa20_poly1305_decrypt_1(private_key: Bytes, nonce: Bytes, message: Bytes)`: Decrypts data using Ed25519. * `__hc__ed_25519_x_salsa20_poly1305_encrypt_1(public_key: Bytes, nonce: Bytes, message: Bytes)`: Encrypts data using Ed25519. * `__hc__emit_signal_1(data: SerializedBytes)`: Emits a signal. * `__hc__enable_clone_cell_1(clone_id: String)`: Enables a clone cell. * `__hc__get_1(address: ActionHash)`: Retrieves an entry by its address. * `__hc__get_agent_activity_1(agent_pubkey: AgentPubKey)`: Retrieves agent activity. * `__hc__get_details_1(address: ActionHash)`: Retrieves details of an entry. * `__hc__get_links_1(base: AnyLinkableHash, tag: Option)`: Retrieves links for a given base and tag. * `__hc__get_links_details_1(base: AnyLinkableHash, tag: Option)`: Retrieves detailed links for a given base and tag. * `__hc__get_validation_receipts_1(address: ActionHash)`: Retrieves validation receipts for an entry. * `__hc__must_get_action_1(address: ActionHash)`: Retrieves an action, panicking if not found. * `__hc__must_get_entry_1(address: ActionHash)`: Retrieves an entry, panicking if not found. * `__hc__must_get_valid_record_1(address: ActionHash)`: Retrieves a valid record, panicking if not found. * `__hc__open_chain_1()`: Opens the current chain. * `__hc__query_1(query: SerializedBytes)`: Executes a query. * `__hc__random_bytes_1(size: usize)`: Generates random bytes. * `__hc__schedule_1(time: Timestamp, payload: SerializedBytes)`: Schedules a task. * `__hc__send_remote_signal_1(agent: AgentPubKey, signal: SerializedBytes)`: Sends a signal to a remote agent. * `__hc__sign_1(data: SerializedBytes)`: Signs data. * `__hc__sign_ephemeral_1(data: SerializedBytes)`: Signs data ephemerally. * `__hc__sys_time_1()`: Retrieves system time. * `__hc__trace_1(message: String)`: Logs a trace message. * `__hc__unreachable_1()`: Indicates an unreachable code path. * `__hc__update_1(entry_hash: ActionHash, entry: SerializedBytes)`: Updates an entry. * `__hc__verify_signature_1(signature: Bytes, message: Bytes, public_key: Bytes)`: Verifies a signature. * `__hc__x_25519_x_salsa20_poly1305_decrypt_1(private_key: Bytes, nonce: Bytes, ciphertext: Bytes)`: Decrypts using X25519. * `__hc__x_25519_x_salsa20_poly1305_encrypt_1(public_key: Bytes, nonce: Bytes, plaintext: Bytes)`: Encrypts using X25519. * `__hc__x_salsa20_poly1305_decrypt_1(key: Bytes, nonce: Bytes, ciphertext: Bytes)`: Decrypts using X/Salsa20/Poly1305. * `__hc__x_salsa20_poly1305_encrypt_1(key: Bytes, nonce: Bytes, plaintext: Bytes)`: Encrypts using X/Salsa20/Poly1305. * `__hc__x_salsa20_poly1305_shared_secret_create_random_1()`: Creates a random shared secret. * `__hc__x_salsa20_poly1305_shared_secret_export_1(keypair: Keypair)`: Exports a shared secret. * `__hc__x_salsa20_poly1305_shared_secret_ingest_1(public_key: Bytes)`: Ingests a shared secret. * `__hc__zome_info_1()`: Retrieves zome information. * `blake2b_256(data: SerializedBytes)`: Computes Blake2b-256 hash. * `close_chain()`: Closes the current chain. * `decode(data: SerializedBytes)`: Decodes serialized bytes. * `dna_info()`: Retrieves DNA information. * `ed_25519_x_salsa20_poly1305_decrypt(private_key: Bytes, nonce: Bytes, ciphertext: Bytes)`: Decrypts using Ed25519. * `encode(data: &T)`: Encodes data. * `entry_type_matches(entry_type_name: &str, entry_type_value: &str)`: Checks if an entry type matches. * `holo_hash_decode(hash: &str)`: Decodes a HoloHash. * `holo_hash_decode_unchecked(hash: &str)`: Decodes a HoloHash without validation. * `holo_hash_encode(hash: &HoloHash)`: Encodes a HoloHash. * `host_args()`: Retrieves host arguments. * `host_call(fn_name: &str, payload: SerializedBytes)`: Calls a host function. * `merge_u32(a: u32, b: u32)`: Merges two u32 values. * `merge_u64(a: u64, b: u64)`: Merges two u64 values. * `merge_usize(a: usize, b: usize)`: Merges two usize values. * `must_get_action(address: ActionHash)`: Retrieves an action, panicking if not found. * `must_get_agent_activity(agent_pubkey: AgentPubKey)`: Retrieves agent activity, panicking if not found. * `must_get_entry(address: ActionHash)`: Retrieves an entry, panicking if not found. * `must_get_valid_record(address: ActionHash)`: Retrieves a valid record, panicking if not found. * `open_chain()`: Opens the current chain. * `return_err_ptr(error: SerializedBytes)`: Returns an error pointer. * `return_ptr(data: SerializedBytes)`: Returns a data pointer. * `sha2_512(data: SerializedBytes)`: Computes SHA2-512 hash. * `split_u128(value: u128)`: Splits a u128 value. * `split_u64(value: u64)`: Splits a u64 value. * `split_usize(value: usize)`: Splits a usize value. * `verify_signature(signature: Bytes, message: Bytes, public_key: Bytes)`: Verifies a signature. * `verify_signature_raw(signature: Bytes, message: Bytes, public_key: Bytes)`: Verifies a raw signature. * `x_25519_x_salsa20_poly1305_decrypt(private_key: Bytes, nonce: Bytes, ciphertext: Bytes)`: Decrypts using X25519. * `x_salsa20_poly1305_decrypt(key: Bytes, nonce: Bytes, ciphertext: Bytes)`: Decrypts using X/Salsa20/Poly1305. * `zome_info()`: Retrieves zome information. ``` -------------------------------- ### HashSet Creation and Initialization Source: https://docs.rs/hdk/latest/hdk/prelude/struct.HashSet_search= Demonstrates how to create a HashSet, including static and const initialization with a custom hasher, and creation with a specified capacity. ```APIDOC ## HashSet Creation and Initialization ### Description This section covers the creation of `HashSet` instances, including creating an empty set, creating a set with a specific initial capacity, and initializing a set within `const` or `static` contexts using a non-random hasher. ### Static and Const Initialization `HashSet` is randomly seeded, making `HashSet::new` unsuitable for `const` contexts. For `const` or `static` initialization, a hasher without random seeding, such as `BuildHasherDefault`, must be used. Note that `HashSet` instances constructed this way are vulnerable to HashDoS attacks. ```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 will not allocate memory until the first element is inserted. #### 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 `capacity` elements without reallocating. It might allocate for more elements than specified. If `capacity` is 0, no allocation occurs. #### Examples ```rust use std::collections::HashSet; let set: HashSet = HashSet::with_capacity(10); assert!(set.capacity() >= 10); ``` ``` -------------------------------- ### Rust: Get String Length in Bytes using len() Source: https://docs.rs/hdk/latest/hdk/prelude/type.NetworkSeed_search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Illustrates how to get the length of a Rust String in bytes using the `len()` method. It highlights that this count is of bytes, not characters, which can differ for multi-byte UTF-8 characters. Example shows `len()` on ASCII and multi-byte character strings. ```rust let a = String::from("foo"); assert_eq!(a.len(), 3); let fancy_f = String::from("ƒoo"); assert_eq!(fancy_f.len(), 4); // 'ƒ' is 2 bytes assert_eq!(fancy_f.chars().count(), 3); ``` -------------------------------- ### Rust: Check if Slice Starts With a Prefix Source: https://docs.rs/hdk/latest/hdk/prelude/key_ref/struct.XSalsa20Poly1305KeyRef_search=std%3A%3Avec Determines if a slice begins with a given slice (needle) or is identical to it. An empty needle always results in true. Examples demonstrate various prefix checks. ```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])); let v = &[10, 40, 30]; assert!(v.starts_with(&[])); let v: &[u8] = &[]; assert!(v.starts_with(&[])); ``` -------------------------------- ### Rust HashSet Capacity Management Example Source: https://docs.rs/hdk/latest/hdk/prelude/struct.HashSet Demonstrates how to manage the capacity of a HashSet in Rust. It shows initializing with capacity, inserting elements, and shrinking the capacity to a specified size. ```rust use std::collections::HashSet; let mut set = HashSet::with_capacity(100); set.insert(1); set.insert(2); assert!(set.capacity() >= 100); set.shrink_to(10); assert!(set.capacity() >= 10); set.shrink_to(0); assert!(set.capacity() >= 2); ``` -------------------------------- ### Create AppSignal Instance (Rust) Source: https://docs.rs/hdk/latest/hdk/prelude/struct.AppSignal_search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Provides a constructor function `new` to create a new instance of `AppSignal`. It takes an `ExternIO` as input. ```rust pub fn new(extern_io: ExternIO) -> AppSignal ``` -------------------------------- ### Rust HashSet Get or Insert With Example (Nightly) Source: https://docs.rs/hdk/latest/hdk/prelude/struct.HashSet_search= Illustrates the `get_or_insert_with` method for Rust HashSets, which inserts a computed value if a given value is not present and returns a reference to the value. This is a nightly-only experimental API. ```rust use std::collections::HashSet; // This example requires the same nightly feature as get_or_insert // #![feature(hash_set_entry)] // let mut set = HashSet::from([1, 2, 3]); // assert_eq!(set.get_or_insert_with(&2, || 200), &2); // assert_eq!(set.get_or_insert_with(&4, || 400), &400); // assert_eq!(set.len(), 4); // assert_eq!(set.get(&400), Some(&400)); ``` -------------------------------- ### Create Struct Documentation Source: https://docs.rs/hdk/latest/hdk/prelude/struct.Create_search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Details the `Create` struct, which represents an action that 'speaks' Entry content into being. It outlines the fields, their types, and their purpose. ```APIDOC ## Struct Create ### Description An action which “speaks” Entry content into being. The same content can be referenced by multiple such actions. ### Fields - **author** (HoloHash) - The agent who authored this action. - **timestamp** (Timestamp) - The time at which this action occurred. - **action_seq** (u32) - The sequence number of this action. - **prev_action** (HoloHash) - A reference to the previous action. - **entry_type** (EntryType) - The type of the entry being created. - **entry_hash** (HoloHash) - The hash of the entry content. - **weight** (W) - The weight associated with this action (defaults to EntryRateWeight). ### Trait Implementations #### `impl ActionBuilder> for Create` - **fn build(self, common: ActionBuilderCommon) -> Create<()>`**: Builds a Create action with common properties. #### `impl ActionUnweighed for Create<()>` - **type Weighed = Create** - **type Weight = EntryRateWeight** - **fn weighed(self, weight: EntryRateWeight) -> Create**: Adds a weight to an unweighed Create action. #### `impl ActionWeighed for Create` - **type Unweighed = Create<()>` - **type Weight = EntryRateWeight** - **fn into_action(self) -> Action**: Constructs the full Action enum with this variant. - **fn unweighed(self) -> Create<()>`**: Erases the rate limiting weight info, creating an unweighed version. #### `impl Clone for Create` - **fn clone(&self) -> Create`**: Returns a duplicate of the value. - **fn clone_from(&mut self, source: &Self)**: Performs copy-assignment from `source`. #### `impl Debug for Create` - **fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>`**: Formats the value using the given formatter. #### `impl<'de, W> Deserialize<'de> for Create` - **fn deserialize<__D>(__deserializer: __D) -> Result, <__D as Deserializer<'de>>::Error>`**: Deserializes this value from the given Serde deserializer. #### `impl From for EntryCreationAction` - **fn from(c: Create) -> EntryCreationAction**: Converts a Create action into an EntryCreationAction. #### `impl Hash for Create` - **fn hash<__H>(&self, state: &mut __H)**: Feeds this value into the given `Hasher`. - **fn hash_slice(data: &[Self], state: &mut H)**: Feeds a slice of this type into the given `Hasher`. #### `impl HashableContent for Create` - **type HashType = Action** - **fn hash_type(&self) -> ::HashType**: Returns the HashType for this content. - **fn hashable_content(&self) -> HashableContentBytes**: Returns a subset of the content for hashing. #### `impl PartialEq for Create` - **fn eq(&self, other: &Create) -> bool**: Tests for equality between two Create actions. - **fn ne(&self, other: &Rhs) -> bool**: Tests for inequality between two Create actions. #### `impl Serialize for Create` - **fn serialize<__S>(&self, __serializer: __S) -> Result<<__S as Serializer>::Ok, <__S as Serializer>::Error>`**: Serializes this value into the given Serde serializer. #### `impl TryFrom<&Create> for SerializedBytes` - **type Error = SerializedBytesError** - **fn try_from(t: &Create) -> Result`**: Attempts to convert a Create action into SerializedBytes. #### `impl TryFrom for SerializedBytes` - **type Error = SerializedBytesError** - **fn try_from(t: Create) -> Result`**: Attempts to convert a Create action into SerializedBytes. #### `impl TryFrom for Create` - **type Error = SerializedBytesError** - **fn try_from(sb: SerializedBytes) -> Result`**: Attempts to convert SerializedBytes into a Create action. #### `impl Eq for Create` ``` -------------------------------- ### Rust Experimental HashSet Get or Insert With Example Source: https://docs.rs/hdk/latest/hdk/prelude/struct.HashSet Demonstrates the experimental `get_or_insert_with` method for Rust HashSets. It inserts a value generated by a closure if the value is not present and returns a reference. Requires nightly Rust. ```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(&4, |v| *v * 10); assert_eq!(value_ref, &40); assert!(set.contains(&40)); assert_eq!(set.len(), 4); ``` -------------------------------- ### Rust Experimental HashSet Get or Insert Example Source: https://docs.rs/hdk/latest/hdk/prelude/struct.HashSet Illustrates the experimental `get_or_insert` method for Rust HashSets. This API inserts a value if it's not present and returns a reference to the value in the set. Requires nightly Rust. ```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 ``` -------------------------------- ### Create OpenChain Instance - Rust Source: https://docs.rs/hdk/latest/hdk/prelude/builder/struct.OpenChain Provides constructor functions for the `OpenChain` struct. `new` and `new_full` both accept a `MigrationTarget` and a `HoloHash` to initialize a new `OpenChain` instance. ```rust pub fn new( prev_target: MigrationTarget, close_hash: HoloHash, ) -> OpenChain ``` ```rust pub fn new_full( prev_target: MigrationTarget, close_hash: HoloHash, ) -> OpenChain ``` -------------------------------- ### Get Element Offset in Slice (Rust) Source: https://docs.rs/hdk/latest/hdk/prelude/key_ref/struct.XSalsa20Poly1305KeyRef_search=std%3A%3Avec Returns the index of an element reference within a slice using pointer arithmetic. Returns `None` if the element is not at the start of an element boundary. This is a nightly-only experimental API and panics if `T` is zero-sized. ```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 ``` -------------------------------- ### Bytes Struct and Construction Source: https://docs.rs/hdk/latest/hdk/prelude/serde_bytes/struct.Bytes Information about the Bytes struct and how to create a new instance. ```APIDOC ## Struct Bytes Source ``` pub struct Bytes { /* private fields */ } ``` ### Description Wrapper around `[u8]` to serialize and deserialize efficiently. ### Implementations #### pub fn new(bytes: &[u8]) -> &Bytes Wrap an existing `&[u8]`. ``` -------------------------------- ### ByteBuf - Constructors Source: https://docs.rs/hdk/latest/hdk/prelude/serde_bytes/struct.ByteBuf_search= Provides methods for creating new ByteBuf instances, either empty or with a specified capacity, and for wrapping existing byte data. ```APIDOC ## ByteBuf Constructors ### `new()` Construct a new, empty `ByteBuf`. ### `with_capacity(cap: usize)` Construct a new, empty `ByteBuf` with the specified capacity. ### `from(bytes: T)` where T: Into> Wrap existing bytes in a `ByteBuf`. ``` -------------------------------- ### Rust BTreeSet: Get or Insert Method Example (Nightly) Source: https://docs.rs/hdk/latest/hdk/prelude/struct.BTreeSet_search=std%3A%3Avec Demonstrates the nightly-only `get_or_insert` method. It shows inserting a new element and retrieving an existing one, verifying the set's length changes only when a new element is added. ```rust #![feature(btree_set_entry)] use std::collections::BTreeSet; let mut set = BTreeSet::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 ``` -------------------------------- ### CreateBase Constructor Source: https://docs.rs/hdk/latest/hdk/prelude/struct.CreateBase_search= Provides details on how to create a new instance of the CreateBase struct. ```APIDOC ## CreateBase Constructor ### Description Constructor for the `CreateBase` struct. ### Method `new` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) - **CreateBase** (CreateBase) - A new instance of the CreateBase struct. #### Response Example ```json { "message": "CreateBase instance created successfully" } ``` ### Error Handling None explicitly mentioned for the constructor. ``` -------------------------------- ### Get Disjoint Mutable References (Rust) Source: https://docs.rs/hdk/latest/hdk/prelude/serde_bytes/struct.Bytes_search= Provides examples of obtaining multiple mutable references to disjoint parts of a slice using `get_disjoint_unchecked_mut` and `get_disjoint_mut`. `get_disjoint_unchecked_mut` is unsafe and requires manual checks for overlapping or out-of-bounds indices, while `get_disjoint_mut` performs these checks and returns a `Result`. ```rust let x = &mut [1, 2, 4]; unsafe { let [a, b] = x.get_disjoint_unchecked_mut([0, 2]); *a *= 10; *b *= 100; } assert_eq!(x, &[10, 2, 400]); ``` ```rust let x = &mut [1, 2, 4]; unsafe { let [a, b] = x.get_disjoint_unchecked_mut([0..1, 1..3]); a[0] = 8; b[0] = 88; b[1] = 888; } assert_eq!(x, &[8, 88, 888]); ``` ```rust let x = &mut [1, 2, 4]; unsafe { let [a, b] = x.get_disjoint_unchecked_mut([1..=2, 0..=0]); a[0] = 11; a[1] = 111; b[0] = 1; } assert_eq!(x, &[1, 11, 111]); ``` ```rust let mut slice = vec![1, 2, 3, 4, 5]; match slice.get_disjoint_mut([0..2, 3..5]) { Ok(refs) => { let (first_part, second_part) = (refs[0], refs[1]); first_part[0] = 10; second_part[1] = 50; } Err(_) => {} } assert_eq!(slice, vec![10, 2, 3, 4, 50]); ``` ```rust let mut slice = vec![1, 2, 3, 4, 5]; let result = slice.get_disjoint_mut([0..3, 1..4]); assert!(result.is_err()); ``` -------------------------------- ### Create Mutable Slice Iterator (Rust) Source: https://docs.rs/hdk/latest/hdk/prelude/serde_bytes/struct.Bytes_search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Returns an iterator that yields mutable references to the elements, allowing modification during iteration. Iterates from start to end. The example demonstrates incrementing each element. ```rust pub fn iter_mut(&mut self) -> IterMut<'_, T> Returns an iterator that allows modifying each value. The iterator yields all items from start to end. ##### §Examples ``` let x = &mut [1, 2, 4]; for elem in x.iter_mut() { *elem += 2; } assert_eq!(x, &[3, 4, 6]); ``` ```