### start_health_monitor Source: https://docs.rs/guardian-db/0.20.26/guardian_db/p2p/network/core/connection_pool/struct.OptimizedConnectionPool.html Starts the background health monitoring process. ```APIDOC ## pub fn start_health_monitor(&self) -> JoinHandle<()> ### Description Starts the connection health monitor to track the status of active connections. ``` -------------------------------- ### Basic Box Pinning Source: https://docs.rs/guardian-db/0.20.26/guardian_db/access_control/traits/type.Option.html Example of creating a pinned box. ```rust let foo = Box::new(()); let bar = Pin::from(foo); ``` -------------------------------- ### BatchProcessor Methods Source: https://docs.rs/guardian-db/0.20.26/guardian_db/p2p/network/core/batch_processor/struct.BatchProcessor.html Methods for initializing, adding operations, starting the processor, and retrieving statistics. ```rust pub fn new(batch_config: BatchConfig, backend: Arc) -> Self ``` ```rust pub async fn add_batch_operation( &self, operation_type: OperationType, data: OperationData, priority: u8, ) -> Result ``` ```rust pub fn start_auto_processor(&self) -> JoinHandle<()> ``` ```rust pub async fn get_stats(&self) -> BatchStats ``` -------------------------------- ### connect Source: https://docs.rs/guardian-db/0.20.26/guardian_db/messaging/struct.Channels.html Starts the connection to and monitoring of a specific peer. If a connection does not exist, it creates a new pubsub topic and starts a background task to listen for messages. ```APIDOC ## fn connect(target: NodeId) ### Description Starts the connection to and monitoring of a specific peer. If a connection with the peer does not already exist, it creates a new pubsub topic, subscribes to it, and starts a background task to listen for messages. ### Parameters - **target** (NodeId) - Required - The identifier of the peer to connect to. ``` -------------------------------- ### Construct Box from raw pointer Source: https://docs.rs/guardian-db/0.20.26/guardian_db/access_control/traits/type.Option.html Examples demonstrating how to recreate a Box from a raw pointer or manually allocate memory for a Box. ```rust #![feature(allocator_api)] use std::alloc::System; let x = Box::new_in(5, System); let (ptr, alloc) = Box::into_raw_with_allocator(x); let x = unsafe { Box::from_raw_in(ptr, alloc) }; ``` ```rust #![feature(allocator_api, slice_ptr_get)] use std::alloc::{Allocator, Layout, System}; unsafe { let ptr = System.allocate(Layout::new::())?.as_mut_ptr() as *mut i32; // In general .write is required to avoid attempting to destruct // the (uninitialized) previous contents of `ptr`, though for this // simple example `*ptr = 5` would have worked as well. ptr.write(5); let x = Box::from_raw_in(ptr, System); } ``` -------------------------------- ### Clone from Reference in Allocator Source: https://docs.rs/guardian-db/0.20.26/guardian_db/access_control/traits/type.Option.html Examples for cloning from a reference using a specific allocator, requiring nightly features. ```rust #![feature(clone_from_ref)] #![feature(allocator_api)] use std::alloc::System; let hello: Box = Box::clone_from_ref_in("hello", System); ``` ```rust #![feature(clone_from_ref)] #![feature(allocator_api)] use std::alloc::System; let hello: Box = Box::try_clone_from_ref_in("hello", System)?; ``` -------------------------------- ### Create JSON Values Source: https://docs.rs/guardian-db/0.20.26/guardian_db/stores/document_store/type.Document.html Examples of creating different JSON types using the json! macro. ```rust let v = json!(null); ``` ```rust let v = json!(true); ``` ```rust let v = json!(12.5); ``` ```rust let v = json!("a string"); ``` ```rust let v = json!(["an", "array"]); ``` ```rust let v = json!({ "an": "object" }); ``` -------------------------------- ### get Source: https://docs.rs/guardian-db/0.20.26/guardian_db/p2p/network/core/optimized_cache/struct.OptimizedCache.html Retrieves data from the cache. ```APIDOC ## pub async fn get(&self, cid: &str) -> Option ### Description Looks up data in the cache with intelligent optimizations based on the provided CID. ### Parameters - **cid** (&str) - Required - The content identifier to look up. ### Returns - **Option** - The cached data if found, otherwise None. ``` -------------------------------- ### Construct Box from Raw Pointer Source: https://docs.rs/guardian-db/0.20.26/guardian_db/access_control/traits/type.Option.html Examples demonstrating how to reconstruct a Box from a raw pointer using Box::from_raw. ```rust let x = Box::new(5); let ptr = Box::into_raw(x); let x = unsafe { Box::from_raw(ptr) }; ``` ```rust use std::alloc::{alloc, Layout}; unsafe { let ptr = alloc(Layout::new::()) as *mut i32; // In general .write is required to avoid attempting to destruct // the (uninitialized) previous contents of `ptr`, though for this // simple example `*ptr = 5` would have worked as well. ptr.write(5); let x = Box::from_raw(ptr); } ``` -------------------------------- ### Sender::send Usage Example Source: https://docs.rs/guardian-db/0.20.26/guardian_db/traits/type.ProgressCallback.html Demonstrates sending values through a channel, blocking until capacity is available. ```rust use tokio::sync::mpsc; let (tx, mut rx) = mpsc::channel(1); tokio::spawn(async move { for i in 0..10 { if let Err(_) = tx.send(i).await { println!("receiver dropped"); return; } } }); while let Some(i) = rx.recv().await { println!("got = {}", i); } ``` -------------------------------- ### BatchProcessor::start_auto_processor Source: https://docs.rs/guardian-db/0.20.26/guardian_db/p2p/network/core/batch_processor/struct.BatchProcessor.html Initializes and starts the background task for automatic batch processing. ```APIDOC ## pub fn start_auto_processor(&self) -> JoinHandle<()> ### Description Starts the automatic batch processor. ``` -------------------------------- ### Define DocumentStoreGetOptions struct Source: https://docs.rs/guardian-db/0.20.26/guardian_db/traits/struct.DocumentStoreGetOptions.html The struct definition for configuring DocumentStore get operations. ```rust pub struct DocumentStoreGetOptions { pub case_insensitive: bool, pub partial_matches: bool, } ``` -------------------------------- ### Construct Box from NonNull pointer Source: https://docs.rs/guardian-db/0.20.26/guardian_db/access_control/traits/type.Option.html Examples demonstrating how to recreate a Box from a NonNull pointer or manually allocate memory for a Box using NonNull. ```rust #![feature(allocator_api)] use std::alloc::System; let x = Box::new_in(5, System); let (non_null, alloc) = Box::into_non_null_with_allocator(x); let x = unsafe { Box::from_non_null_in(non_null, alloc) }; ``` ```rust #![feature(allocator_api)] use std::alloc::{Allocator, Layout, System}; unsafe { let non_null = System.allocate(Layout::new::())?.cast::(); // In general .write is required to avoid attempting to destruct // the (uninitialized) previous contents of `non_null`. non_null.write(5); let x = Box::from_non_null_in(non_null, System); } ``` -------------------------------- ### Fallible Arc construction Source: https://docs.rs/guardian-db/0.20.26/guardian_db/traits/type.StoreConstructor.html Examples of using try_new_in, try_new_uninit_in, and try_new_zeroed_in to handle allocation failures. ```rust #![feature(allocator_api)] use std::sync::Arc; use std::alloc::System; let five = Arc::try_new_in(5, System)?; ``` ```rust #![feature(allocator_api)] #![feature(get_mut_unchecked)] use std::sync::Arc; use std::alloc::System; let mut five = Arc::::try_new_uninit_in(System)?; let five = unsafe { // Deferred initialization: Arc::get_mut_unchecked(&mut five).as_mut_ptr().write(5); five.assume_init() }; assert_eq!(*five, 5); ``` ```rust #![feature(allocator_api)] use std::sync::Arc; use std::alloc::System; let zero = Arc::::try_new_zeroed_in(System)?; let zero = unsafe { zero.assume_init() }; assert_eq!(*zero, 0); ``` -------------------------------- ### Sender::try_send Usage Example Source: https://docs.rs/guardian-db/0.20.26/guardian_db/traits/type.ProgressCallback.html Demonstrates immediate non-blocking message sending, which fails if the buffer is full. ```rust use tokio::sync::mpsc; // Create a channel with buffer size 1 let (tx1, mut rx) = mpsc::channel(1); let tx2 = tx1.clone(); tokio::spawn(async move { tx1.send(1).await.unwrap(); tx1.send(2).await.unwrap(); // task waits until the receiver receives a value. }); tokio::spawn(async move { // This will return an error and send // no message if the buffer is full let _ = tx2.try_send(3); }); let mut msg; msg = rx.recv().await.unwrap(); println!("message {} received", msg); msg = rx.recv().await.unwrap(); println!("message {} received", msg); // Third message may have never been sent match rx.recv().await { Some(msg) => println!("message {} received", msg), None => println!("the third message was never sent"), } ``` -------------------------------- ### Consume Box into raw pointer and allocator Source: https://docs.rs/guardian-db/0.20.26/guardian_db/access_control/traits/type.Option.html Demonstrates consuming a Box into a raw pointer and allocator, with examples for automatic cleanup via Box::from_raw_in and manual memory deallocation. ```rust #![feature(allocator_api)] use std::alloc::System; let x = Box::new_in(String::from("Hello"), System); let (ptr, alloc) = Box::into_raw_with_allocator(x); let x = unsafe { Box::from_raw_in(ptr, alloc) }; ``` ```rust #![feature(allocator_api)] use std::alloc::{Allocator, Layout, System}; use std::ptr::{self, NonNull}; let x = Box::new_in(String::from("Hello"), System); let (ptr, alloc) = Box::into_raw_with_allocator(x); unsafe { ptr::drop_in_place(ptr); let non_null = NonNull::new_unchecked(ptr); alloc.deallocate(non_null.cast(), Layout::new::()); } ``` -------------------------------- ### new Source: https://docs.rs/guardian-db/0.20.26/guardian_db/p2p/network/core/struct.IrohBackend.html Creates a new instance of the Iroh backend using the provided client configuration. ```APIDOC ### pub async fn new(config: &ClientConfig) -> Result Creates a new instance of the Iroh backend. #### Arguments - **config** (ClientConfig) - Required - Client configuration containing the data path. ``` -------------------------------- ### Consume Box into NonNull pointer and allocator Source: https://docs.rs/guardian-db/0.20.26/guardian_db/access_control/traits/type.Option.html Demonstrates consuming a Box into a NonNull pointer and allocator, with examples for automatic cleanup via Box::from_non_null_in and manual memory deallocation. ```rust #![feature(allocator_api)] use std::alloc::System; let x = Box::new_in(String::from("Hello"), System); let (non_null, alloc) = Box::into_non_null_with_allocator(x); let x = unsafe { Box::from_non_null_in(non_null, alloc) }; ``` ```rust #![feature(allocator_api)] use std::alloc::{Allocator, Layout, System}; let x = Box::new_in(String::from("Hello"), System); let (non_null, alloc) = Box::into_non_null_with_allocator(x); unsafe { non_null.drop_in_place(); alloc.deallocate(non_null.cast::(), Layout::new::()); } ``` -------------------------------- ### Construct Box from NonNull Pointer Source: https://docs.rs/guardian-db/0.20.26/guardian_db/access_control/traits/type.Option.html Examples demonstrating how to reconstruct a Box from a NonNull pointer using Box::from_non_null. Requires the box_vec_non_null feature. ```rust #![feature(box_vec_non_null)] let x = Box::new(5); let non_null = Box::into_non_null(x); let x = unsafe { Box::from_non_null(non_null) }; ``` ```rust #![feature(box_vec_non_null)] use std::alloc::{alloc, Layout}; use std::ptr::NonNull; unsafe { let non_null = NonNull::new(alloc(Layout::new::()).cast::()) .expect("allocation failed"); // In general .write is required to avoid attempting to destruct // the (uninitialized) previous contents of `non_null`. non_null.write(5); let x = Box::from_non_null(non_null); } ``` -------------------------------- ### Create a GuardianDBDocumentStore Source: https://docs.rs/guardian-db/0.20.26/guardian_db/p2p/network/client/struct.IrohClient.html Demonstrates initializing an IrohClient and using it to create a new document store with specific identity, address, and configuration options. ```rust use guardian_db::p2p::network::IrohClient; use guardian_db::p2p::network::config::ClientConfig; use guardian_db::log::identity::{DefaultIdentificator, Identificator}; use guardian_db::traits::NewStoreOptions; use guardian_db::stores::document_store::default_store_opts_for_map; use guardian_db::guardian::error::Result; use guardian_db::address; use std::sync::Arc; let client = IrohClient::new(ClientConfig::development()).await?; // Create an identity. let mut identificator = DefaultIdentificator::new(); let identity = Arc::new(identificator.create("user")); // Create an address from a string. let addr = Arc::new(address::parse("/guardiandb/zdpuAm...")?); // Configure options - use the helper function to create default options. let doc_opts = default_store_opts_for_map("_id"); let options = NewStoreOptions { store_specific_opts: Some(Box::new(doc_opts)), ..Default::default() }; let store = client.create_document_store( identity, addr, options ).await?; ``` -------------------------------- ### RedbCache::new Source: https://docs.rs/guardian-db/0.20.26/guardian_db/cache/struct.RedbCache.html Creates a new RedbCache instance. ```APIDOC ## pub fn new(opts: Options) -> Self ### Description Creates a new RedbCache instance using the provided options. ``` -------------------------------- ### pub async fn create Source: https://docs.rs/guardian-db/0.20.26/guardian_db/access_control/fn.create.html Creates a new access controller and returns the Hash of its manifest. ```APIDOC ## Function: create ### Description Creates a new access controller and returns the Hash of its manifest. ### Signature `pub async fn create(db: Arc>, controller_type: &str, params: CreateAccessControllerOptions, _options: Option) -> Result` ### Arguments - **db** (Arc>) - The BaseGuardianDB instance - **controller_type** (&str) - The controller type (“simple”, “guardian”, “iroh”) - **params** (CreateAccessControllerOptions) - The controller’s configuration parameters - **options** (Option) - Additional options for creation ### Returns - **Ok(Hash)** - Hash of the created manifest - **Err(GuardianError)** - Error during creation ``` -------------------------------- ### get Source: https://docs.rs/guardian-db/0.20.26/guardian_db/keystore/struct.RedbKeystore.html Retrieves the value associated with a specific key. ```APIDOC ## fn get(&self, key: &str) -> Pin>>> + Send>> ### Description Retrieves the value associated with the provided key identifier, if it exists. ### Parameters - **key** (&str) - The key identifier. ``` -------------------------------- ### Configuring LogOptions with Method Chaining Source: https://docs.rs/guardian-db/0.20.26/guardian_db/log/struct.LogOptions.html Demonstrates how to initialize LogOptions and use method chaining to set specific parameters before passing them to a new Log. ```rust let opts = LogOptions::new().id("some_id").clock(LamportClock::new().set_time(128)); let log = Log::new(/* identity */,opts); ``` -------------------------------- ### Arc::weak_count Source: https://docs.rs/guardian-db/0.20.26/guardian_db/stores/base_store/type.CacheRef.html Gets the number of Weak pointers to this allocation. ```APIDOC ## pub fn weak_count(this: &Arc) -> usize ### Description Gets the number of `Weak` pointers to this allocation. Note that another thread can change the weak count at any time. ``` -------------------------------- ### create Source: https://docs.rs/guardian-db/0.20.26/guardian_db/access_control/index.html Creates a new access controller and returns the Hash of its manifest. ```APIDOC ## create ### Description Creates a new access controller and returns the Hash of its manifest. ``` -------------------------------- ### Initialize BlobStore Source: https://docs.rs/guardian-db/0.20.26/guardian_db/p2p/network/core/blobs/struct.BlobStore.html Creates a new BlobStore instance using a shared FsStore. ```rust use std::sync::Arc; use tokio::sync::RwLock; use iroh_blobs::store::fs::FsStore; use guardian_db::p2p::network::core::BlobStore; let store = Arc::new(RwLock::new(fs_store)); let blobs_client = BlobStore::new(store); ``` -------------------------------- ### Arc::strong_count Source: https://docs.rs/guardian-db/0.20.26/guardian_db/stores/base_store/type.CacheRef.html Gets the number of strong (Arc) pointers to this allocation. ```APIDOC ## pub fn strong_count(this: &Arc) -> usize ### Description Gets the number of strong (`Arc`) pointers to this allocation. Note that another thread can change the strong count at any time. ``` -------------------------------- ### Get vector length Source: https://docs.rs/guardian-db/0.20.26/guardian_db/data_store/type.Results.html Returns the number of elements currently in the vector. ```rust let a = vec![1, 2, 3]; assert_eq!(a.len(), 3); ``` -------------------------------- ### Initialize Vector via as_non_null Source: https://docs.rs/guardian-db/0.20.26/guardian_db/data_store/type.Results.html Demonstrates manual initialization using the experimental as_non_null API. ```rust #![feature(box_vec_non_null)] // Allocate vector big enough for 4 elements. let size = 4; let mut x: Vec = Vec::with_capacity(size); let x_ptr = x.as_non_null(); // Initialize elements via raw pointer writes, then set length. unsafe { for i in 0..size { x_ptr.add(i).write(i as i32); } x.set_len(size); } assert_eq!(&*x, &[0, 1, 2, 3]); ``` -------------------------------- ### pub fn create_keystore(directory: Option) -> Result> Source: https://docs.rs/guardian-db/0.20.26/guardian_db/keystore/fn.create_keystore.html Factory function to create keystores based on configuration. ```APIDOC ## Function: create_keystore ### Description Factory function to create keystores based on configuration. ### Signature `pub fn create_keystore(directory: Option) -> Result>` ### Parameters - **directory** (Option) - Optional - The directory path to use for the keystore configuration. ### Returns - **Result>** - Returns a thread-safe, shared reference to a KeystoreInterface implementation, or an error if creation fails. ``` -------------------------------- ### Pin::as_mut Source: https://docs.rs/guardian-db/0.20.26/guardian_db/traits/type.AsyncDocumentFilter.html Gets a mutable reference to the pinned value this Pin points to. ```APIDOC ## pub fn as_mut(&mut self) -> Pin<&mut ::Target> ### Description Gets a mutable reference to the pinned value this `Pin` points to. This is useful when doing multiple calls to functions that consume the pinning pointer. ``` -------------------------------- ### Create a new GuardianDBAdapter Source: https://docs.rs/guardian-db/0.20.26/guardian_db/access_control/struct.GuardianDBAdapter.html Initializes a new adapter instance by wrapping a BaseGuardianDB. ```rust pub fn new(base_db: Arc>) -> Self ``` -------------------------------- ### Create a new Key Source: https://docs.rs/guardian-db/0.20.26/guardian_db/data_store/struct.Key.html Initialize a Key instance using a path string. ```rust use guardian_db::data_store::Key; let key = Key::new("/users/alice/profile"); let key = Key::new("config/database/host"); ``` -------------------------------- ### Pin::as_ref Source: https://docs.rs/guardian-db/0.20.26/guardian_db/traits/type.AsyncDocumentFilter.html Gets a shared reference to the pinned value this Pin points to. ```APIDOC ## pub fn as_ref(&self) -> Pin<&::Target> ### Description Gets a shared reference to the pinned value this `Pin` points to. This is a generic method to go from `&Pin>` to `Pin<&T>`. ``` -------------------------------- ### docs Source: https://docs.rs/guardian-db/0.20.26/guardian_db/guardian/struct.GuardianDB.html Creates a DocumentStore instance. ```APIDOC ## pub async fn docs(&self, address: &str, options: Option) -> Result>> ### Description Creates or retrieves a DocumentStore associated with the specified address. ### Parameters - **address** (&str) - Required - The address for the document store. - **options** (Option) - Optional - Creation options for the store. ``` -------------------------------- ### BatchProcessor::new Source: https://docs.rs/guardian-db/0.20.26/guardian_db/p2p/network/core/batch_processor/struct.BatchProcessor.html Creates a new instance of the BatchProcessor with the provided configuration and backend. ```APIDOC ## pub fn new(batch_config: BatchConfig, backend: Arc) -> Self ### Description Creates a new batch processor with an IrohBackend. ``` -------------------------------- ### Transposing Result and Option Source: https://docs.rs/guardian-db/0.20.26/guardian_db/guardian/error/type.Result.html Example of transposing a Result of an Option into an Option of a Result. ```rust #[derive(Debug, Eq, PartialEq)] struct SomeErr; let x: Result, SomeErr> = Ok(Some(5)); let y: Option> = Some(Ok(5)); assert_eq!(x.transpose(), y); ``` -------------------------------- ### Pin::as_deref_mut Source: https://docs.rs/guardian-db/0.20.26/guardian_db/traits/type.AsyncDocumentFilter.html Gets Pin<&mut T> to the underlying pinned value from this nested Pin-pointer. ```APIDOC ## pub fn as_deref_mut(self: Pin<&mut Pin>) -> Pin<&mut ::Target> ### Description Gets `Pin<&mut T>` to the underlying pinned value from this nested `Pin`-pointer. This is a generic method to go from `Pin<&mut Pin>>` to `Pin<&mut T>`. ``` -------------------------------- ### accept Source: https://docs.rs/guardian-db/0.20.26/guardian_db/p2p/network/core/ticket_exchange/type.TicketRegistry.html Handle an incoming connection. ```APIDOC ## async fn accept(&self, conn: Connection) -> Result<(), AcceptError> ### Description Handle an incoming connection. ### Parameters - **conn** (Connection) - The incoming connection to handle. ### Returns - **Result<(), AcceptError>** - Returns unit on success or an AcceptError. ``` -------------------------------- ### Index into JSON Values Source: https://docs.rs/guardian-db/0.20.26/guardian_db/stores/document_store/type.Document.html Accessing elements in arrays or maps using the get method. ```rust let object = json!({ "A": 65, "B": 66, "C": 67 }); assert_eq!(*object.get("A").unwrap(), json!(65)); let array = json!([ "A", "B", "C" ]); assert_eq!(*array.get(2).unwrap(), json!("C")); assert_eq!(array.get("A"), None); ``` -------------------------------- ### Implement MessageMarshaler for PostcardMarshaler Source: https://docs.rs/guardian-db/0.20.26/guardian_db/traits/trait.MessageMarshaler.html Example implementation of the MessageMarshaler trait using the Postcard format. ```rust impl MessageMarshaler for PostcardMarshaler { type Error = GuardianError } ``` -------------------------------- ### Create cache instance Source: https://docs.rs/guardian-db/0.20.26/guardian_db/cache/fn.create_cache.html Initializes a new RedbCache instance using the specified Options. ```rust pub fn create_cache(opts: Options) -> RedbCache ``` -------------------------------- ### IrohClient Initialization Source: https://docs.rs/guardian-db/0.20.26/guardian_db/p2p/network/client/struct.IrohClient.html Methods to create and configure an IrohClient instance. ```APIDOC ## IrohClient::new(config: ClientConfig) ## IrohClient::default() ## IrohClient::development() ## IrohClient::production() ## IrohClient::testing() ## IrohClient::new_with_backend(backend: Arc) ### Description Creates a new instance of the Guardian DB client. Various factory methods are provided for different environment configurations or to initialize with an existing backend. ### Parameters - **config** (ClientConfig) - Required (for new) - Configuration settings for the client. - **backend** (Arc) - Required (for new_with_backend) - An existing Iroh backend instance. ``` -------------------------------- ### Define long-lived Vec storage Source: https://docs.rs/guardian-db/0.20.26/guardian_db/data_store/type.Results.html Example of a static Mutex-protected vector for long-lived storage. ```rust static LONG_LIVED: Mutex>> = Mutex::new(Vec::new()); ``` -------------------------------- ### create_keystore Source: https://docs.rs/guardian-db/0.20.26/guardian_db/keystore/index.html Factory function used to initialize a keystore based on provided configuration. ```APIDOC ## Function: create_keystore ### Description Factory function to create keystores based on configuration. ### Signature `create_keystore(config)` ``` -------------------------------- ### Pinning Box ambiguity warning Source: https://docs.rs/guardian-db/0.20.26/guardian_db/access_control/traits/type.Option.html Demonstrates an example of a poor implementation of From that causes ambiguity. ```rust struct Foo; // A type defined in this crate. impl From> for Pin { fn from(_: Box<()>) -> Pin { Pin::new(Foo) } } ``` -------------------------------- ### Checking Result Status Source: https://docs.rs/guardian-db/0.20.26/guardian_db/guardian/error/type.Result.html Examples of using .is_ok() and .is_err() to check the variant of a Result. ```rust let x: Result = Ok(-3); assert_eq!(x.is_ok(), true); let x: Result = Err("Some error message"); assert_eq!(x.is_ok(), false); ``` ```rust let x: Result = Ok(-3); assert_eq!(x.is_err(), false); let x: Result = Err("Some error message"); assert_eq!(x.is_err(), true); ``` -------------------------------- ### new Source: https://docs.rs/guardian-db/0.20.26/guardian_db/guardian/struct.GuardianDB.html Creates a new instance of the GuardianDB. ```APIDOC ## pub async fn new(client: IrohClient, options: Option) -> Result ### Description Creates a new GuardianDB instance using the provided IrohClient and optional configuration. ### Parameters - **client** (IrohClient) - Required - The Iroh client instance. - **options** (Option) - Optional - Configuration options for the new database instance. ``` -------------------------------- ### Cloning Result Contents Source: https://docs.rs/guardian-db/0.20.26/guardian_db/guardian/error/type.Result.html Examples of using .cloned() on Result types containing references. ```rust let val = 12; let x: Result<&i32, i32> = Ok(&val); assert_eq!(x, Ok(&12)); let cloned = x.cloned(); assert_eq!(cloned, Ok(12)); ``` ```rust let mut val = 12; let x: Result<&mut i32, i32> = Ok(&mut val); assert_eq!(x, Ok(&mut 12)); let cloned = x.cloned(); assert_eq!(cloned, Ok(12)); ``` -------------------------------- ### Copying Result Contents Source: https://docs.rs/guardian-db/0.20.26/guardian_db/guardian/error/type.Result.html Examples of using .copied() on Result types containing references. ```rust let val = 12; let x: Result<&i32, i32> = Ok(&val); assert_eq!(x, Ok(&12)); let copied = x.copied(); assert_eq!(copied, Ok(12)); ``` ```rust let mut val = 12; let x: Result<&mut i32, i32> = Ok(&mut val); assert_eq!(x, Ok(&mut 12)); let copied = x.copied(); assert_eq!(copied, Ok(12)); ``` -------------------------------- ### GetOptions Struct Definition Source: https://docs.rs/guardian-db/0.20.26/guardian_db/p2p/network/core/batch_processor/struct.GetOptions.html The structure used to configure Get operations within the batch processor. ```rust pub struct GetOptions { pub timeout: Option, pub preferred_peers: Vec, } ``` -------------------------------- ### RedbKeystore Methods Source: https://docs.rs/guardian-db/0.20.26/guardian_db/keystore/struct.RedbKeystore.html Methods available for interacting with the RedbKeystore instance. ```APIDOC ## pub fn new(path: Option) -> Result ### Description Creates a new RedbKeystore with secrets stored verbatim. If path is None, creates a temporary in-memory database. ## pub fn temporary() -> Result ### Description Creates a temporary in-memory keystore for testing. ## pub async fn put_keypair(&self, key: &str, secret_key: &SecretKey) -> Result<()> ### Description Stores an Iroh SecretKey as bytes. ## pub async fn get_keypair(&self, key: &str) -> Result> ### Description Retrieves an Iroh SecretKey from bytes. ## pub async fn list_keys(&self) -> Result> ### Description Lists all stored keys. ## pub async fn close(&self) -> Result<()> ### Description Closes the database. ``` -------------------------------- ### Sender::closed Usage Example Source: https://docs.rs/guardian-db/0.20.26/guardian_db/traits/type.ProgressCallback.html Demonstrates waiting for the receiver to be dropped to stop production work. ```rust use tokio::sync::mpsc; let (tx1, rx) = mpsc::channel::<()>(1); let tx2 = tx1.clone(); let tx3 = tx1.clone(); let tx4 = tx1.clone(); let tx5 = tx1.clone(); tokio::spawn(async move { drop(rx); }); futures::join!( tx1.closed(), tx2.closed(), tx3.closed(), tx4.closed(), tx5.closed() ); println!("Receiver dropped"); ``` -------------------------------- ### new Source: https://docs.rs/guardian-db/0.20.26/guardian_db/p2p/network/core/connection_pool/struct.OptimizedConnectionPool.html Creates a new instance of the OptimizedConnectionPool. ```APIDOC ## pub fn new(pool_config: PoolConfig) -> Self ### Description Creates a new optimized connection pool using the provided configuration. ### Parameters - **pool_config** (PoolConfig) - Required - The configuration settings for the connection pool. ``` -------------------------------- ### log Source: https://docs.rs/guardian-db/0.20.26/guardian_db/guardian/struct.GuardianDB.html Creates an EventLogStore instance. ```APIDOC ## pub async fn log(&self, address: &str, options: Option) -> Result>> ### Description Creates or retrieves an EventLogStore associated with the specified address. ### Parameters - **address** (&str) - Required - The address for the event log store. - **options** (Option) - Optional - Creation options for the store. ``` -------------------------------- ### Construct a Pin facade Source: https://docs.rs/guardian-db/0.20.26/guardian_db/p2p/network/types/type.PubsubStream.html Demonstrates creating a Pin facade for a type that implements Unpin. ```rust use std::pin::Pin; let mut val: u8 = 5; // Since `val` doesn't care about being moved, we can safely create a "facade" `Pin` // which will allow `val` to participate in `Pin`-bound apis without checking that // pinning guarantees are actually upheld. let mut pinned: Pin<&mut u8> = Pin::new(&mut val); ``` -------------------------------- ### Leaking Box memory Source: https://docs.rs/guardian-db/0.20.26/guardian_db/access_control/traits/type.Option.html Examples of consuming a Box to return a mutable reference with a static lifetime. ```rust let x = Box::new(41); let static_ref: &'static mut usize = Box::leak(x); *static_ref += 1; assert_eq!(*static_ref, 42); ``` ```rust let x = vec![1, 2, 3].into_boxed_slice(); let static_ref = Box::leak(x); static_ref[0] = 4; assert_eq!(*static_ref, [4, 2, 3]); ``` -------------------------------- ### TracerWrapper Initialization Source: https://docs.rs/guardian-db/0.20.26/guardian_db/traits/enum.TracerWrapper.html Methods to create instances of TracerWrapper for different tracing backends. ```APIDOC ## TracerWrapper::new_tracing Creates a new TracerWrapper using the native tracing system. ## TracerWrapper::new_opentelemetry Creates a new TracerWrapper using OpenTelemetry. - **tracer** (Arc) - The OpenTelemetry tracer instance. ## TracerWrapper::new_noop Creates a no-op TracerWrapper. ``` -------------------------------- ### Flattening Nested Results Source: https://docs.rs/guardian-db/0.20.26/guardian_db/guardian/error/type.Result.html Examples of using .flatten() to reduce nesting levels in Result types. ```rust let x: Result, u32> = Ok(Ok("hello")); assert_eq!(Ok("hello"), x.flatten()); let x: Result, u32> = Ok(Err(6)); assert_eq!(Err(6), x.flatten()); let x: Result, u32> = Err(6); assert_eq!(Err(6), x.flatten()); ``` ```rust let x: Result, u32>, u32> = Ok(Ok(Ok("hello"))); assert_eq!(Ok(Ok("hello")), x.flatten()); assert_eq!(Ok("hello"), x.flatten().flatten()); ``` -------------------------------- ### Construct and set time for LamportClock Source: https://docs.rs/guardian-db/0.20.26/guardian_db/log/lamport_clock/struct.LamportClock.html Demonstrates initializing a new clock with an identifier and setting its initial time value. ```rust let clock = LamportClock::new("some_id").set_time(128); ``` -------------------------------- ### Get mutable reference to Arc Source: https://docs.rs/guardian-db/0.20.26/guardian_db/events/type.Event.html Retrieves a mutable reference if the Arc is unique, otherwise returns None. ```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()); ``` -------------------------------- ### create_temp_keystore() Source: https://docs.rs/guardian-db/0.20.26/guardian_db/keystore/fn.create_temp_keystore.html Creates a temporary in-memory keystore. ```APIDOC ## create_temp_keystore ### Description Creates a temporary in-memory keystore. ### Signature `pub fn create_temp_keystore() -> Result>` ### Returns - **Result>** - A result containing an atomically reference-counted pointer to the created keystore interface, or an error if creation fails. ``` -------------------------------- ### Initialize Vector via as_mut_ptr Source: https://docs.rs/guardian-db/0.20.26/guardian_db/data_store/type.Results.html Demonstrates manual initialization of a vector's buffer using a raw mutable pointer. ```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]); ``` -------------------------------- ### create Source: https://docs.rs/guardian-db/0.20.26/guardian_db/access_control/manifest/fn.create.html Creates a new manifest and returns its Hash. When skip_manifest is set, the existing address is returned without persisting anything; otherwise the manifest is serialized to CBOR and stored in Iroh. ```APIDOC ## pub async fn create ### Description Creates a new manifest and returns its Hash. When `skip_manifest` is set, the existing address is returned without persisting anything; otherwise the manifest is serialized to CBOR and stored in Iroh. ### Signature `pub async fn create(client: Arc, controller_type: String, params: &CreateAccessControllerOptions) -> Result` ### Parameters - **client** (Arc) - The Iroh client instance. - **controller_type** (String) - The type of access controller to create. - **params** (&CreateAccessControllerOptions) - Configuration options for the access controller creation. ### Returns - **Result** - Returns the Hash of the created manifest or an error if the operation fails. ``` -------------------------------- ### Conditional Result Checking Source: https://docs.rs/guardian-db/0.20.26/guardian_db/guardian/error/type.Result.html Example of using .is_ok_and() to verify the value inside an Ok variant against a predicate. ```rust let x: Result = Ok(2); assert_eq!(x.is_ok_and(|x| x > 1), true); let x: Result = Ok(0); assert_eq!(x.is_ok_and(|x| x > 1), false); let x: Result = Err("hey"); assert_eq!(x.is_ok_and(|x| x > 1), false); let x: Result = Ok("ownership".to_string()); assert_eq!(x.as_ref().is_ok_and(|x| x.len() > 1), true); println!("still alive {:?}", x); ``` -------------------------------- ### Accessing the IrohBackend Source: https://docs.rs/guardian-db/0.20.26/guardian_db/p2p/network/client/struct.IrohClient.html Use the backend method to access low-level optimizations, connection pools, and performance metrics. ```rust let client = IrohClient::development().await?; // Direct access to the optimized backend. let backend = client.backend(); let report = backend.generate_performance_report().await; println!("{}", report); ``` -------------------------------- ### create_db_manifest Source: https://docs.rs/guardian-db/0.20.26/guardian_db/db_manifest/fn.create_db_manifest.html Creates a new database manifest and saves it to Iroh. ```APIDOC ## Function: create_db_manifest ### Description Creates a new database manifest and saves it to Iroh. ### Signature `pub async fn create_db_manifest(client: &IrohClient, name: &str, db_type: &str, access_controller_address: &str) -> Result` ### Parameters - **client** (&IrohClient) - The Iroh client instance. - **name** (&str) - The name of the database. - **db_type** (&str) - The type of the database. - **access_controller_address** (&str) - The address of the access controller. ### Returns - **Result** - Returns a Result containing the Hash of the created manifest on success. ``` -------------------------------- ### Creating Uninitialized Arc Instances Source: https://docs.rs/guardian-db/0.20.26/guardian_db/stores/base_store/type.IndexBuilder.html Methods for allocating Arc memory without immediate initialization, useful for deferred setup. ```rust use std::sync::Arc; let mut five = Arc::::new_uninit(); // Deferred initialization: Arc::get_mut(&mut five).unwrap().write(5); let five = unsafe { five.assume_init() }; assert_eq!(*five, 5) ``` ```rust use std::sync::Arc; let zero = Arc::::new_zeroed(); let zero = unsafe { zero.assume_init() }; assert_eq!(*zero, 0) ``` -------------------------------- ### create_db_manifest Source: https://docs.rs/guardian-db/0.20.26/guardian_db/db_manifest/index.html Creates a new database manifest and saves it to Iroh. ```APIDOC ## create_db_manifest ### Description Creates a new database manifest and saves it to Iroh. ``` -------------------------------- ### Default Value Implementation Example Source: https://docs.rs/guardian-db/0.20.26/guardian_db/stores/document_store/type.Document.html Demonstrates using the Default trait for Value, which defaults to Value::Null, useful for handling missing fields during deserialization. ```rust use serde_json::Value; #[derive(Deserialize)] struct Settings { level: i32, #[serde(default)] extras: Value, } let data = r#" { "level": 42 } "#; let s: Settings = serde_json::from_str(data)?; assert_eq!(s.level, 42); assert_eq!(s.extras, Value::Null); ``` -------------------------------- ### Initialize Default Cache Source: https://docs.rs/guardian-db/0.20.26/guardian_db/cache/fn.create_default_cache.html Creates a new cache instance with pre-configured optimized settings. ```rust pub fn create_default_cache() -> RedbCache ``` -------------------------------- ### key_value Source: https://docs.rs/guardian-db/0.20.26/guardian_db/guardian/struct.GuardianDB.html Creates a KeyValueStore instance. ```APIDOC ## pub async fn key_value(&self, address: &str, options: Option) -> Result>> ### Description Creates or retrieves a KeyValueStore associated with the specified address. ### Parameters - **address** (&str) - Required - The address for the key-value store. - **options** (Option) - Optional - Creation options for the store. ``` -------------------------------- ### Manually Create Box from Global Allocator Source: https://docs.rs/guardian-db/0.20.26/guardian_db/traits/type.IndexConstructor.html Manually create a Box from scratch by using the global allocator. ```rust use std::alloc::{alloc, Layout}; unsafe { let ptr = alloc(Layout::new::()) as *mut i32; // In general .write is required to avoid attempting to destruct // the (uninitialized) previous contents of `ptr`, though for this // simple example `*ptr = 5` would have worked as well. ptr.write(5); let x = Box::from_raw(ptr); } ``` -------------------------------- ### cat(hash_str: &str) Source: https://docs.rs/guardian-db/0.20.26/guardian_db/p2p/network/core/struct.IrohBackend.html Retrieves content from the store by its BLAKE3 hash. ```APIDOC ## cat ### Description Retrieves content from the store by its BLAKE3 hash. ### Parameters - **hash_str** (str) - Required - BLAKE3 hash in hexadecimal format ``` -------------------------------- ### new Source: https://docs.rs/guardian-db/0.20.26/guardian_db/p2p/network/core/optimized_cache/struct.OptimizedCache.html Creates a new instance of the OptimizedCache. ```APIDOC ## pub fn new(cache_config: CacheConfig) -> Self ### Description Creates a new instance of the optimized cache using the provided configuration. ### Parameters - **cache_config** (CacheConfig) - Required - Configuration settings for the cache. ``` -------------------------------- ### new Source: https://docs.rs/guardian-db/0.20.26/guardian_db/p2p/network/core/gossip/struct.EpidemicPubSub.html Creates a new EpidemicPubSub instance using the provided IrohBackend. ```APIDOC ### pub async fn new(backend: Arc) -> Result Creates a new EpidemicPubSub instance using iroh-gossip. This method ensures that incoming connections are correctly routed to the Gossip registered on the Router. ``` -------------------------------- ### Initialize KeyValueStoreBoxWrapper Source: https://docs.rs/guardian-db/0.20.26/guardian_db/guardian/struct.KeyValueStoreBoxWrapper.html Constructor for creating a new instance of the wrapper from an Arc-wrapped KeyValueStore. ```rust pub fn new(inner: Arc>) -> Self ``` -------------------------------- ### create_temp_keystore Function Signature Source: https://docs.rs/guardian-db/0.20.26/guardian_db/keystore/fn.create_temp_keystore.html Displays the function signature for creating an in-memory keystore. ```rust pub fn create_temp_keystore() -> Result> ``` -------------------------------- ### Box::new_uninit_in Source: https://docs.rs/guardian-db/0.20.26/guardian_db/traits/type.OnWritePrototype.html Constructs a new box with uninitialized contents in the provided allocator. ```APIDOC ## pub fn new_uninit_in(alloc: A) -> Box, A> ### Description Constructs a new box with uninitialized contents in the provided allocator. ``` -------------------------------- ### EventBus::new Source: https://docs.rs/guardian-db/0.20.26/guardian_db/events/struct.EventBus.html Creates a new instance of the EventBus. ```APIDOC ## pub fn new() -> Self ### Description Creates a new Event Bus instance. ### Signature `pub fn new() -> Self` ``` -------------------------------- ### CloneToUninit Implementation Source: https://docs.rs/guardian-db/0.20.26/guardian_db/events/struct.EventBox.html Experimental nightly-only API for performing copy-assignment to uninitialized memory. ```rust unsafe fn clone_to_uninit(&self, dest: *mut u8) ``` -------------------------------- ### Try to create a new Box Source: https://docs.rs/guardian-db/0.20.26/guardian_db/traits/type.OnWritePrototype.html Experimental API that returns an error if heap allocation fails. ```rust #![feature(allocator_api)] let five = Box::try_new(5)?; ``` -------------------------------- ### Try to create an uninitialized Box Source: https://docs.rs/guardian-db/0.20.26/guardian_db/traits/type.OnWritePrototype.html Experimental API for creating an uninitialized box with error handling for allocation failure. ```rust #![feature(allocator_api)] let mut five = Box::::try_new_uninit()?; // Deferred initialization: five.write(5); let five = unsafe { five.assume_init() }; assert_eq!(*five, 5); ``` -------------------------------- ### create_default_cache() Source: https://docs.rs/guardian-db/0.20.26/guardian_db/cache/fn.create_default_cache.html Initializes and returns a new RedbCache object configured with default optimized settings. ```APIDOC ## fn create_default_cache ### Description Creates a default cache with optimized settings for the guardian_db library. ### Signature `pub fn create_default_cache() -> RedbCache` ### Returns - **RedbCache** - An instance of the cache configured with default optimized parameters. ``` -------------------------------- ### pub fn new_base_index(public_key: Vec) -> Box + Send + Sync> Source: https://docs.rs/guardian-db/0.20.26/guardian_db/stores/base_store/index/fn.new_base_index.html Constructor for the BaseIndex. Creates a new instance with an empty HashMap to store the key-value index. ```APIDOC ## Function: new_base_index ### Description Constructor for the `BaseIndex`. Creates a new instance with an empty HashMap to store the key-value index. ### Signature `pub fn new_base_index(public_key: Vec) -> Box + Send + Sync>` ### Parameters - **public_key** (Vec) - The public key used to initialize the index. ``` -------------------------------- ### load Source: https://docs.rs/guardian-db/0.20.26/guardian_db/access_control/acl_iroh/struct.IrohAccessController.html Loads the access controller configuration from an address. ```APIDOC ### fn load(&self, address: &str) -> Result<()> Loads the access controller configuration from an address. ``` -------------------------------- ### Retrieving Bytes from Backend Source: https://docs.rs/guardian-db/0.20.26/guardian_db/p2p/network/client/struct.IrohClient.html Demonstrates retrieving data from the backend using a content hash. ```rust let client = IrohClient::development().await?; let hash = "..."; // content hash let data = client.cat_bytes(hash).await?; println!("Retrieved {} bytes", data.len()); ``` -------------------------------- ### get_or_create_topic_with_peers Source: https://docs.rs/guardian-db/0.20.26/guardian_db/p2p/network/core/gossip/struct.EpidemicPubSub.html Ensures a topic exists and bootstraps the mesh with specified peers. ```APIDOC ## fn get_or_create_topic_with_peers(&self, topic: &str, peers: Vec) ### Description Ensures that the specified topic exists, using the provided peers to bootstrap the gossip mesh. ### Parameters - **topic** (str) - The name of the topic. - **peers** (Vec) - A list of peer identifiers to bootstrap the connection. ``` -------------------------------- ### Try clone from reference with allocator Source: https://docs.rs/guardian-db/0.20.26/guardian_db/traits/type.OnWritePrototype.html Attempts to allocate memory and clone the source, returning a Result. Requires nightly features. ```rust #![feature(clone_from_ref)] #![feature(allocator_api)] use std::alloc::System; let hello: Box = Box::try_clone_from_ref_in("hello", System)?; ``` -------------------------------- ### NetworkConfig::development Source: https://docs.rs/guardian-db/0.20.26/guardian_db/p2p/network/config/struct.NetworkConfig.html Creates a new NetworkConfig instance configured for development environments. ```APIDOC ## fn development() ### Description Returns a NetworkConfig instance with settings optimized for development environments. ### Signature pub fn development() -> Self ``` -------------------------------- ### Box::try_new_uninit_in Source: https://docs.rs/guardian-db/0.20.26/guardian_db/traits/type.OnWritePrototype.html Constructs a new box with uninitialized contents in the provided allocator, returning an error if allocation fails. ```APIDOC ## pub fn try_new_uninit_in(alloc: A) -> Result, A>, AllocError> ### Description Constructs a new box with uninitialized contents in the provided allocator, returning an error if the allocation fails. ``` -------------------------------- ### Monitor synchronization progress Source: https://docs.rs/guardian-db/0.20.26/guardian_db/stores/sync_observer/struct.SyncObserver.html Demonstrates how to subscribe to a SyncObserver and handle various SyncEvent types in an asynchronous loop. ```rust use guardian_db::stores::sync_observer::{SyncObserver, SyncEvent}; async fn monitor_sync(observer: SyncObserver) { let mut receiver = observer.subscribe().await.unwrap(); while let Ok(event) = receiver.recv().await { match event { SyncEvent::Started { total, .. } => { println!("Synchronization started: {} entries", total); } SyncEvent::Progress { processed, total, .. } => { let pct = (processed as f64 / total as f64) * 100.0; println!("Progress: {:.1}% ({}/{})", pct, processed, total); } SyncEvent::Ready { .. } => { println!("Synchronization complete!"); } SyncEvent::Error { error, .. } => { eprintln!("Error: {}", error); } _ => {} } } } ``` -------------------------------- ### init_blobs Source: https://docs.rs/guardian-db/0.20.26/guardian_db/p2p/network/client/struct.IrohClient.html Initializes the iroh-blobs client using the backend’s shared store to ensure consistency and avoid storage duplication. ```APIDOC ## pub async fn init_blobs(&self) -> Result<()> ### Description Initializes the iroh-blobs client using the backend’s shared store. ### Returns - **Result<()>** - Ok(()) if initialized successfully, Err on error ``` -------------------------------- ### Clone from reference Source: https://docs.rs/guardian-db/0.20.26/guardian_db/traits/type.OnWritePrototype.html Experimental API to allocate memory and clone a reference into it. ```rust #![feature(clone_from_ref)] let hello: Box = Box::clone_from_ref("hello"); ``` -------------------------------- ### Convert Box to raw pointer Source: https://docs.rs/guardian-db/0.20.26/guardian_db/access_control/traits/type.Option.html Demonstrates converting a Box to a raw pointer and back for automatic cleanup. ```rust let x = Box::new(String::from("Hello")); let ptr = Box::into_raw(x); let x = unsafe { Box::from_raw(ptr) }; ``` -------------------------------- ### LevelDownCache implementation methods Source: https://docs.rs/guardian-db/0.20.26/guardian_db/cache/level_down/struct.LevelDownCache.html Core methods for initializing and managing the lifecycle of cache instances. ```rust pub fn new(_opts: Option<&Options>) -> Self ``` ```rust pub fn span(&self) -> &Span ``` ```rust pub fn load_internal( &self, directory: &str, db_address: &dyn Address, ) -> Result, Box> ``` ```rust pub fn close_internal(&self) -> Result<(), Box> ``` ```rust pub fn destroy_internal( &self, directory: &str, db_address: &dyn Address, ) -> Result<(), Box> ``` -------------------------------- ### Initialize a new TicketRegistry Source: https://docs.rs/guardian-db/0.20.26/guardian_db/p2p/network/core/ticket_exchange/fn.new_registry.html Creates an empty registry instance for ticket exchange operations. ```rust pub fn new_registry() -> TicketRegistry ```