### Get References from Result Source: https://docs.rs/explicon/0.2.0/explicon/type.Result.html Use `as_ref` to get references to the contained values of a `Result` without consuming it. `as_mut` provides mutable references. ```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")); ``` ```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); ``` -------------------------------- ### Collect Results from Iterator Source: https://docs.rs/explicon/0.2.0/explicon/type.Result.html Use `collect()` to gather results from an iterator. If any element is an `Err`, it's returned immediately. Otherwise, a container with all `Ok` values is returned. This example demonstrates checking for overflow during addition. ```rust let v = vec![1, 2]; let res: Result, &'static str> = v.iter().map(|x: &u32| x.checked_add(1).ok_or("Overflow!") ).collect(); assert_eq!(res, Ok(vec![2, 3])); ``` -------------------------------- ### CloneToUninit Implementation (Nightly) Source: https://docs.rs/explicon/0.2.0/explicon/enum.Sourced.html An experimental, nightly-only API that performs copy-assignment from `self` to an uninitialized destination. Requires `T` to implement `Clone`. ```rust unsafe fn clone_to_uninit(&self, dest: *mut u8) ``` -------------------------------- ### Iterator Collection with Side Effects Source: https://docs.rs/explicon/0.2.0/explicon/type.Result.html Illustrates that `collect()` on a `Result` iterator stops processing upon encountering an `Err`. This example shows a side effect (updating `shared`) that only occurs for elements processed before the error. ```rust let v = vec![3, 2, 1, 10]; let mut shared = 0; let res: Result, &'static str> = v.iter().map(|x: &u32| { shared += x; x.checked_sub(2).ok_or("Underflow!") }).collect(); assert_eq!(res, Err("Underflow!")); assert_eq!(shared, 6); ``` -------------------------------- ### Handling File Metadata with `and_then` Source: https://docs.rs/explicon/0.2.0/explicon/type.Result.html Demonstrates using `and_then` to chain metadata retrieval and modification time operations on file paths. It shows how to handle potential errors like 'NotFound'. Note that path interpretation can be OS-dependent. ```rust use std::{io::ErrorKind, path::Path}; // Note: on Windows "/" maps to "C:\\" let root_modified_time = Path::new("/").metadata().and_then(|md| md.modified()); assert!(root_modified_time.is_ok()); let should_fail = Path::new("/bad/path").metadata().and_then(|md| md.modified()); assert!(should_fail.is_err()); assert_eq!(should_fail.unwrap_err().kind(), ErrorKind::NotFound); ``` -------------------------------- ### Explicon Core Components Source: https://docs.rs/explicon/0.2.0/index.html Overview of the primary enums and type aliases provided by the explicon crate for configuration resolution. ```APIDOC ## Core Components ### Enums - **ExpliconError**: Represents errors that can occur during configuration value resolution. - **Sourced**: A configuration value that can be sourced either directly or from an environment variable. ### Type Aliases - **Result**: Result type alias using `ExpliconError` for error handling in configuration resolution. ``` -------------------------------- ### Define Sourced Configuration and Error Handling Source: https://docs.rs/explicon/0.2.0/src/explicon/lib.rs.html The core structure for handling sourced configuration values and the associated error type. ```rust use std::{env::var, str::FromStr}; use serde::{Deserialize, Serialize}; /// Represents errors that can occur during configuration value resolution. #[derive(thiserror::Error, Debug)] pub enum ExpliconError { /// Occurs when an environment variable can't be resolved. #[error("Error while resolving env var: {0}")] Var(#[from] std::env::VarError), /// Generic error container for other resolution failures. #[error("{0}")] Other(String), } /// Result type alias using [`ExpliconError`] for error handling in configuration resolution. pub type Result = std::result::Result; /// A configuration value that can be sourced either directly or from an environment variable. /// /// Supports deserialization from both formats: /// - Direct value representation (e.g., `42` or `"direct_value"`) /// - Environment variable reference (e.g., `{ "env": "VAR_NAME" }`) #[derive(Debug, Clone, Deserialize, Serialize)] #[serde(rename_all = "snake_case")] pub enum Sourced { /// Value should be read from the specified environment variable Env(String), /// Directly provided value that doesn't require resolution #[serde(untagged)] Value(T), } ``` -------------------------------- ### Unwrap Result or Default Source: https://docs.rs/explicon/0.2.0/explicon/type.Result.html Returns the Ok value or the default value of the type if the result is an Err. ```rust let good_year_from_input = "1909"; let bad_year_from_input = "190blarg"; let good_year = good_year_from_input.parse().unwrap_or_default(); let bad_year = bad_year_from_input.parse().unwrap_or_default(); assert_eq!(1909, good_year); assert_eq!(0, bad_year); ``` -------------------------------- ### Resolve Sourced Values via FromStr Source: https://docs.rs/explicon/0.2.0/src/explicon/lib.rs.html Methods for resolving configuration values that implement FromStr, including validation and fallback logic. ```rust impl Sourced where T: FromStr, T: Clone, ::Err: ToString, { /// Resolves the configuration value by parsing if sourced from an environment variable. /// /// Use this method when the target type `T` implements [`FromStr`] (e.g., numbers, booleans). /// /// # Returns /// - `Ok(T)` with direct value if using [`Sourced::Value`] /// - `Ok(T)` with **parsed** environment variable value if using [`Sourced::Env`] /// /// # Errors /// - [`ExpliconError::Var`] if environment variable lookup fails /// - [`ExpliconError::Other`] if environment variable value parsing fails (via [`FromStr`]) pub fn resolve(&self) -> Result { match self { Self::Value(value) => Ok(value.clone()), Self::Env(var_name) => { let var_value = var(var_name)?; // Получаем String // Используем parse, т.к. T: FromStr let value = var_value .parse::() .map_err(|e| ExpliconError::Other(e.to_string()))?; Ok(value) } } } /// Resolves the value using `resolve()` or returns type's default if resolution fails. pub fn resolve_or_default(&self) -> Result where T: Default, { self.resolve().or_else(|_| Ok(T::default())) } /// Resolves the value using `resolve()` or returns the provided fallback value if resolution fails. pub fn resolve_or(&self, fallback: T) -> T { self.resolve().unwrap_or(fallback) } /// Resolves the value using `resolve()` and validates it against a predicate. pub fn resolve_and_validate(&self, validator: F) -> Result where F: FnOnce(&T) -> bool, { let value = self.resolve()?; if validator(&value) { Ok(value) } else { Err(ExpliconError::Other("Validation failed".into())) } } } ``` -------------------------------- ### Result Method API Source: https://docs.rs/explicon/0.2.0/explicon/type.Result.html Documentation for core Result methods including or, or_else, unwrap_or, unwrap_or_else, and unsafe unchecked methods. ```APIDOC ## pub fn or(self, res: Result) -> Result ### Description Returns `res` if the result is `Err`, otherwise returns the `Ok` value of `self`. ### Parameters - **res** (Result) - Required - The alternative result to return if self is Err. ## pub fn or_else(self, op: O) -> Result ### Description Calls `op` if the result is `Err`, otherwise returns the `Ok` value of `self`. ### Parameters - **op** (FnOnce(E) -> Result) - Required - The closure to execute if self is Err. ## pub fn unwrap_or(self, default: T) -> T ### Description Returns the contained `Ok` value or a provided default. ### Parameters - **default** (T) - Required - The default value to return if self is Err. ## pub fn unwrap_or_else(self, op: F) -> T ### Description Returns the contained `Ok` value or computes it from a closure. ### Parameters - **op** (FnOnce(E) -> T) - Required - The closure to compute the default value. ## pub unsafe fn unwrap_unchecked(self) -> T ### Description Returns the contained `Ok` value, consuming the `self` value, without checking that the value is not an `Err`. ### Safety Calling this method on an `Err` is undefined behavior. ## pub unsafe fn unwrap_err_unchecked(self) -> E ### Description Returns the contained `Err` value, consuming the `self` value, without checking that the value is not an `Ok`. ### Safety Calling this method on an `Ok` is undefined behavior. ``` -------------------------------- ### impl PartialEq for Result Source: https://docs.rs/explicon/0.2.0/explicon/type.Result.html Provides equality comparison functionality for the Result type. ```APIDOC ## fn eq(&self, other: &Result) -> bool ### Description Tests for `self` and `other` values to be equal, and is used by `==`. ### Method `eq` ### Endpoint N/A (Method on `Result`) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) None #### Response Example None ``` ```APIDOC ## fn ne(&self, other: &Rhs) -> bool ### Description Tests for `!=`. ### Method `ne` ### Endpoint N/A (Method on `Result`) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) None #### Response Example None ``` -------------------------------- ### fn serialize Source: https://docs.rs/explicon/0.2.0/explicon/type.Result.html Serializes the Result value into a provided Serde serializer. ```APIDOC ## fn serialize ### Description Serialize this value into the given Serde serializer. ### Parameters #### Request Body - **serializer** (S) - Required - The serializer instance. ### Response #### Success Response (200) - **Result<::Ok, ::Error>** - The result of the serialization process. ``` -------------------------------- ### Convert Result Ok to Option Source: https://docs.rs/explicon/0.2.0/explicon/type.Result.html The `ok` method converts a `Result` into an `Option`, consuming the Result and discarding any error value. ```rust let x: Result = Ok(2); assert_eq!(x.ok(), Some(2)); let x: Result = Err("Nothing here"); assert_eq!(x.ok(), None); ``` -------------------------------- ### fn product Source: https://docs.rs/explicon/0.2.0/explicon/type.Result.html Calculates the product of elements in an iterator of Results, returning the first Err encountered or the product of all Ok values. ```APIDOC ## fn product ### Description Takes each element in the Iterator: if it is an Err, no further elements are taken, and the Err is returned. Should no Err occur, the product of all elements is returned. ### Parameters #### Request Body - **iter** (Iterator>) - Required - The iterator of Result types to process. ### Response #### Success Response (200) - **Result** - The product of all elements or the first encountered error. ``` -------------------------------- ### fn from_iter(iter: I) -> Result Source: https://docs.rs/explicon/0.2.0/explicon/type.Result.html Takes each element in the Iterator. If it is an Err, no further elements are taken, and the Err is returned. Should no Err occur, a container with the values of each Result is returned. ```APIDOC ## fn from_iter(iter: I) -> Result ### Description Takes each element in the `Iterator`: if it is an `Err`, no further elements are taken, and the `Err` is returned. Should no `Err` occur, a container with the values of each `Result` is returned. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```rust let v = vec![1, 2]; let res: Result, &'static str> = v.iter().map(|x: &u32| x.checked_add(1).ok_or("Overflow!")).collect(); assert_eq!(res, Ok(vec![2, 3])); let v = vec![1, 2, 0]; let res: Result, &'static str> = v.iter().map(|x: &u32| x.checked_sub(1).ok_or("Underflow!")).collect(); assert_eq!(res, Err("Underflow!")); let v = vec![3, 2, 1, 10]; let mut shared = 0; let res: Result, &'static str> = v.iter().map(|x: &u32| { shared += x; x.checked_sub(2).ok_or("Underflow!") }).collect(); assert_eq!(res, Err("Underflow!")); assert_eq!(shared, 6); ``` ### Response #### Success Response (200) None #### Response Example None ``` -------------------------------- ### Conversion Traits (From, Into, TryFrom, TryInto) Source: https://docs.rs/explicon/0.2.0/explicon/enum.Sourced.html Standard traits for performing type conversions, including fallible and infallible variants. ```APIDOC ## From ### Method fn from(t: T) -> T ### Description Returns the argument unchanged. ## Into ### Method fn into(self) -> U ### Description Calls U::from(self). This conversion is defined by the implementation of From for U. ## TryFrom ### Method fn try_from(value: U) -> Result>::Error> ### Description Performs a fallible conversion. ### Associated Types - **Error** (Infallible) - The type returned in the event of a conversion error. ## TryInto ### Method fn try_into(self) -> Result>::Error> ### Description Performs a fallible conversion into a target type. ``` -------------------------------- ### And Result Chaining Source: https://docs.rs/explicon/0.2.0/explicon/type.Result.html Returns the provided result if the current result is Ok, otherwise returns the Err. ```rust let x: Result = Ok(2); let y: Result<&str, &str> = Err("late error"); assert_eq!(x.and(y), Err("late error")); let x: Result = Err("early error"); let y: Result<&str, &str> = Ok("foo"); assert_eq!(x.and(y), Err("early error")); let x: Result = Err("not a 2"); let y: Result<&str, &str> = Err("late error"); assert_eq!(x.and(y), Err("not a 2")); let x: Result = Ok(2); let y: Result<&str, &str> = Ok("different result type"); assert_eq!(x.and(y), Ok("different result type")); ``` -------------------------------- ### Result Conversion Methods Source: https://docs.rs/explicon/0.2.0/explicon/type.Result.html Methods for converting Result types into Option types or references. ```APIDOC ## pub fn ok(self) -> Option ### Description Converts from Result to Option, consuming self and discarding the error. ## pub fn err(self) -> Option ### Description Converts from Result to Option, consuming self and discarding the success value. ## pub const fn as_ref(&self) -> Result<&T, &E> ### Description Converts from &Result to Result<&T, &E>. ## pub const fn as_mut(&mut self) -> Result<&mut T, &mut E> ### Description Converts from &mut Result to Result<&mut T, &mut E>. ``` -------------------------------- ### Expect Error Source: https://docs.rs/explicon/0.2.0/explicon/type.Result.html Returns the Err value or panics if the result is an Ok. ```rust let x: Result = Ok(10); x.expect_err("Testing expect_err"); // panics with `Testing expect_err: 10` ``` -------------------------------- ### Resolution Methods (FromStr) Source: https://docs.rs/explicon/0.2.0/explicon/enum.Sourced.html Methods for resolving values when the target type implements FromStr. ```APIDOC ## resolve() ### Description Resolves the configuration value by parsing if sourced from an environment variable. ### Returns - **Ok(T)** - The direct value or the parsed environment variable value. ### Errors - **ExpliconError::Var** - If environment variable lookup fails. - **ExpliconError::Other** - If environment variable value parsing fails. ``` -------------------------------- ### Resolve from string and validate implementation Source: https://docs.rs/explicon/0.2.0/src/explicon/lib.rs.html Method to resolve a value from a string source and apply a custom validation function. ```rust pub fn resolve_from_string_and_validate(&self, validator: F) -> Result where F: FnOnce(&T) -> bool, { let value = self.resolve_from_string()?; if validator(&value) { Ok(value) } else { Err(ExpliconError::Other("Validation failed".into())) } } } ``` -------------------------------- ### Result::unwrap Source: https://docs.rs/explicon/0.2.0/explicon/type.Result.html Returns the contained Ok value, consuming the self value. Panics if the value is an Err. ```APIDOC ## pub fn unwrap(self) -> T where E: Debug ### Description Returns the contained `Ok` value, consuming the `self` value. Because this function may panic, its use is generally discouraged. Panics are meant for unrecoverable errors, and may abort the entire program. Instead, prefer to use the `?` (try) operator, or pattern matching to handle the `Err` case explicitly, or call `unwrap_or`, `unwrap_or_else`, or `unwrap_or_default`. ### Method `unwrap` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) None #### Response Example None ### Panics Panics if the value is an `Err`. ``` -------------------------------- ### Convert Result<&mut T, &mut E> using DerefMut Source: https://docs.rs/explicon/0.2.0/explicon/type.Result.html Use `as_deref_mut` to convert a `Result` to `Result<&mut ::Target, &mut E>` by applying `DerefMut` to the `Ok` variant. This provides mutable references. ```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); ``` -------------------------------- ### impl PartialOrd for Result Source: https://docs.rs/explicon/0.2.0/explicon/type.Result.html Provides partial ordering functionality for the Result type. ```APIDOC ## fn partial_cmp(&self, other: &Result) -> Option ### Description This method returns an ordering between `self` and `other` values if one exists. ### Method `partial_cmp` ### Endpoint N/A (Method on `Result`) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) None #### Response Example None ``` ```APIDOC ## fn lt(&self, other: &Rhs) -> bool ### Description Tests less than (for `self` and `other`) and is used by the `<` operator. ### Method `lt` ### Endpoint N/A (Method on `Result`) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) None #### Response Example None ``` ```APIDOC ## fn le(&self, other: &Rhs) -> bool ### Description Tests less than or equal to (for `self` and `other`) and is used by the `<=` operator. ### Method `le` ### Endpoint N/A (Method on `Result`) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) None #### Response Example None ``` ```APIDOC ## fn gt(&self, other: &Rhs) -> bool ### Description Tests greater than (for `self` and `other`) and is used by the `>` operator. ### Method `gt` ### Endpoint N/A (Method on `Result`) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) None #### Response Example None ``` ```APIDOC ## fn ge(&self, other: &Rhs) -> bool ### Description Tests greater than or equal to (for `self` and `other`) and is used by the `>=` operator. ### Method `ge` ### Endpoint N/A (Method on `Result`) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) None #### Response Example None ``` -------------------------------- ### Sourced Configuration Value Source: https://docs.rs/explicon/0.2.0/src/explicon/lib.rs.html Defines a configuration value that can be sourced either directly or from an environment variable, with methods for resolving these values. ```APIDOC ## Struct Sourced ### Description A configuration value that can be sourced either directly or from an environment variable. Supports deserialization from both formats: - Direct value representation (e.g., `42` or `"direct_value"`) - Environment variable reference (e.g., `{ "env": "VAR_NAME" }`) ### Fields - **Env** (String) - Value should be read from the specified environment variable. - **Value** (T) - Directly provided value that doesn't require resolution. ## Impl Sourced ### Method resolve(&self) -> Result #### Description Resolves the configuration value by parsing if sourced from an environment variable. Use this method when the target type `T` implements [`FromStr`] (e.g., numbers, booleans). #### Returns - `Ok(T)` with direct value if using [`Sourced::Value`] - `Ok(T)` with **parsed** environment variable value if using [`Sourced::Env`] #### Errors - [`ExpliconError::Var`] if environment variable lookup fails - [`ExpliconError::Other`] if environment variable value parsing fails (via [`FromStr`]) ### Method resolve_or_default(&self) -> Result #### Description Resolves the value using `resolve()` or returns type's default if resolution fails. #### Type Constraints - `T: Default` #### Returns - `Result` ### Method resolve_or(&self, fallback: T) -> T #### Description Resolves the value using `resolve()` or returns the provided fallback value if resolution fails. #### Parameters - **fallback** (T) - The value to return if resolution fails. #### Returns - `T` ### Method resolve_and_validate(&self, validator: F) -> Result #### Description Resolves the value using `resolve()` and validates it against a predicate. #### Parameters - **validator** (F) - A closure that takes a reference to the resolved value and returns `true` if valid, `false` otherwise. #### Returns - `Result` #### Errors - [`ExpliconError::Other`] if validation fails. ## Impl Sourced ### Method resolve_from_string(&self) -> Result #### Description Resolves the configuration value by converting directly from the environment variable string. Use this method when the target type `T` implements [`From`] but not necessarily [`FromStr`] (e.g., [`secrecy::SecretString`]). #### Returns - `Ok(T)` with direct value if using [`Sourced::Value`] - `Ok(T)` with value created **directly via `From`** from the environment variable if using [`Sourced::Env`] #### Errors - [`ExpliconError::Var`] if environment variable lookup fails. Conversion via `From` is assumed infallible. ### Method resolve_from_string_or(&self, fallback: T) -> T #### Description Resolves the value using `resolve_from_string()` or returns the provided fallback value. Note: Does not return default, as `From` types might not have a meaningful default. #### Parameters - **fallback** (T) - The value to return if resolution fails. #### Returns - `T` ### Method resolve_from_string_and_validate(&self, validator: F) -> Result #### Description Resolves the value using `resolve_from_string()` and validates it against a predicate. #### Parameters - **validator** (F) - A closure that takes a reference to the resolved value and returns `true` if valid, `false` otherwise. #### Returns - `Result` #### Errors - [`ExpliconError::Other`] if validation fails. ``` -------------------------------- ### Serialize Implementation for Sourced Source: https://docs.rs/explicon/0.2.0/explicon/enum.Sourced.html Enables serialization of the `Sourced` enum to a Serde serializer. Requires `T` to implement `Serialize`. ```rust fn serialize<__S>(&self, __serializer: __S) -> Result<__S::Ok, __S::Error> where __S: Serializer, ``` -------------------------------- ### Into Ok Infallible Source: https://docs.rs/explicon/0.2.0/explicon/type.Result.html Returns the Ok value without risk of panicking, useful for compile-time safety. ```rust fn only_good_news() -> Result { Ok("this is fine".into()) } let s: String = only_good_news().into_ok(); println!("{s}"); ``` -------------------------------- ### Resolve Sourced Value or Fallback (FromStr) Source: https://docs.rs/explicon/0.2.0/explicon/enum.Sourced.html Resolves the value using `resolve()` or returns the provided fallback value if resolution fails. ```rust pub fn resolve_or(&self, fallback: T) -> T ``` -------------------------------- ### Using `or` to Provide an Alternative Result Source: https://docs.rs/explicon/0.2.0/explicon/type.Result.html The `or` method returns the `Ok` value of `self` if it is `Ok`, otherwise it returns the provided `res` argument. Arguments are eagerly evaluated. ```rust let x: Result = Ok(2); let y: Result = Err("late error"); assert_eq!(x.or(y), Ok(2)); let x: Result = Err("early error"); let y: Result = Ok(2); assert_eq!(x.or(y), Ok(2)); let x: Result = Err("not a 2"); let y: Result = Err("late error"); assert_eq!(x.or(y), Err("late error")); let x: Result = Ok(2); let y: Result = Ok(100); assert_eq!(x.or(y), Ok(2)); ``` -------------------------------- ### Resolution Methods (From) Source: https://docs.rs/explicon/0.2.0/explicon/enum.Sourced.html Methods for resolving values when the target type implements From. ```APIDOC ## resolve_from_string() ### Description Resolves the configuration value by converting directly from the environment variable string. ### Returns - **Ok(T)** - The direct value or the value created via From from the environment variable. ### Errors - **ExpliconError::Var** - If environment variable lookup fails. ``` -------------------------------- ### Expect Ok Value or Panic Source: https://docs.rs/explicon/0.2.0/explicon/type.Result.html The `expect` method returns the contained Ok value or panics if the value is Err. The panic message includes a custom message and the error's content. Use with caution, as panics can abort the program. ```rust let x: Result = Err("emergency failure"); x.expect("Testing expect"); // panics with `Testing expect: emergency failure` ``` ```rust let path = std::env::var("IMPORTANT_PATH") .expect("env variable `IMPORTANT_PATH` should be set by `wrapper_script.sh`"); ``` -------------------------------- ### Resolve Sourced Value or Fallback (From) Source: https://docs.rs/explicon/0.2.0/explicon/enum.Sourced.html Resolves the value using `resolve_from_string()` or returns the provided fallback value. This method does not return a default as `From` types might not have a meaningful default. ```rust pub fn resolve_from_string_or(&self, fallback: T) -> T ``` -------------------------------- ### Collect Results with Error Handling Source: https://docs.rs/explicon/0.2.0/explicon/type.Result.html Demonstrates collecting results from an iterator where an error condition (underflow) can occur. The first encountered error stops the collection and is returned. ```rust let v = vec![1, 2, 0]; let res: Result, &'static str> = v.iter().map(|x: &u32| x.checked_sub(1).ok_or("Underflow!") ).collect(); assert_eq!(res, Err("Underflow!")); ``` -------------------------------- ### Resolve and Validate Sourced Value (FromStr) Source: https://docs.rs/explicon/0.2.0/explicon/enum.Sourced.html Resolves the value using `resolve()` and validates it against a predicate. The predicate `F` must be a closure that takes a reference to `T` and returns a boolean. ```rust pub fn resolve_and_validate(&self, validator: F) -> Result where F: FnOnce(&T) -> bool, ``` -------------------------------- ### Unwrap Error Source: https://docs.rs/explicon/0.2.0/explicon/type.Result.html Returns the Err value or panics if the result is an Ok. ```rust let x: Result = Ok(2); x.unwrap_err(); // panics with `2` ``` ```rust let x: Result = Err("emergency failure"); assert_eq!(x.unwrap_err(), "emergency failure"); ``` -------------------------------- ### Unwrap Ok Value or Panic Source: https://docs.rs/explicon/0.2.0/explicon/type.Result.html The `unwrap` method returns the contained Ok value, consuming the Result. It panics if the value is Err. This method is generally discouraged in favor of safer error handling methods like `?` or pattern matching. ```rust let x: Result = Ok(7); assert_eq!(x.unwrap(), 7); ``` -------------------------------- ### Result::as_deref_mut Source: https://docs.rs/explicon/0.2.0/explicon/type.Result.html Converts from Result to Result<&mut ::Target, &mut E> by coercing the Ok variant via DerefMut. ```APIDOC ## pub fn as_deref_mut(&mut self) -> Result<&mut ::Target, &mut E> where T: DerefMut ### Description Converts from `Result` (or `&mut Result`) to `Result<&mut ::Target, &mut E>`. Coerces the `Ok` variant of the original `Result` via `DerefMut` and returns the new `Result`. ### Method `as_deref_mut` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```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); ``` ### Response #### Success Response (200) None #### Response Example None ``` -------------------------------- ### impl FromResidual> for Result Source: https://docs.rs/explicon/0.2.0/explicon/type.Result.html Constructs the type from a compatible Residual type. ```APIDOC ## fn from_residual(_: Yeet) -> Result ### Description Constructs the type from a compatible `Residual` type. ### Method `from_residual` ### Endpoint N/A (Associated function) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) None #### Response Example None ``` -------------------------------- ### impl Ord for Result Source: https://docs.rs/explicon/0.2.0/explicon/type.Result.html Provides ordering functionality for the Result type. ```APIDOC ## fn cmp(&self, other: &Result) -> Ordering ### Description This method returns an `Ordering` between `self` and `other`. ### Method `cmp` ### Endpoint N/A (Method on `Result`) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) None #### Response Example None ``` ```APIDOC ## fn max(self, other: Self) -> Self ### Description Compares and returns the maximum of two values. ### Method `max` ### Endpoint N/A (Method on `Result`) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) None #### Response Example None ``` ```APIDOC ## fn min(self, other: Self) -> Self ### Description Compares and returns the minimum of two values. ### Method `min` ### Endpoint N/A (Method on `Result`) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) None #### Response Example None ``` ```APIDOC ## fn clamp(self, min: Self, max: Self) -> Self ### Description Restrict a value to a certain interval. ### Method `clamp` ### Endpoint N/A (Method on `Result`) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) None #### Response Example None ``` -------------------------------- ### Result::expect Source: https://docs.rs/explicon/0.2.0/explicon/type.Result.html Returns the contained Ok value, consuming the self value. Panics if the value is an Err. ```APIDOC ## pub fn expect(self, msg: &str) -> T where E: Debug ### Description Returns the contained `Ok` value, consuming the `self` value. Because this function may panic, its use is generally discouraged. Instead, prefer to use pattern matching and handle the `Err` case explicitly, or call `unwrap_or`, `unwrap_or_else`, or `unwrap_or_default`. ### Method `expect` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```rust let x: Result = Err("emergency failure"); x.expect("Testing expect"); // panics with `Testing expect: emergency failure` ``` ### Response #### Success Response (200) None #### Response Example None ### Panics Panics if the value is an `Err`, with a panic message including the passed message, and the content of the `Err`. ``` -------------------------------- ### Resolve Sourced Value or Default (FromStr) Source: https://docs.rs/explicon/0.2.0/explicon/enum.Sourced.html Resolves the value using `resolve()` or returns the type's default if resolution fails. Requires `T` to implement `Default`. ```rust pub fn resolve_or_default(&self) -> Result ``` -------------------------------- ### impl Hash for Result Source: https://docs.rs/explicon/0.2.0/explicon/type.Result.html Provides hashing functionality for the Result type. ```APIDOC ## fn hash<__H>(&self, state: &mut __H) where __H: Hasher ### Description Feeds this value into the given `Hasher`. ### Method `hash` ### Endpoint N/A (Method on `Result`) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) None #### Response Example None ``` ```APIDOC ## fn hash_slice(data: &[Self], state: &mut H) where H: Hasher ### Description Feeds a slice of this type into the given `Hasher`. ### Method `hash_slice` ### Endpoint N/A (Associated function) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) None #### Response Example None ``` -------------------------------- ### Clone Implementation for Sourced Source: https://docs.rs/explicon/0.2.0/explicon/enum.Sourced.html Provides a `clone` method for the `Sourced` enum, allowing for duplication of its values. Requires `T` to implement `Clone`. ```rust fn clone(&self) -> Sourced ``` -------------------------------- ### Transpose Result, E> to Option> Source: https://docs.rs/explicon/0.2.0/explicon/type.Result.html Transposes a Result containing an Option into an Option containing a Result. Ok(None) becomes None, while Ok(Some(_)) and Err(_) are wrapped in Some. ```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); ``` -------------------------------- ### Resolve Sourced Value (FromStr) Source: https://docs.rs/explicon/0.2.0/explicon/enum.Sourced.html Resolves the configuration value by parsing if sourced from an environment variable. Use when the target type `T` implements `FromStr`. Errors can occur if environment variable lookup fails or parsing fails. ```rust pub fn resolve(&self) -> Result ``` -------------------------------- ### Sourced resolution unit tests Source: https://docs.rs/explicon/0.2.0/src/explicon/lib.rs.html Unit tests covering resolution of values, environment variables, default values, and validation logic. ```rust #[cfg(test)] mod tests { use super::*; #[test] fn resolve_value() { let sourced = Sourced::Value(42); assert_eq!(sourced.resolve().unwrap(), 42); } #[test] fn resolve_env_success() { let var_name = "TEST_RESOLVE_ENV_SUCCESS"; let expected_value = 123; unsafe { std::env::set_var(var_name, expected_value.to_string()) }; let sourced = Sourced::::Env(var_name.to_string()); let result = sourced.resolve().unwrap(); assert_eq!(result, expected_value); unsafe { std::env::remove_var(var_name) }; } #[test] fn resolve_env_var_not_found() { let var_name = "NON_EXISTENT_VAR_XYZ123"; unsafe { std::env::remove_var(var_name) }; let sourced = Sourced::::Env(var_name.to_string()); let result = sourced.resolve(); assert!(matches!(result, Err(ExpliconError::Var(_)))); } #[test] fn resolve_env_var_invalid_parse() { let var_name = "TEST_INVALID_PARSE"; unsafe { std::env::set_var(var_name, "abc") }; let sourced = Sourced::::Env(var_name.to_string()); let result = sourced.resolve(); assert!(matches!(result, Err(ExpliconError::Other(_)))); unsafe { std::env::remove_var(var_name) }; } #[test] fn resolve_or_default_env_missing() { let var_name = "NON_EXISTENT_VAR_FOR_DEFAULT"; unsafe { std::env::remove_var(var_name) }; let sourced = Sourced::::Env(var_name.to_string()); let result = sourced.resolve_or_default().unwrap(); assert_eq!(result, i32::default()); } #[test] fn resolve_or_default_parse_error() { let var_name = "TEST_PARSE_ERROR_DEFAULT"; unsafe { std::env::set_var(var_name, "abc") }; let sourced = Sourced::::Env(var_name.to_string()); let result = sourced.resolve_or_default().unwrap(); assert_eq!(result, i32::default()); unsafe { std::env::remove_var(var_name) }; } #[test] fn resolve_or_default_success() { let var_name = "TEST_RESOLVE_OR_DEFAULT_SUCCESS"; unsafe { std::env::set_var(var_name, "5") }; let sourced = Sourced::::Env(var_name.to_string()); let result = sourced.resolve_or_default().unwrap(); assert_eq!(result, 5); unsafe { std::env::remove_var(var_name) }; } #[test] fn resolve_and_validate_success() { let sourced = Sourced::Value(5); let result = sourced.resolve_and_validate(|v| *v == 5).unwrap(); assert_eq!(result, 5); } #[test] fn resolve_and_validate_failure() { let sourced = Sourced::Value(5); let result = sourced.resolve_and_validate(|v| *v == 10); assert!(matches!(result, Err(ExpliconError::Other(_)))); } #[test] fn resolve_and_validate_env_missing() { let var_name = "NON_EXISTENT_VAR_FOR_VALIDATE"; unsafe { std::env::remove_var(var_name) }; let sourced = Sourced::::Env(var_name.to_string()); let result = sourced.resolve_and_validate(|_| true); assert!(matches!(result, Err(ExpliconError::Var(_)))); } #[test] fn resolve_and_validate_env_invalid() { let var_name = "TEST_VALIDATE_ENV_INVALID"; unsafe { std::env::set_var(var_name, "10") }; let sourced = Sourced::::Env(var_name.to_string()); let result = sourced.resolve_and_validate(|v| *v == 5); assert!(matches!(result, Err(ExpliconError::Other(_)))); unsafe { std::env::remove_var(var_name) }; } #[test] fn resolve_env_string() { let var_name = "TEST_ENV_STRING"; let expected = "hello"; unsafe { std::env::set_var(var_name, expected) }; let sourced = Sourced::::Env(var_name.to_string()); let result = sourced.resolve().unwrap(); assert_eq!(result, expected); unsafe { std::env::remove_var(var_name) }; } #[test] fn resolve_env_bool() { let var_name = "TEST_ENV_BOOL"; unsafe { std::env::set_var(var_name, "true") }; let sourced = Sourced::::Env(var_name.to_string()); let result = sourced.resolve().unwrap(); ``` -------------------------------- ### Convert Result<&T, &E> using Deref Source: https://docs.rs/explicon/0.2.0/explicon/type.Result.html The `as_deref` method converts a `Result` to `Result<&::Target, &E>` by applying `Deref` to the `Ok` variant. It returns references to the contained values. ```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); ``` -------------------------------- ### Computing a Default Value with `unwrap_or_else` Source: https://docs.rs/explicon/0.2.0/explicon/type.Result.html The `unwrap_or_else` method returns the contained `Ok` value or computes a default value using a closure if the `Result` is `Err`. This is useful when the default value is expensive to compute. ```rust fn count(x: &str) -> usize { x.len() } assert_eq!(Ok(2).unwrap_or_else(count), 2); assert_eq!(Err("foo").unwrap_or_else(count), 3); ``` -------------------------------- ### Resolve and Validate Sourced Value (From) Source: https://docs.rs/explicon/0.2.0/explicon/enum.Sourced.html Resolves the value using `resolve_from_string()` and validates it against a predicate. The predicate `F` must be a closure that takes a reference to `T` and returns a boolean. ```rust pub fn resolve_from_string_and_validate(&self, validator: F) -> Result where F: FnOnce(&T) -> bool, ``` -------------------------------- ### Map Result to Default Value Source: https://docs.rs/explicon/0.2.0/explicon/type.Result.html The `map_or_default` method (experimental) applies a function to the `Ok` value or returns the default value of the target type if the `Result` is `Err`. ```rust #![feature(result_option_map_or_default)] 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); ``` -------------------------------- ### Convert Result to Iterator (Ok Case) Source: https://docs.rs/explicon/0.2.0/explicon/type.Result.html Converts a `Result::Ok` value into an iterator. The iterator will yield the contained value exactly once. ```rust let x: Result = Ok(5); let v: Vec = x.into_iter().collect(); assert_eq!(v, [5]); ```