### DashMap::with_capacity_and_hasher example Source: https://docs.rs/keyring-core/latest/keyring_core/sample/store/type.CredMap.html Creates a new DashMap with a specified starting capacity and hasher, then inserts two key-value pairs. ```rust use dashmap::DashMap; use std::collections::hash_map::RandomState; let s = RandomState::new(); let mappings = DashMap::with_capacity_and_hasher(2, s); mappings.insert(2, 4); mappings.insert(8, 16); ``` -------------------------------- ### DashMap::with_capacity example Source: https://docs.rs/keyring-core/latest/keyring_core/sample/store/type.CredMap.html Creates a new DashMap with a specified starting capacity and inserts two key-value pairs. ```rust use dashmap::DashMap; let mappings = DashMap::with_capacity(2); mappings.insert(2, 4); mappings.insert(8, 16); ``` -------------------------------- ### DashMap::with_capacity_and_hasher_and_shard_amount example Source: https://docs.rs/keyring-core/latest/keyring_core/sample/store/type.CredMap.html Creates a new DashMap with a specified starting capacity, hasher, and shard amount. The shard amount must be greater than 0 and a power of two; otherwise the function panics. ```rust use dashmap::DashMap; use std::collections::hash_map::RandomState; let s = RandomState::new(); let mappings = DashMap::with_capacity_and_hasher_and_shard_amount(2, s, 32); mappings.insert(2, 4); mappings.insert(8, 16); ``` -------------------------------- ### is_ok example Source: https://docs.rs/keyring-core/latest/keyring_core/error/type.Result.html?search= Example for the is_ok method, which returns true if the result is Ok. ```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); ``` -------------------------------- ### DashMap::hasher example Source: https://docs.rs/keyring-core/latest/keyring_core/sample/store/type.CredMap.html Returns a reference to the map's BuildHasher. The example creates a DashMap and retrieves its hasher. ```rust use dashmap::DashMap; use std::collections::hash_map::RandomState; let hasher = RandomState::new(); let map: DashMap = DashMap::new(); let hasher: &RandomState = map.hasher(); ``` -------------------------------- ### is_ok_and example Source: https://docs.rs/keyring-core/latest/keyring_core/error/type.Result.html?search= Example for the is_ok_and method, which returns true if the result is Ok and the value matches a predicate. The last case shows using as_ref to avoid consuming the result. ```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); ``` -------------------------------- ### Box::clone_from_ref_in example Source: https://docs.rs/keyring-core/latest/keyring_core/error/type.PlatformError.html Example showing Box::clone_from_ref_in, which allocates memory in the given allocator and clones the source into it. Requires nightly features clone_from_ref and allocator_api. ```rust #![feature(clone_from_ref)] #![feature(allocator_api)] use std::alloc::System; let hello: Box = Box::clone_from_ref_in("hello", System); ``` -------------------------------- ### Box::try_clone_from_ref_in example Source: https://docs.rs/keyring-core/latest/keyring_core/error/type.PlatformError.html Example demonstrating Box::try_clone_from_ref_in, which clones into a box with the given allocator and returns a Result, propagating errors with ?. Requires nightly features clone_from_ref and allocator_api. ```rust #![feature(clone_from_ref)] #![feature(allocator_api)] use std::alloc::System; let hello: Box = Box::try_clone_from_ref_in("hello", System)?; ``` -------------------------------- ### ok example Source: https://docs.rs/keyring-core/latest/keyring_core/error/type.Result.html?search= Demonstrates converting a Result to an Option, returning Some(value) for Ok and None for Err. ```rust let x: Result = Ok(2); assert_eq!(x.ok(), Some(2)); let x: Result = Err("Nothing here"); assert_eq!(x.ok(), None); ``` -------------------------------- ### Mock credential error handling example Source: https://docs.rs/keyring-core/latest/keyring_core/mock/index.html?search= Complete example showing how to set a mock error on a credential and verify that the error is returned once and then cleared. The error does not affect the stored password. ```rust keyring_core::set_default_store(mock::Store::new().unwrap()); let entry = Entry::new("service", "user").unwrap(); entry.set_password("test").expect("the entry's password is now test"); let mock: &mock::Cred = entry.as_any().downcast_ref().unwrap(); mock.set_error(Error::Invalid("mock error".to_string(), "takes precedence".to_string())); _ = entry.get_password().expect_err("the error will be returned"); let val = entry.get_password().expect("the error has been cleared"); assert_eq!(val, "test", "the error did not affect the password"); ``` -------------------------------- ### copied example for Result<&mut T, E> Source: https://docs.rs/keyring-core/latest/keyring_core/error/type.Result.html?search= Example for the copied method on Result<&mut T, E>, which copies the Ok value. Requires T: Copy. ```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)); ``` -------------------------------- ### Box::take example Source: https://docs.rs/keyring-core/latest/keyring_core/error/type.PlatformError.html Example demonstrating Box::take, which consumes the box and returns the value and a box to uninitialized memory. It then reuses the allocation with Box::write. ```rust #![feature(box_take)] let c = Box::new(5); // take the value out of the box let (value, uninit) = Box::take(c); assert_eq!(value, 5); // reuse the box for a second value let c = Box::write(uninit, 6); assert_eq!(*c, 6); ``` -------------------------------- ### cloned example for Result<&mut T, E> Source: https://docs.rs/keyring-core/latest/keyring_core/error/type.Result.html?search= Example for the cloned method on Result<&mut T, E>, which clones the Ok value. Requires T: Clone. ```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)); ``` -------------------------------- ### cloned example for Result<&T, E> Source: https://docs.rs/keyring-core/latest/keyring_core/error/type.Result.html?search= Example for the cloned method on Result<&T, E>, which clones the Ok value. Requires T: Clone. ```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)); ``` -------------------------------- ### copied example for Result<&T, E> Source: https://docs.rs/keyring-core/latest/keyring_core/error/type.Result.html?search= Example for the copied method on Result<&T, E>, which copies the Ok value. Requires T: Copy. ```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)); ``` -------------------------------- ### DashMap::new example Source: https://docs.rs/keyring-core/latest/keyring_core/sample/store/type.CredMap.html Creates a new DashMap with a capacity of 0 and inserts a key-value pair. ```rust use dashmap::DashMap; let reviews = DashMap::new(); reviews.insert("Veloren", "What a fantastic game!"); ``` -------------------------------- ### Box::into_inner example Source: https://docs.rs/keyring-core/latest/keyring_core/error/type.PlatformError.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Example for Box::into_inner, showing how to consume a box and retrieve the inner value. ```rust let c = Box::new(5); assert_eq!(Box::into_inner(c), 5); ``` -------------------------------- ### Result iterator example Source: https://docs.rs/keyring-core/latest/keyring_core/error/type.Result.html Example usage of Result as an iterator, converting into an iterator and using sum. ```rust let x: Result = Ok(2); assert_eq!(x.iter().sum::(), 2); let x: Result = Err("nothing"); assert_eq!(x.iter().sum::(), 0); ``` -------------------------------- ### as_ref example Source: https://docs.rs/keyring-core/latest/keyring_core/error/type.Result.html?search= Shows converting a Result to a Result of references, allowing inspection without consuming the original. ```rust let x: Result = Ok(2); assert_eq!(x.as_ref(), Ok(&2)); let x: Result = Err("Error"); assert_eq!(x.as_ref(), Err(&"Error")); ``` -------------------------------- ### map example Source: https://docs.rs/keyring-core/latest/keyring_core/error/type.Result.html?search= Shows mapping a Result's Ok value using a function, leaving Err untouched. The example parses lines of a string and prints each number multiplied by two. ```rust let line = "1\n2\n3\n4\n"; for num in line.lines() { match num.parse::().map(|i| i * 2) { Ok(n) => println!("{n}"), Err(..) => {} } } ``` -------------------------------- ### expect recommended message style example Source: https://docs.rs/keyring-core/latest/keyring_core/error/type.Result.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Shows the recommended style for expect messages: describe the reason you expect the Result to be Ok, focusing on the word 'should'. ```rust let path = std::env::var("IMPORTANT_PATH") .expect("env variable `IMPORTANT_PATH` should be set by `wrapper_script.sh`"); ``` -------------------------------- ### is_err example Source: https://docs.rs/keyring-core/latest/keyring_core/error/type.Result.html?search= Example for the is_err method, which returns true if the result is Err. ```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); ``` -------------------------------- ### and_then control flow example Source: https://docs.rs/keyring-core/latest/keyring_core/error/type.Result.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Shows the and_then method for control flow based on Result values. This example defines a function that squares a number and converts it to a string, returning an error on overflow. ```rust fn sq_then_to_string(x: u32) -> Result { x.checked_mul(x).map(|sq| sq.to_string()).ok_or("overflowed") } ``` -------------------------------- ### Box::map example Source: https://docs.rs/keyring-core/latest/keyring_core/error/type.PlatformError.html Example showing Box::map, which maps the value in a box and reuses the allocation if possible. The result is also boxed. ```rust let b = Box::new(7); let new = Box::map(b, |i| i + 7); assert_eq!(*new, 14); ``` -------------------------------- ### Box::try_map example Source: https://docs.rs/keyring-core/latest/keyring_core/error/type.PlatformError.html Example demonstrating Box::try_map, which attempts to map the value in a box and returns a Try type. The example uses u32::try_from and unwraps the result. ```rust #![feature(smart_pointer_try_map)] let b = Box::new(7); let new = Box::try_map(b, u32::try_from).unwrap(); assert_eq!(*new, 7); ``` -------------------------------- ### is_err_and example Source: https://docs.rs/keyring-core/latest/keyring_core/error/type.Result.html?search= Shows how to use is_err_and to check if a Result is Err and the error value matches a predicate. The example uses std::io::Error and demonstrates true/false results for different error kinds and an Ok value. ```rust use std::io::{Error, ErrorKind}; let x: Result = Err(Error::new(ErrorKind::NotFound, "!")); assert_eq!(x.is_err_and(|x| x.kind() == ErrorKind::NotFound), true); let x: Result = Err(Error::new(ErrorKind::PermissionDenied, "!")); assert_eq!(x.is_err_and(|x| x.kind() == ErrorKind::NotFound), false); let x: Result = Ok(123); assert_eq!(x.is_err_and(|x| x.kind() == ErrorKind::NotFound), false); let x: Result = Err("ownership".to_string()); assert_eq!(x.as_ref().is_err_and(|x| x.len() > 1), true); println!("still alive {:?}", x); ``` -------------------------------- ### transpose example for Result, E> Source: https://docs.rs/keyring-core/latest/keyring_core/error/type.Result.html?search= Example for the transpose method on Result, E>, which converts a Result of an Option into an Option of a Result. Ok(None) maps to None, Ok(Some(_)) and Err(_) map to Some(Ok(_)) and Some(Err(_)). ```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); ``` -------------------------------- ### map_or_default example Source: https://docs.rs/keyring-core/latest/keyring_core/error/type.Result.html?search= Demonstrates mapping the Ok value with a function, or returning the default value of the type U for Err. ```rust let x: Result<_, &str> = Ok("foo"); let y: Result<&str, _> = Err("bar"); assert_eq!(x.map_or_default(|x| x.len()), 3); assert_eq!(y.map_or_default(|y| y.len()), 0); ``` -------------------------------- ### err example Source: https://docs.rs/keyring-core/latest/keyring_core/error/type.Result.html?search= Demonstrates converting a Result to an Option, returning Some(error) for Err and None for Ok. ```rust let x: Result = Ok(2); assert_eq!(x.err(), None); let x: Result = Err("Nothing here"); assert_eq!(x.err(), Some("Nothing here")); ``` -------------------------------- ### DashMap::with_hasher example Source: https://docs.rs/keyring-core/latest/keyring_core/sample/store/type.CredMap.html Creates a new DashMap with a capacity of 0 and the provided hasher, then inserts a key-value pair. ```rust use dashmap::DashMap; use std::collections::hash_map::RandomState; let s = RandomState::new(); let reviews = DashMap::with_hasher(s); reviews.insert("Veloren", "What a fantastic game!"); ``` -------------------------------- ### flatten example for Result, E> Source: https://docs.rs/keyring-core/latest/keyring_core/error/type.Result.html?search= Example for the flatten method on Result, E>, which converts to Result by removing one level of nesting. ```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()); ``` -------------------------------- ### expect example: panic on Err Source: https://docs.rs/keyring-core/latest/keyring_core/error/type.Result.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Returns the contained Ok value, panicking if the value is Err. The example shows a panic message with the passed message and the Err content. ```rust let x: Result = Err("emergency failure"); x.expect("Testing expect"); // panics with `Testing expect: emergency failure` ``` -------------------------------- ### Box::into_inner example Source: https://docs.rs/keyring-core/latest/keyring_core/error/type.PlatformError.html Example showing how to use Box::into_inner to extract the value from a box. The code asserts that the extracted value equals 5. ```rust assert_eq!(Box::into_inner(c), 5); ``` -------------------------------- ### Box::into_inner example (partial) Source: https://docs.rs/keyring-core/latest/keyring_core/error/type.PlatformError.html Consumes a Box and returns the wrapped value using the nightly-only box_into_inner feature. The example only shows the creation of the box; the actual into_inner call is not shown. ```rust #![feature(box_into_inner)] let c = Box::new(5); ``` -------------------------------- ### as_mut example Source: https://docs.rs/keyring-core/latest/keyring_core/error/type.Result.html?search= Demonstrates converting a mutable Result to a Result of mutable references, allowing modification of the contained value. ```rust fn mutate(r: &mut Result) { match r.as_mut() { Ok(v) => *v = 42, Err(e) => *e = 0, } } let mut x: Result = Ok(2); mutate(&mut x); assert_eq!(x.unwrap(), 42); let mut x: Result = Err(13); mutate(&mut x); assert_eq!(x.unwrap_err(), 0); ``` -------------------------------- ### iter example: iterate over Ok value Source: https://docs.rs/keyring-core/latest/keyring_core/error/type.Result.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Returns an iterator over the possibly contained value, yielding one value if Ok, otherwise none. The example shows both Ok and Err cases. ```rust let x: Result = Ok(7); assert_eq!(x.iter().next(), Some(&7)); let x: Result = Err("nothing!"); assert_eq!(x.iter().next(), None); ``` -------------------------------- ### clear example Source: https://docs.rs/keyring-core/latest/keyring_core/sample/store/type.CredMap.html Removes all key-value pairs from the map. ```rust use dashmap::DashMap; let mut map = DashMap::new(); map.insert("Albin", 15); map.insert("Jones", 22); map.insert("Charlie", 27); map.clear(); assert!(map.is_empty()); ``` -------------------------------- ### DashMap::with_capacity_and_shard_amount example Source: https://docs.rs/keyring-core/latest/keyring_core/sample/store/type.CredMap.html Creates a new DashMap with a specified capacity and shard amount. The shard amount must be greater than 0 and a power of two; otherwise the function panics. ```rust use dashmap::DashMap; let mappings = DashMap::with_capacity_and_shard_amount(32, 32); mappings.insert(2, 4); mappings.insert(8, 16); ``` -------------------------------- ### DashMap::with_hasher_and_shard_amount example Source: https://docs.rs/keyring-core/latest/keyring_core/sample/store/type.CredMap.html Creates a new DashMap with a specified hasher and shard amount. The shard amount must be greater than 0 and a power of two; otherwise the function panics. ```rust use dashmap::DashMap; use std::collections::hash_map::RandomState; let s = RandomState::new(); let mappings = DashMap::with_hasher_and_shard_amount(s, 32); mappings.insert(2, 4); mappings.insert(8, 16); ``` -------------------------------- ### Non-blocking get with try_get Source: https://docs.rs/keyring-core/latest/keyring_core/sample/store/type.CredMap.html Attempts to get an immutable reference without blocking; returns TryResult::Locked if the shard is locked. The example shows that holding a mutable reference causes try_get to return a locked result. ```rust use dashmap::DashMap; use dashmap::try_result::TryResult; let map = DashMap::new(); map.insert("Johnny", 21); assert_eq!(*map.try_get("Johnny").unwrap(), 21); let _result1_locking = map.get_mut("Johnny"); let result2 = map.try_get("Johnny"); assert!(result2.is_locked()); ``` -------------------------------- ### Store::new_with_configuration Source: https://docs.rs/keyring-core/latest/keyring_core/sample/store/struct.Store.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Creates a new store with a user-specified configuration. Allowed configuration keys are 'persist' and 'backing-file'. ```APIDOC ## Store::new_with_configuration ### Description Creates a new store with a user-specified configuration. There are two allowed configuration keys: `persist` and `backing-file`. See the module docs for details of how these affect the store's behavior. ### Method new_with_configuration ### Signature pub fn new_with_configuration(config: &HashMap<&str, &str>) -> Result> ### Parameters - **config** (&HashMap<&str, &str>) - Required - A map of configuration keys to values. ### Returns - **Result>** - A result containing an Arc to the new store, or an error. ``` -------------------------------- ### Construct a Box from a raw pointer with Box::from_raw_in Source: https://docs.rs/keyring-core/latest/keyring_core/error/type.PlatformError.html Requires the nightly-only `allocator_api` feature. The first example recreates a `Box` from a raw pointer obtained via `Box::into_raw_with_allocator`. The second manually creates a `Box` from scratch using the system allocator, writing a value to the allocated memory before constructing the box. Both are unsafe and require the memory to be allocated by the given allocator. ```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); } ``` -------------------------------- ### Store::new_with_backing Source: https://docs.rs/keyring-core/latest/keyring_core/sample/store/struct.Store.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Creates a new store from a backing file. The file need not exist; if it does, initial contents are loaded from it. ```APIDOC ## Store::new_with_backing ### Description Creates a new store from a backing file. The backing file must be a valid path, but it need not exist, in which case the store starts off empty. If the file does exist, the initial contents of the store are loaded from it. ### Method new_with_backing ### Signature pub fn new_with_backing(path: &str) -> Result> ### Parameters - **path** (&str) - Required - The path to the backing file. ### Returns - **Result>** - A result containing an Arc to the new store, or an error. ``` -------------------------------- ### Non-blocking mutable get with try_get_mut Source: https://docs.rs/keyring-core/latest/keyring_core/sample/store/type.CredMap.html Attempts to get a mutable reference without blocking; returns TryResult::Locked if the shard is locked. The example shows that holding an immutable reference causes try_get_mut to return a locked result. ```rust use dashmap::DashMap; use dashmap::try_result::TryResult; let map = DashMap::new(); map.insert("Johnny", 21); *map.try_get_mut("Johnny").unwrap() += 1; assert_eq!(*map.get("Johnny").unwrap(), 22); let _result1_locking = map.get("Johnny"); let result2 = map.try_get_mut("Johnny"); assert!(result2.is_locked()); ``` -------------------------------- ### Construct a Box from a NonNull pointer with Box::from_non_null_in Source: https://docs.rs/keyring-core/latest/keyring_core/error/type.PlatformError.html Requires the nightly-only `allocator_api` feature. The first example recreates a `Box` from a `NonNull` pointer obtained via `Box::into_non_null_with_allocator`. The second manually creates a `Box` from scratch using the system allocator, writing a value to the allocated memory before constructing the box. Both are unsafe and require the memory to be allocated by the given allocator. ```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); } ``` -------------------------------- ### Store::new Source: https://docs.rs/keyring-core/latest/keyring_core/sample/store/struct.Store.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Creates a new store with a default configuration (empty, no backing file). Returns an Arc to the store. ```APIDOC ## Store::new ### Description Creates a new store with a default configuration. The default configuration is empty with no backing file. ### Method new ### Signature pub fn new() -> Result> ### Parameters None ### Returns - **Result>** - A result containing an Arc to the new store, or an error. ``` -------------------------------- ### map_or example Source: https://docs.rs/keyring-core/latest/keyring_core/error/type.Result.html?search= Demonstrates providing a default value for Err or applying a function to the Ok value. Note that arguments are eagerly evaluated. ```rust let x: Result<_, &str> = Ok("foo"); assert_eq!(x.map_or(42, |v| v.len()), 3); let x: Result<&str, _> = Err("bar"); assert_eq!(x.map_or(42, |v| v.len()), 42); ``` -------------------------------- ### Store::new_internal Source: https://docs.rs/keyring-core/latest/keyring_core/sample/store/struct.Store.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Creates a store with the given credentials and backing file. This is an internal constructor. ```APIDOC ## Store::new_internal ### Description Creates a store with the given credentials and backing file. ### Method new_internal ### Signature pub fn new_internal(creds: CredMap, backing: Option) -> Arc ### Parameters - **creds** (CredMap) - Required - The credentials to initialize the store with. - **backing** (Option) - Required - The backing file path, if any. ### Returns - **Arc** - An Arc to the new store. ``` -------------------------------- ### DashMap::with_shard_amount example Source: https://docs.rs/keyring-core/latest/keyring_core/sample/store/type.CredMap.html Creates a new DashMap with a specified shard amount. The shard amount must be greater than 0 and a power of two; otherwise the function panics. ```rust use dashmap::DashMap; let mappings = DashMap::with_shard_amount(32); mappings.insert(2, 4); mappings.insert(8, 16); ``` -------------------------------- ### Get immutable reference with get Source: https://docs.rs/keyring-core/latest/keyring_core/sample/store/type.CredMap.html Gets an immutable reference to an entry by key. May deadlock if called while holding a mutable reference into the map. ```rust use dashmap::DashMap; let youtubers = DashMap::new(); youtubers.insert("Bosnian Bill", 457000); assert_eq!(*youtubers.get("Bosnian Bill").unwrap(), 457000); ``` -------------------------------- ### get Source: https://docs.rs/keyring-core/latest/keyring_core/sample/store/type.CredMap.html Get an immutable reference to an entry in the map. ```APIDOC ## get ### Description Get an immutable reference to an entry in the map. ### Method get ### Signature pub fn get(&'a self, key: &Q) -> Option> where K: Borrow, Q: Hash + Eq + ?Sized, ### Parameters - **key** (&Q) - Required - The key to look up. ### Return Value - Option> - An immutable reference to the entry if it exists, otherwise None. ### Locking Behaviour May deadlock if called when holding a mutable reference into the map. ### Example ```rust use dashmap::DashMap; let youtubers = DashMap::new(); youtubers.insert("Bosnian Bill", 457000); assert_eq!(*youtubers.get("Bosnian Bill").unwrap(), 457000); ``` ``` -------------------------------- ### Convert String to Box Source: https://docs.rs/keyring-core/latest/keyring_core/error/type.PlatformError.html Demonstrates converting a `String` into a boxed `dyn Error + Send + Sync` using `Box::::from`. The example asserts the boxed error size. ```rust use std::error::Error; let a_string_error = "a string error".to_string(); let a_boxed_error = Box::::from(a_string_error); assert!( size_of::>() == size_of_val(&a_boxed_error)) ``` -------------------------------- ### Entry::new(service, user) Source: https://docs.rs/keyring-core/latest/keyring_core/mock/index.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Creates a new credential entry for use with the mock store. ```APIDOC ## [Rust] Entry::new(service, user) ### Description Creates a new credential entry with the given service and user. This is used to interact with the mock store. ### Method Rust function call ### Endpoint Entry::new(service, user) ### Parameters - **service** (string) - Required - The service name for the credential. - **user** (string) - Required - The user name for the credential. ### Return Value - **Result** - A new entry or an error. ### Example ```rust let entry = Entry::new("service", "user").unwrap(); ``` ``` -------------------------------- ### Box::into_non_null_with_allocator: convert back to Box for automatic cleanup Source: https://docs.rs/keyring-core/latest/keyring_core/error/type.PlatformError.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Uses Box::into_non_null_with_allocator to get a NonNull pointer and allocator, then converts back with Box::from_non_null_in for automatic cleanup. Requires nightly allocator_api. ```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) }; ``` -------------------------------- ### Box::into_non_null equivalent cleanup Source: https://docs.rs/keyring-core/latest/keyring_core/error/type.PlatformError.html Equivalent to the manual cleanup example, but uses Box::from_non_null and drop to perform cleanup. This is the easiest way to release the memory after converting a Box to a NonNull pointer. ```rust let x = Box::new(String::from("Hello")); let non_null = Box::into_non_null(x); unsafe { drop(Box::from_non_null(non_null)); } ``` -------------------------------- ### Discouraged From> for Pin implementation Source: https://docs.rs/keyring-core/latest/keyring_core/error/type.PlatformError.html Shows a discouraged implementation of From> for Pin that introduces ambiguity when calling Pin::from. The example defines a local type Foo and implements From> for Pin, then uses Pin::from on a boxed unit. ```rust struct Foo; // A type defined in this crate. impl From> for Pin { fn from(_: Box<()>) -> Pin { Pin::new(Foo) } } let foo = Box::new(()); let bar = Pin::from(foo); ``` -------------------------------- ### Entry::new Source: https://docs.rs/keyring-core/latest/keyring_core/mock/index.html?search=u32+-%3E+bool Creates a new credential entry in the default store. This is a standard method on Entry, but is used with the mock store for testing. ```APIDOC ## Entry::new ### Description Creates a new credential entry in the default store. This is a standard method on Entry, but is used with the mock store for testing. ### Usage ```rust let entry = Entry::new("service", "user").unwrap(); ``` ### Parameters - **service** (str) - Required - The service name. - **user** (str) - Required - The username. ### Returns - **Result** - Ok containing the new entry, or Err if creation failed. ``` -------------------------------- ### Get mutable reference with get_mut Source: https://docs.rs/keyring-core/latest/keyring_core/sample/store/type.CredMap.html Gets a mutable reference to an entry, allowing in-place modification. May deadlock if called while holding any reference into the map. ```rust use dashmap::DashMap; let class = DashMap::new(); class.insert("Albin", 15); *class.get_mut("Albin").unwrap() -= 1; assert_eq!(*class.get("Albin").unwrap(), 14); ``` -------------------------------- ### Box::new_uninit Source: https://docs.rs/keyring-core/latest/keyring_core/error/type.PlatformError.html Documentation for the `Box::new_uninit` associated function. ```APIDOC ## Box::new_uninit ### Description Constructs a new box with uninitialized contents. ### Method Associated function ### Signature `pub fn new_uninit() -> Box>` ### Returns - **Box>** - A box with uninitialized contents. ### Examples ```rust let mut five = Box::::new_uninit(); // Deferred initialization: five.write(5); let five = unsafe { five.assume_init() }; assert_eq!(*five, 5) ``` ``` -------------------------------- ### mock::Store::new Source: https://docs.rs/keyring-core/latest/keyring_core/mock/index.html?search=u32+-%3E+bool Creates a new mock credential store. The store is platform-independent and provides no persistence. ```APIDOC ## mock::Store::new ### Description Creates a new mock credential store. The store is platform-independent and provides no persistence. ### Usage ```rust let store = keyring_core::mock::Store::new().unwrap(); ``` ### Returns - **Result** - Ok containing the new store, or Err if creation failed. ``` -------------------------------- ### Store::new Source: https://docs.rs/keyring-core/latest/keyring_core/mock/index.html?search= Creates a new mock credential store. This store is platform-independent, provides no persistence, and allows specifying return values for each call. ```APIDOC ## Store::new ### Description Creates a new mock credential store. This store is platform-independent, provides no persistence, and allows specifying return values for each call. ### Method Constructor ### Signature `Store::new() -> Result` ### Usage Call during application startup before creating any entries to use the mock store as the default. ### Example ```rust keyring_core::set_default_store(keyring_core::mock::Store::new().unwrap()); ``` ### Returns A `Result` containing the new `Store` on success, or an `Error` on failure. ``` -------------------------------- ### Entry Struct Methods Source: https://docs.rs/keyring-core/latest/keyring_core/struct.Entry.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Documentation for the Entry struct methods in the keyring_core crate. ```APIDOC ## Entry::new ### Description Creates a new Entry for the given service and user using the default credential builder. ### Method new ### Signature pub fn new(service: &str, user: &str) -> Result ### Parameters - **service** (&str) - Required - The service name for the credential. - **user** (&str) - Required - The user name for the credential. ### Errors - Returns an `Invalid` error if the `service` or `user` values are not acceptable to the default credential store. - Returns a `NoDefaultStore` error if the default credential store has not been set. ``` ```APIDOC ## Entry::new_with_modifiers ### Description Creates a new Entry for the given service and user, passing store-specific modifiers. ### Method new_with_modifiers ### Signature pub fn new_with_modifiers(service: &str, user: &str, modifiers: &HashMap<&str, &str>) -> Result ### Parameters - **service** (&str) - Required - The service name for the credential. - **user** (&str) - Required - The user name for the credential. - **modifiers** (&HashMap<&str, &str>) - Required - Store-specific modifiers. ### Errors - Returns an `Invalid` error if the `service`, `user`, or `modifier` pairs are not acceptable to the default credential store. - Returns a `NoDefaultStore` error if the default credential store has not been set. ``` ```APIDOC ## Entry::new_with_credential ### Description Creates an Entry that wraps a pre-existing credential from any credential store. ### Method new_with_credential ### Signature pub fn new_with_credential(credential: Arc) -> Entry ### Parameters - **credential** (Arc) - Required - The credential to wrap. ``` ```APIDOC ## Entry::search ### Description Searches for credentials in the default credential store, returning entries that wrap any found. ### Method search ### Signature pub fn search(spec: &HashMap<&str, &str>) -> Result> ### Parameters - **spec** (&HashMap<&str, &str>) - Required - The search specification. ### Errors - Returns an `Invalid` error if the `spec` value is not acceptable to the default credential store. - Returns a `NoDefaultStore` error if the default credential store has not been set. ``` ```APIDOC ## Entry::set_password ### Description Sets the password for this entry. If a credential already exists, it updates the password; otherwise, it creates a new credential. ### Method set_password ### Signature pub fn set_password(&self, password: &str) -> Result<()> ### Parameters - **password** (&str) - Required - The password to set. ### Errors - Returns an `Ambiguous` error if this entry is a specifier and there is more than one matching credential. - Returns a `NoEntry` error if this entry is a wrapper and the underlying credential has been deleted. - Returns an `Invalid` error if the credential cannot store the given password. ``` ```APIDOC ## Entry::set_secret ### Description Sets the secret for this entry. If a credential already exists, it updates the secret; otherwise, it creates a new credential. ### Method set_secret ### Signature pub fn set_secret(&self, secret: &[u8]) -> Result<()> ### Parameters - **secret** (&[u8]) - Required - The secret to set. ### Errors - Returns an `Ambiguous` error if this entry is a specifier and there is more than one matching credential. - Returns a `NoEntry` error if this entry is a wrapper and the underlying credential has been deleted. - Returns an `Invalid` error if the credential cannot store the given secret. ``` ```APIDOC ## Entry::get_password ### Description Retrieves the password saved for this entry. ### Method get_password ### Signature pub fn get_password(&self) -> Result ### Errors - Returns a `NoEntry` error if this entry is a specifier and there is no matching credential. - Returns an `Ambiguous` error if this entry is a specifier and there is more than one matching credential. - Returns a `NoEntry` error if this entry is a wrapper and the underlying credential has been deleted and cannot be recreated. - Returns a `BadEncoding` error containing the data as a byte array if the password is not valid UTF-8. ``` ```APIDOC ## Entry::get_secret ### Description Retrieves the secret saved for this entry. ### Method get_secret ### Signature pub fn get_secret(&self) -> Result> ### Errors - Returns a `NoEntry` error if this entry is a specifier and there is no matching credential. - Returns an `Ambiguous` error if this entry is a specifier and there is more than one matching credential. - Returns a `NoEntry` error if this entry is a wrapper and the underlying credential has been deleted. ``` ```APIDOC ## Entry::get_attributes ### Description Gets the store-specific decorations on this entry's credential. ### Method get_attributes ### Signature pub fn get_attributes(&self) -> Result> ### Errors - Returns a `NoEntry` error if this entry is a specifier and there is no matching credential. - Returns an `Ambiguous` error if this entry is a specifier and there is more than one matching credential. - Returns a `NoEntry` error if this entry is a wrapper and the underlying credential has been deleted. ``` -------------------------------- ### as_deref example: coerce Ok via Deref Source: https://docs.rs/keyring-core/latest/keyring_core/error/type.Result.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Converts Result to Result<&::Target, &E>. The example shows both Ok and Err cases with String and u32. ```rust let x: Result = Ok("hello".to_string()); let y: Result<&str, &u32> = Ok("hello"); assert_eq!(x.as_deref(), y); let x: Result = Err(42); let y: Result<&str, &u32> = Err(&42); assert_eq!(x.as_deref(), y); ``` -------------------------------- ### Entry::new_with_credential Source: https://docs.rs/keyring-core/latest/keyring_core/struct.Entry.html?search=std%3A%3Avec Creates an Entry that wraps a pre-existing credential from any credential store. ```APIDOC ## Entry::new_with_credential ### Description Creates an entry that wraps a pre-existing credential. The credential can be from any credential store. ### Method new_with_credential ### Signature pub fn new_with_credential(credential: Arc) -> Entry ### Parameters - **credential** (Arc) - Required - The pre-existing credential to wrap. ``` -------------------------------- ### Box::new_uninit Source: https://docs.rs/keyring-core/latest/keyring_core/error/type.PlatformError.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Constructs a new Box with uninitialized contents, allowing deferred initialization. Available on non-no_global_oom_handling only. ```APIDOC ## pub fn new_uninit() -> Box> ### Description Constructs a new box with uninitialized contents. Available on **non-`no_global_oom_handling`** only. ### Parameters None. ### Returns - **Box>** - A box with uninitialized contents. ### Example ```rust let mut five = Box::::new_uninit(); // Deferred initialization: five.write(5); let five = unsafe { five.assume_init() }; assert_eq!(*five, 5) ``` ``` -------------------------------- ### keyring_core::mock::Store::new() Source: https://docs.rs/keyring-core/latest/keyring_core/mock/index.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Creates a new mock credential store for testing purposes. ```APIDOC ## [Rust] keyring_core::mock::Store::new() ### Description Creates a new mock credential store that is platform-independent and provides no persistence. This store allows clients to specify return values (including errors) for each call. ### Method Rust function call ### Endpoint keyring_core::mock::Store::new() ### Parameters None ### Return Value - **Result** - A new mock store instance or an error. ### Example ```rust let store = keyring_core::mock::Store::new().unwrap(); ``` ``` -------------------------------- ### Box::leak unsized data example Source: https://docs.rs/keyring-core/latest/keyring_core/error/type.PlatformError.html Example of `Box::leak` with unsized data (a boxed slice). The leaked mutable reference allows modifying the slice elements, and the assertion verifies the change. ```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]); ``` -------------------------------- ### as_deref_mut example: mutable Deref coercion Source: https://docs.rs/keyring-core/latest/keyring_core/error/type.Result.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Converts Result to Result<&mut ::Target, &mut E>. The example shows both Ok and Err cases, mutating the Ok value. ```rust let mut s = "HELLO".to_string(); let mut x: Result = Ok("hello".to_string()); let y: Result<&mut str, &mut u32> = Ok(&mut s); assert_eq!(x.as_deref_mut().map(|x| { x.make_ascii_uppercase(); x }), y); let mut i = 42; let mut x: Result = Err(42); let y: Result<&mut str, &mut u32> = Err(&mut i); assert_eq!(x.as_deref_mut().map(|x| { x.make_ascii_uppercase(); x }), y); ``` -------------------------------- ### inspect_err example: read file with error logging Source: https://docs.rs/keyring-core/latest/keyring_core/error/type.Result.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Calls a function with a reference to the contained value if Err, returning the original result. The example reads a file and logs an error message on failure. ```rust use std::{fs, io}; fn read() -> io::Result { fs::read_to_string("address.txt") .inspect_err(|e| eprintln!("failed to read file: {e}")) } ``` -------------------------------- ### iter_mut example: mutable iteration Source: https://docs.rs/keyring-core/latest/keyring_core/error/type.Result.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Returns a mutable iterator over the possibly contained value, yielding one value if Ok, otherwise none. The example shows modifying the Ok value and an Err case. ```rust let mut x: Result = Ok(7); match x.iter_mut().next() { Some(v) => *v = 40, None => {}, } assert_eq!(x, Ok(40)); let mut x: Result = Err("nothing!"); assert_eq!(x.iter_mut().next(), None); ``` -------------------------------- ### get_specifiers Source: https://docs.rs/keyring-core/latest/keyring_core/struct.Entry.html?search=std%3A%3Avec Gets the `` pair for this entry, if any. ```APIDOC ## get_specifiers ### Description Gets the `` pair for this entry, if any. ### Method pub fn get_specifiers(&self) -> Option<(String, String)> ``` -------------------------------- ### into_ok(self) -> T Source: https://docs.rs/keyring-core/latest/keyring_core/error/type.Result.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Documentation for the `into_ok` method on `Result`. ```APIDOC ## into_ok(self) -> T ### Description Returns the contained `Ok` value, but never panics. This method is known to never panic on the result types it is implemented for. It can be used instead of `unwrap` as a maintainability safeguard that will fail to compile if the error type of the `Result` is later changed to an error that can actually occur. ### Signature `pub const fn into_ok(self) -> T where E: Into` ### Parameters - **self** (Result) - The result value to unwrap. ### Returns - **T** - The contained `Ok` value. ### Examples ```rust fn only_good_news() -> Result { Ok("this is fine".into()) } let s: String = only_good_news().into_ok(); println!("{s}"); ``` ### Availability Nightly-only experimental API (`unwrap_infallible`) ``` -------------------------------- ### Entry::get_password() Source: https://docs.rs/keyring-core/latest/keyring_core/mock/index.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Gets the password for a credential entry. ```APIDOC ## [Rust] Entry::get_password() ### Description Gets the password for the credential entry from the mock store. ### Method Rust function call ### Endpoint Entry::get_password() ### Parameters None ### Return Value - **Result** - The password or an error. ### Example ```rust let val = entry.get_password().expect("the error has been cleared"); ``` ```