### Example of anyhow::Result in main Source: https://docs.rs/anyhow/latest/anyhow/type.Result.html This example shows how anyhow::Result can be used in the main function. Failures will be printed with context and a backtrace if captured. ```rust use anyhow::Result; fn main() -> Result<()> { let config = std::fs::read_to_string("cluster.json")?; let map: ClusterMap = serde_json::from_str(&config)?; println!("cluster info: {:#?}", map); Ok(()) } ``` -------------------------------- ### Example Usage of anyhow::Result Source: https://docs.rs/anyhow/latest/src/anyhow/lib.rs.html An example demonstrating how `anyhow::Result` can be used in a function that might return a deserialized JSON value or an I/O error. ```rust # pub trait Deserialize {} # # mod serde_json { # use super::Deserialize; # use std::io; # # pub fn from_str(json: &str) -> io::Result { # unimplemented!() # } # } # # #[derive(Debug)] # struct ClusterMap; # # impl Deserialize for ClusterMap {} # use anyhow::Result; ``` -------------------------------- ### Example Usage Source: https://docs.rs/anyhow/latest/anyhow/struct.Chain.html Demonstrates how to use the `chain` iterator to find a specific underlying error type. ```APIDOC ## §Example ```rust use anyhow::Error; use std::io; pub fn underlying_io_error_kind(error: &Error) -> Option { for cause in error.chain() { if let Some(io_error) = cause.downcast_ref::() { return Some(io_error.kind()); } } None } ``` ``` -------------------------------- ### Example of Adding Context to a Parse Error Source: https://docs.rs/anyhow/latest/src/anyhow/error.rs.html Demonstrates how to use anyhow::Error::context to add specific information to a custom error type during error propagation. This example shows how to include the line number and file path in the error context. ```rust pub fn parse(path: impl AsRef) -> Result { let file = File::open(&path)?; parse_impl(file).map_err(|error| { let context = format!( "only the first {} lines of {} are valid", error.line, path.as_ref().display(), ); anyhow::Error::new(error).context(context) }) } ``` -------------------------------- ### Example Usage of Context Source: https://docs.rs/anyhow/latest/src/anyhow/context.rs.html Demonstrates how to use the `context` method on an `Option` to provide an error message if the option is `None`. This is a common pattern for handling potentially missing values. ```rust # type T = (); # use anyhow::{Context, Result}; fn maybe_get() -> Option { # const IGNORE: &str = stringify! { ... # }; # unimplemented!() } fn demo() -> Result<()> { let t = maybe_get().context("there is no T")?; # const IGNORE: &str = stringify! { ... # }; # unimplemented!() } ``` -------------------------------- ### Example Usage of Context Source: https://docs.rs/anyhow/latest/anyhow/trait.Context.html Demonstrates how to use the `context` and `with_context` methods to add human-readable context to errors, improving debugging by providing more information about the error's origin and circumstances. ```APIDOC ## Example ```rust use anyhow::{Context, Result}; use std::fs; use std::path::PathBuf; pub struct ImportantThing { path: PathBuf, } impl ImportantThing { pub fn detach(&mut self) -> Result<()> { /* ... */ } } pub fn do_it(mut it: ImportantThing) -> Result> { it.detach().context("Failed to detach the important thing")?; let path = &it.path; let content = fs::read(path) .with_context(|| format!("Failed to read instrs from {}", path.display()))?; Ok(content) } ``` When printed, the outermost context would be printed first and the lower level underlying causes would be enumerated below. ``` Error: Failed to read instrs from ./path/to/instrs.json Caused by: No such file or directory (os error 2) ``` ``` -------------------------------- ### Chain::new Source: https://docs.rs/anyhow/latest/anyhow/struct.Chain.html Constructs a new Chain iterator starting with the given head error. ```APIDOC ## pub fn new(head: &'a (dyn StdError + 'static)) -> Self Constructs a new Chain iterator starting with the given head error. ``` -------------------------------- ### Type Inference Error Example Source: https://docs.rs/anyhow/latest/anyhow/fn.Ok.html This example demonstrates a scenario where type annotations are needed because the compiler cannot infer the error type `E` for `std::result::Result` when using `anyhow::Result::Ok` directly. ```rust error[E0282]: type annotations needed for `std::result::Result` --> src/main.rs:11:13 | 11 | let _ = anyhow::Result::Ok(1); | - ^^^^^^^^^^^^^^^^^^ cannot infer type for type parameter `E` declared on the enum `Result` | | | consider giving this pattern the explicit type `std::result::Result`, where the type parameter `E` is specified ``` -------------------------------- ### Chain::new Source: https://docs.rs/anyhow/latest/src/anyhow/chain.rs.html Constructs a new Chain starting with the given head error. This is the entry point for iterating over an error's source chain. ```APIDOC ## Chain::new ### Description Constructs a new `Chain` starting with the given head error. ### Method `new` ### Parameters #### Path Parameters - **head** (`&'a (dyn StdError + 'static)`) - Required - The starting error in the chain. ``` -------------------------------- ### Example: Using Error::msg in Stream Combinators Source: https://docs.rs/anyhow/latest/src/anyhow/error.rs.html Demonstrates how `Error::msg` can be used with stream combinators to convert errors from operations within the stream into anyhow::Error objects. ```rust async fn demo(stream: S) -> Result> where S: Stream, { stream .then(ffi::do_some_work) // returns Result .map_err(Error::msg) .try_collect() .await } ``` -------------------------------- ### Handling File Metadata with Result Source: https://docs.rs/anyhow/latest/anyhow/type.Result.html Demonstrates using `and_then` to chain fallible operations like getting file metadata and its modification time. Errors are checked using `is_ok` and `is_err`. ```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); ``` -------------------------------- ### Adding Context to Results Source: https://docs.rs/anyhow/latest/anyhow/trait.Context.html Demonstrates how to use the `context` and `with_context` methods to add human-readable context to errors. The `context` method adds immediate context, while `with_context` evaluates the context lazily. This example also shows how context is displayed when an error is printed. ```rust use anyhow::{Context, Result}; use std::fs; use std::path::PathBuf; pub struct ImportantThing { path: PathBuf, } impl ImportantThing { pub fn detach(&mut self) -> Result<()> {...} } pub fn do_it(mut it: ImportantThing) -> Result> { it.detach().context("Failed to detach the important thing")?; let path = &it.path; let content = fs::read(path) .with_context(|| format!("Failed to read instrs from {}", path.display()))?; Ok(content) } ``` ```text Error: Failed to read instrs from ./path/to/instrs.json Caused by: No such file or directory (os error 2) ``` -------------------------------- ### Custom Error Rendering Source: https://docs.rs/anyhow/latest/anyhow/struct.Error.html This example shows how to manually render an error and its cause chain if the built-in representations are not sufficient. It iterates through the error chain using `err.chain()`. ```rust use anyhow::{Context, Result}; fn main() { if let Err(err) = try_main() { eprintln!("ERROR: {}", err); err.chain().skip(1).for_each(|cause| eprintln!("because: {}", cause)); std::process::exit(1); } } fn try_main() -> Result<()> { ... } ``` -------------------------------- ### Constructing an Error from a Boxed Error Source: https://docs.rs/anyhow/latest/src/anyhow/error.rs.html This function constructs an `anyhow::Error` from a boxed standard library error that is `Send + Sync`. It handles the necessary vtable setup for the boxed error. ```APIDOC ## `construct_from_boxed` ### Description Constructs an `anyhow::Error` from a `Box`. ### Method `pub(crate) fn construct_from_boxed(error: Box, backtrace: Option) -> Self` ### Parameters - `error` (Box): The boxed error to wrap. - `backtrace` (Option): An optional backtrace to associate with the error. ### Safety This function is unsafe because the provided vtable must operate correctly on the boxed error type. ``` -------------------------------- ### Parse Type Path with Identifier Source: https://docs.rs/anyhow/latest/src/anyhow/ensure.rs.html Handles parsing of type paths that start with an identifier. This is a common case for simple type names. ```rust (type $stack:tt $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($ident:tt $($dup:tt)*) $i:ident $($rest:tt)*) => { $crate::__parse_ensure!(tpath $stack $bail ($($fuel)*) {($($buf)* $ident) $($parse)*} ($($rest)*) $($rest)*) } ``` -------------------------------- ### Error Handling in Stream Processing Source: https://docs.rs/anyhow/latest/anyhow/struct.Error.html This example demonstrates using `Error::msg` to convert errors from a stream's item processing into `anyhow::Error`. It's suitable for iterator or stream combinators. ```rust use anyhow::{Error, Result}; use futures::stream::{Stream, StreamExt, TryStreamExt}; async fn demo(stream: S) -> Result> where S: Stream, { stream .then(ffi::do_some_work) // returns Result .map_err(Error::msg) .try_collect() .await } ``` -------------------------------- ### Getting Backtrace Reference Source: https://docs.rs/anyhow/latest/src/anyhow/error.rs.html Unsafely retrieves a reference to the `Backtrace` from an `ErrorImpl`. This function is compiled only when the `std` feature is enabled and attempts to get the backtrace, falling back to `None` if not available. ```rust #[cfg(feature = "std")] pub(crate) unsafe fn backtrace(this: Ref) -> &Backtrace { // This unwrap can only panic if the underlying error's backtrace method // is nondeterministic, which would only happen in maliciously // constructed code. unsafe { this.deref() } .backtrace .as_ref() .or_else(|| { ``` -------------------------------- ### Using Context on Option Source: https://docs.rs/anyhow/latest/anyhow/trait.Context.html Demonstrates how to use the `context` method on an `Option` to convert `None` into an `anyhow::Result` with a specific error message. ```rust use anyhow::{Context, Result}; fn maybe_get() -> Option { ... } fn demo() -> Result<()> { let t = maybe_get().context("there is no T")?; ... } ``` -------------------------------- ### Basic anyhow Usage Source: https://docs.rs/anyhow/latest/src/anyhow/fmt.rs.html Demonstrates the basic usage of the anyhow crate for error handling. This snippet shows how to create and return an anyhow::Error. ```rust use anyhow::{Context, Result}; fn might_fail() -> Result { Ok(5) } fn main() { match might_fail() { Ok(value) => println!("Success: {}", value), Err(e) => println!("Error: {:?}", e), } } ``` -------------------------------- ### into_ok Source: https://docs.rs/anyhow/latest/anyhow/type.Result.html Returns the contained Ok value, but never panics. This is a nightly-only experimental API. ```APIDOC ## into_ok ### Description Returns the contained `Ok` value, but never panics. This method is known to never panic on the result types it is implemented for. ### Method `pub const fn into_ok(self) -> T` ### Constraints `where E: Into` ### Notes This is a nightly-only experimental API. ### Examples ``` fn only_good_news() -> Result { Ok("this is fine".into()) } let s: String = only_good_news().into_ok(); println!("{s}"); ``` ``` -------------------------------- ### AsRef for Error Source: https://docs.rs/anyhow/latest/src/anyhow/error.rs.html Implements AsRef to get a reference to a dynamic standard error. ```rust impl AsRef for Error { fn as_ref(&self) -> &(dyn StdError + 'static) { &**self } } ``` -------------------------------- ### AsRef Implementations for StdError Source: https://docs.rs/anyhow/latest/src/anyhow/error.rs.html Provides `AsRef` implementations to get references to dynamic `StdError` types from `Error`. ```APIDOC ## `AsRef` for `Error` ### Description Allows getting a reference to `dyn StdError + Send + Sync` from an `Error`. ### Implementation `impl AsRef for Error` ``` ```APIDOC ## `AsRef` for `Error` ### Description Allows getting a reference to `dyn StdError` from an `Error`. ### Implementation `impl AsRef for Error` ``` -------------------------------- ### Formatting Errors with `Debug` and `Display` Source: https://docs.rs/anyhow/latest/src/anyhow/fmt.rs.html Explains how anyhow uses the `Debug` and `Display` traits for error formatting. The `{:?}` format specifier typically shows the full error chain with context, while `{}` shows the primary error message. ```rust use anyhow::{Context, Result}; fn inner_function() -> Result<()> { Err(anyhow::anyhow!("Inner error details")).context("Error in inner function") } fn outer_function() -> Result<()> { inner_function().context("Error in outer function") } fn main() { match outer_function() { Ok(_) => println!("Operation successful."), Err(e) => { println!("Display format: {}", e); // Uses Display trait println!("Debug format: {:?}", e); // Uses Debug trait, shows chain } } } ``` -------------------------------- ### No-std Support Configuration Source: https://docs.rs/anyhow/latest/anyhow/index.html To use `anyhow` in a no-std environment, disable the default 'std' feature in your `Cargo.toml` and ensure a global allocator is available. This configuration is necessary for embedded or minimal environments. ```toml [dependencies] anyhow = { version = "1.0", default-features = false } ``` -------------------------------- ### chain Source: https://docs.rs/anyhow/latest/anyhow/struct.Error.html Provides an iterator over the chain of source errors contained within this Error object, starting from the immediate source. ```APIDOC ## chain(&self) -> Chain<'_> ### Description An iterator of the chain of source errors contained by this Error. This iterator will visit every error in the cause chain of this error object, beginning with the error that this error object was created from. ``` -------------------------------- ### Error Reporting with `anyhow::Error` Source: https://docs.rs/anyhow/latest/src/anyhow/fmt.rs.html Illustrates how `anyhow::Error` provides a rich debugging output when formatted with `{:?}`, including the error chain and context added via `.context()`. ```rust use anyhow::{Context, Result}; fn step_three() -> Result<()> { Err(anyhow::anyhow!("Failed at the final step")).context("Step 3") } fn step_two() -> Result<()> { step_three().context("Step 2") } fn step_one() -> Result<()> { step_two().context("Step 1") } fn main() { match step_one() { Ok(_) => println!("Success!"), Err(e) => println!("Full error report:\n{:?}", e), } } ``` -------------------------------- ### Get Backtrace Source: https://docs.rs/anyhow/latest/src/anyhow/error.rs.html Retrieves the backtrace for the current error. Requires specific environment variables to be set for backtraces to be captured and meaningful. ```APIDOC ## backtrace ### Description Get the backtrace for this Error. In order for the backtrace to be meaningful, one of the two environment variables `RUST_LIB_BACKTRACE=1` or `RUST_BACKTRACE=1` must be defined and `RUST_LIB_BACKTRACE` must not be `0`. Backtraces are somewhat expensive to capture in Rust, so we don't necessarily want to be capturing them all over the place all the time. - If you want panics and errors to both have backtraces, set `RUST_BACKTRACE=1`; - If you want only errors to have backtraces, set `RUST_LIB_BACKTRACE=1`; - If you want only panics to have backtraces, set `RUST_BACKTRACE=1` and `RUST_LIB_BACKTRACE=0`. ### Stability Standard library backtraces are only available when using Rust ≥ 1.65. On older compilers, this function is only available if the crate's "backtrace" feature is enabled, and will use the `backtrace` crate as the underlying backtrace implementation. The return type of this function on old compilers is `&(impl Debug + Display)`. ```toml [dependencies] anyhow = { version = "1.0", features = ["backtrace"] } ``` ### Method `pub fn backtrace(&self) -> &Backtrace` ``` -------------------------------- ### Parse Ensure Macro: Epath with Identifier Source: https://docs.rs/anyhow/latest/src/anyhow/ensure.rs.html Handles parsing of path expressions starting with an identifier within the `__parse_ensure!` macro. ```rust $crate::__parse_ensure!(epath (atom $stack) $bail ($($fuel)*) {($($buf)* $ident) $($parse)*} ($($rest)*) $($rest)*); ``` -------------------------------- ### anyhow::Result Usage Source: https://docs.rs/anyhow/latest/anyhow/type.Result.html Demonstrates how to use anyhow::Result as a return type for functions, simplifying error propagation. ```APIDOC ## anyhow::Result ### Description `anyhow::Result` is a convenient return type for applications. When used as the return type for `fn main`, failures are printed along with context and a backtrace if captured. `anyhow::Result` can be used with one or two type parameters: ### Method Type Alias ### Usage Examples ```rust use anyhow::Result; // Equivalent to std::result::Result fn demo1() -> Result { ... } // Equivalent to std::result::Result fn demo2() -> Result { ... } ``` ### Example ```rust use anyhow::Result; fn main() -> Result<()> { let config = std::fs::read_to_string("cluster.json")?; let map: ClusterMap = serde_json::from_str(&config)?; println!("cluster info: {:#?}", map); Ok(()) } ``` ``` -------------------------------- ### AsRef for Error Source: https://docs.rs/anyhow/latest/src/anyhow/error.rs.html Implements AsRef to get a reference to a dynamic standard error that is Send and Sync. ```rust impl AsRef for Error { fn as_ref(&self) -> &(dyn StdError + Send + Sync + 'static) { &**self } } ``` -------------------------------- ### take Source: https://docs.rs/anyhow/latest/anyhow/struct.Chain.html Creates an iterator that yields the first `n` elements, or fewer if the underlying iterator ends sooner. ```APIDOC ## fn take(self, n: usize) -> Take ### Description Creates an iterator that yields the first `n` elements, or fewer if the underlying iterator ends sooner. ### Parameters - **n**: The number of elements to take. ### Type Constraints - `Self`: Must implement `Sized`. ``` -------------------------------- ### Enabling Backtraces with `anyhow` Crate Feature Source: https://docs.rs/anyhow/latest/anyhow/struct.Error.html Illustrates how to enable backtraces for `anyhow::Error` by adding the `"backtrace"` feature to the `anyhow` dependency in `Cargo.toml`. Backtraces are useful for debugging but can incur performance costs. ```toml [dependencies] anyhow = { version = "1.0", features = ["backtrace"] } ``` -------------------------------- ### Error Chain Iterator Source: https://docs.rs/anyhow/latest/src/anyhow/error.rs.html Provides an iterator over the chain of source errors contained within this Error object, starting from the immediate cause. ```APIDOC ## chain ### Description An iterator of the chain of source errors contained by this Error. This iterator will visit every error in the cause chain of this error object, beginning with the error that this error object was created from. ### Example ``` use anyhow::Error; use std::io; pub fn underlying_io_error_kind(error: &Error) -> Option { for cause in error.chain() { if let Some(io_error) = cause.downcast_ref::() { return Some(io_error.kind()); } } None } ``` ### Method `pub fn chain(&self) -> Chain` ``` -------------------------------- ### Adding Context to File Operations Source: https://docs.rs/anyhow/latest/src/anyhow/lib.rs.html Demonstrates adding context to errors during file operations using `context` and `with_context`. Imports `anyhow::Context` and `std::fs`. ```rust use anyhow::{Context, Result}; use std::fs; use std::path::PathBuf; pub struct ImportantThing { path: PathBuf, } impl ImportantThing { # const IGNORE: &'static str = stringify! { pub fn detach(&mut self) -> Result<()> {...} # }; # fn detach(&mut self) -> Result<()> { # unimplemented!() # } } pub fn do_it(mut it: ImportantThing) -> Result> { it.detach().context("Failed to detach the important thing")?; let path = &it.path; let content = fs::read(path) .with_context(|| format!("Failed to read instrs from {}", path.display()))?; Ok(content) } ``` -------------------------------- ### unwrap_err() on Err Result Source: https://docs.rs/anyhow/latest/anyhow/type.Result.html Use `unwrap_err()` to get the contained error value when you are certain the Result is Err. This method panics if the Result is Ok. ```rust let x: Result = Err("emergency failure"); assert_eq!(x.unwrap_err(), "emergency failure"); ``` -------------------------------- ### Alternate Display Representation Source: https://docs.rs/anyhow/latest/anyhow/struct.Error.html Using the alternate selector `{:#}` prints causes as well, showing the error chain with anyhow's default formatting. ```text Failed to read instrs from ./path/to/instrs.json: No such file or directory (os error 2) ``` -------------------------------- ### Basic unwrap on Ok Result Source: https://docs.rs/anyhow/latest/anyhow/type.Result.html Use `unwrap()` to get the contained value when you are certain the Result is Ok. This method panics if the Result is Err. ```rust let x: Result = Ok(2); assert_eq!(x.unwrap(), 2); ``` -------------------------------- ### Get reference to Result contents Source: https://docs.rs/anyhow/latest/anyhow/type.Result.html Use `as_ref()` to obtain references to the contained values of a Result without consuming it. This is useful for inspecting values. ```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")); ``` -------------------------------- ### Iterating and Calculating Product with Result Source: https://docs.rs/anyhow/latest/anyhow/type.Result.html Demonstrates how to use the `product` method on an iterator of Results. If any element fails to parse, the entire operation returns an Err. Otherwise, it returns the Ok value of the product. ```rust let nums = vec!["5", "10", "1", "2"]; let total: Result = nums.iter().map(|w| w.parse::()).product(); assert_eq!(total, Ok(100)); ``` ```rust let nums = vec!["5", "10", "one", "2"]; let total: Result = nums.iter().map(|w| w.parse::()).product(); assert!(total.is_err()); ``` -------------------------------- ### Parse Ensure Macro: Epath with Colons and Identifier Source: https://docs.rs/anyhow/latest/src/anyhow/ensure.rs.html Handles parsing of path expressions starting with colons and an identifier within the `__parse_ensure!` macro. ```rust $crate::__parse_ensure!(epath (atom $stack) $bail ($($fuel)*) {($($buf)* $colons $ident) $($parse)*} ($($rest)*) $($rest)*); ``` -------------------------------- ### Adhoc::new Method Source: https://docs.rs/anyhow/latest/src/anyhow/kind.rs.html Constructs an anyhow::Error from a message that only requires Display and Debug. It captures a backtrace. ```rust impl Adhoc { #[cold] pub fn new(self, message: M) -> Error where M: Display + Debug + Send + Sync + 'static, { Error::construct_from_adhoc(message, Some(std::backtrace::Backtrace::capture())backtrace!()) } } ``` -------------------------------- ### Getting Mutable StdError Reference Source: https://docs.rs/anyhow/latest/src/anyhow/error.rs.html Unsafely retrieves a mutable reference to the underlying `StdError` from an `ErrorImpl`. This is conditionally compiled based on the `std` or `core_error` features. ```rust #[cfg(any(feature = "std", not(anyhow_no_core_error)))] pub(crate) unsafe fn error_mut(this: Mut) -> &mut (dyn StdError + Send + Sync + 'static) { // Use vtable to attach E's native StdError vtable for the right // original type E. unsafe { (vtable(this.ptr).object_ref)(this.by_ref()) .by_mut() .deref_mut() } } ``` -------------------------------- ### Function Signature for Ok Source: https://docs.rs/anyhow/latest/anyhow/fn.Ok.html This is the function signature for `anyhow::fn::Ok`. It takes a value of any type `T` and returns a `Result`. ```rust pub fn Ok(value: T) -> Result ``` -------------------------------- ### Parse Type Path with Angle Bracket Source: https://docs.rs/anyhow/latest/src/anyhow/ensure.rs.html Handles parsing of type paths that are followed by an opening angle bracket '<', indicating the start of generic parameters. ```rust (type $stack:tt $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($langle:tt $($dup:tt)*) < $($rest:tt)*) => { $crate::__parse_ensure!(type (qpath (tpath $stack)) $bail ($($fuel)*) {($($buf)* $langle) $($parse)*} ($($rest)*) $($rest)*) } ``` -------------------------------- ### Boxed::new Method Source: https://docs.rs/anyhow/latest/src/anyhow/kind.rs.html Constructs an anyhow::Error from a boxed dynamic error. It attempts to capture a backtrace if possible, otherwise uses a captured backtrace. ```rust #[cfg(any(feature = "std", not(anyhow_no_core_error)))] impl Boxed { #[cold] pub fn new(self, error: Box) -> Error { let backtrace = match crate::nightly::request_ref_backtrace(&*error as &dyn core::error::Error) { Some(_) => None, None => Some(std::backtrace::Backtrace::capture()), }backtrace_if_absent!(&*error); Error::construct_from_boxed(error, backtrace) } } ``` -------------------------------- ### Getting StdError Reference Source: https://docs.rs/anyhow/latest/src/anyhow/error.rs.html Unsafely retrieves a reference to the underlying `StdError` from an `ErrorImpl` using its vtable. This allows interacting with the error as a standard Rust error type. ```rust impl ErrorImpl { pub(crate) unsafe fn error(this: Ref) -> &(dyn StdError + Send + Sync + 'static) { // Use vtable to attach E's native StdError vtable for the right // original type E. unsafe { (vtable(this.ptr).object_ref)(this).deref() } } } ``` -------------------------------- ### partition Source: https://docs.rs/anyhow/latest/anyhow/struct.Chain.html Consumes an iterator and creates two collections based on a predicate. ```APIDOC ## fn partition(self, f: F) -> (B, B) ### Description Consumes an iterator, creating two collections from it based on a predicate. ### Method `partition` ### Parameters - `f` (F): A closure that takes an item and returns a boolean. ### Type Parameters - `B`: The type of the collections, which must implement `Default` and `Extend`. ### Returns - `(B, B)`: A tuple containing two collections: one for elements where the predicate returned `true`, and one for elements where it returned `false`. ``` -------------------------------- ### Parse Type Path with Colons and Angle Bracket Source: https://docs.rs/anyhow/latest/src/anyhow/ensure.rs.html Handles parsing of type paths starting with '::<' which is used for associated types or specific generic path syntaxes. ```rust (tpath $stack:tt $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($colons:tt $langle:tt $($dup:tt)*) :: < $($rest:tt)*) => { $crate::__parse_ensure!(generic (tpath $stack) $bail ($($fuel)*) {($($buf)* $colons $langle) $($parse)*} ($($rest)*) $($rest)*) } ``` -------------------------------- ### partition_in_place Source: https://docs.rs/anyhow/latest/anyhow/struct.Chain.html Reorders elements in-place based on a predicate. This is a nightly-only experimental API. ```APIDOC ## fn partition_in_place<'a, T, P>(self, predicate: P) -> usize ### Description Reorders the elements of this iterator _in-place_ according to the given predicate, such that all those that return `true` precede all those that return `false`. Returns the number of `true` elements found. ### Method `partition_in_place` ### Parameters - `predicate` (P): A closure that takes a reference to an element and returns a boolean. ### Type Parameters - `'a`: Lifetime parameter. - `T`: The type of the elements in the iterator. - `P`: The type of the predicate closure. ### Returns - `usize`: The number of elements for which the predicate returned `true`. ### Notes This is a nightly-only experimental API. ``` -------------------------------- ### Get Root Cause of an Error Source: https://docs.rs/anyhow/latest/src/anyhow/error.rs.html Retrieves the lowest-level cause of an Anyhow error, which is the last error in the chain produced by `chain()`. This requires the `std` feature or `anyhow_no_core_error` to be disabled. ```rust #[cfg(any(feature = "std", not(anyhow_no_core_error)))] #[allow(clippy::double_ended_iterator_last)] pub fn root_cause(&self) -> &(dyn StdError + 'static) { self.chain().last().unwrap() } ``` -------------------------------- ### Convert Result to Option (Ok value) Source: https://docs.rs/anyhow/latest/anyhow/type.Result.html Use `ok()` to convert a Result into an Option, retaining the Ok value if present. Errors are converted to None. ```rust let x: Result = Ok(2); assert_eq!(x.ok(), Some(2)); let x: Result = Err("Nothing here"); assert_eq!(x.ok(), None); ``` -------------------------------- ### Default for Chain Source: https://docs.rs/anyhow/latest/src/anyhow/chain.rs.html Provides a default empty `Chain`. ```APIDOC ## Default for Chain ### Description Creates an empty `Chain` with no errors. This is useful for initializing a `Chain` when no error is present initially. ### Method `default` ### Return Value - `Chain<'a>` - An empty `Chain` instance. ``` -------------------------------- ### unwrap_or_default() for default values Source: https://docs.rs/anyhow/latest/anyhow/type.Result.html Use `unwrap_or_default()` to get the contained Ok value or the type's default value if the Result is Err. This is useful for fallbacks when a default is acceptable. ```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); ``` -------------------------------- ### Get mutable reference to Result contents Source: https://docs.rs/anyhow/latest/anyhow/type.Result.html Use `as_mut()` to obtain mutable references to the contained values of a Result. This allows in-place modification of Ok or Err values. ```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); ``` -------------------------------- ### by_ref Source: https://docs.rs/anyhow/latest/anyhow/struct.Chain.html Creates a “by reference” adapter for this instance of `Iterator`. ```APIDOC ## fn by_ref(&mut self) -> &mut Self ### Description Creates a “by reference” adapter for this instance of `Iterator`. ### Type Constraints - `Self`: Must implement `Sized`. ``` -------------------------------- ### Parse Type Path with Colons and Double Angle Brackets Source: https://docs.rs/anyhow/latest/src/anyhow/ensure.rs.html Handles parsing of type paths starting with '::<<', used for complex associated types or nested generic structures. ```rust (tpath $stack:tt $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($colons:tt $langle:tt $($dup:tt)*) :: << $($rest:tt)*) => { $crate::__parse_ensure!(type (qpath (tpath (arglist (tpath $stack)))) $bail ($($fuel)*) {($($buf)* $colons $langle) $($parse)*} ($($rest)*) $($rest)*) } ``` -------------------------------- ### map_windows Source: https://docs.rs/anyhow/latest/anyhow/struct.Chain.html Calls the given function `f` for each contiguous window of size `N` over `self` and returns an iterator over the outputs of `f`. This is a nightly-only experimental API. ```APIDOC ## fn map_windows(self, f: F) -> MapWindows ### Description Calls the given function `f` for each contiguous window of size `N` over `self` and returns an iterator over the outputs of `f`. ### Parameters - **f**: The function to apply to each window. ### Type Constraints - `Self`: Must implement `Sized`. - `F`: Must implement `FnMut(&[Self::Item; N]) -> R`. - `N`: The size of the window. ``` -------------------------------- ### Parse Ensure Macro: Epath with Colons and Angle Brackets Source: https://docs.rs/anyhow/latest/src/anyhow/ensure.rs.html Handles parsing of path expressions starting with colons and followed by angle brackets within the `__parse_ensure!` macro. ```rust $crate::__parse_ensure!(generic (epath $stack) $bail ($($fuel)*) {($($buf)* $colons $langle) $($parse)*} ($($rest)*) $($rest)*); ``` -------------------------------- ### product Source: https://docs.rs/anyhow/latest/anyhow/struct.Chain.html Iterates over the entire iterator, multiplying all the elements. ```APIDOC ## product

(self) -> P ### Description Iterates over the entire iterator, multiplying all the elements. The product type `P` must implement `Product`. ``` -------------------------------- ### anyhow Macro Definition Source: https://docs.rs/anyhow/latest/anyhow/macro.anyhow.html Defines the different forms the anyhow macro can take, including literal strings, expressions, and formatted strings with arguments. ```rust macro_rules! anyhow { ($msg:literal $(,)?) => { ... }; ($err:expr $(,)?) => { ... }; ($fmt:expr, $($arg:tt)*) => { ... }; } ``` -------------------------------- ### Parse Type Path with Colons and Identifier Source: https://docs.rs/anyhow/latest/src/anyhow/ensure.rs.html Handles parsing of qualified type paths that start with '::' followed by an identifier, used for accessing items within modules or associated items. ```rust (tpath $stack:tt $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($colons:tt $ident:tt $($dup:tt)*) :: $i:ident $($rest:tt)*) => { $crate::__parse_ensure!(tpath $stack $bail ($($fuel)*) {($($buf)* $colons $ident) $($parse)*} ($($rest)*) $($rest)*) } ``` -------------------------------- ### Adding Context to Errors Source: https://docs.rs/anyhow/latest/src/anyhow/fmt.rs.html Illustrates how to add context to errors using the `context` method provided by anyhow. This is useful for providing more information about where an error occurred. ```rust use anyhow::{Context, Result}; fn read_config() -> Result { // Simulate reading a config file that might not exist Err(anyhow::anyhow!("Config file not found")).context("Failed to read configuration") } fn main() { match read_config() { Ok(config) => println!("Config: {}", config), Err(e) => println!("Error: {:?}", e), } } ``` -------------------------------- ### Context and Downcasting Source: https://docs.rs/anyhow/latest/anyhow/trait.Context.html Explains how adding context with `anyhow::Context` affects downcasting. It ensures that existing downcasts will continue to work, supporting both cases where the context type is significant for downcasting or insignificant. ```APIDOC ## §Effect on downcasting After attaching context of type `C` onto an error of type `E`, the resulting `anyhow::Error` may be downcast to `C` **or** to `E`. ### Attaching context whose type is insignificant onto errors whose type is used in downcasts. ```rust use anyhow::{Context, Result}; fn do_it() -> Result<()> { helper().context("Failed to complete the work")?; ... } fn main() { let err = do_it().unwrap_err(); if let Some(e) = err.downcast_ref::() { // If helper() returned SuspiciousError, this downcast will // correctly succeed even with the context in between. } } ``` ### Attaching context whose type is used in downcasts onto errors whose type is insignificant. ```rust use anyhow::{Context, Result}; fn do_it() -> Result<()> { helper().context(HelperFailed)?; ... } fn main() { let err = do_it().unwrap_err(); if let Some(e) = err.downcast_ref::() { // If helper failed, this downcast will succeed because // HelperFailed is the context that has been attached to // that error. } } ``` ``` -------------------------------- ### Parse Ensure Macro: Epath with Colons and Identifier (revisited) Source: https://docs.rs/anyhow/latest/src/anyhow/ensure.rs.html Handles parsing of path expressions starting with colons and an identifier, revisiting a previous pattern within the `__parse_ensure!` macro. ```rust $crate::__parse_ensure!(epath $stack $bail ($($fuel)*) {($($buf)* $colons $ident) $($parse)*} ($($rest)*) $($rest)*); ``` -------------------------------- ### Parse Ensure Macro: Epath with Colons and Left Arrow Source: https://docs.rs/anyhow/latest/src/anyhow/ensure.rs.html Handles parsing of path expressions starting with colons and a left arrow, followed by a literal, within the `__parse_ensure!` macro. ```rust $crate::__parse_ensure!(generic (epath $stack) $bail ($($fuel)*) {($($buf)* $colons $larrow) $($parse)*} ($($dup)*) $($dup)*); ``` -------------------------------- ### Result Implementations Source: https://docs.rs/anyhow/latest/anyhow/type.Result.html Common implementations for the Result type, including methods for copying, cloning, transposing, and flattening. ```APIDOC ## Implementations ### `impl Result<&T, E>` #### `copied(self) -> Result` * **Description**: Maps a `Result<&T, E>` to a `Result` by copying the contents of the `Ok` part. Requires `T: Copy`. * **Example**: ```rust let val = 12; let x: Result<&i32, i32> = Ok(&val); let copied = x.copied(); assert_eq!(copied, Ok(12)); ``` #### `cloned(self) -> Result` * **Description**: Maps a `Result<&T, E>` to a `Result` by cloning the contents of the `Ok` part. Requires `T: Clone`. * **Example**: ```rust let val = 12; let x: Result<&i32, i32> = Ok(&val); let cloned = x.cloned(); assert_eq!(cloned, Ok(12)); ``` ### `impl Result<&mut T, E>` #### `copied(self) -> Result` * **Description**: Maps a `Result<&mut T, E>` to a `Result` by copying the contents of the `Ok` part. Requires `T: Copy`. * **Example**: ```rust let mut val = 12; let x: Result<&mut i32, i32> = Ok(&mut val); let copied = x.copied(); assert_eq!(copied, Ok(12)); ``` #### `cloned(self) -> Result` * **Description**: Maps a `Result<&mut T, E>` to a `Result` by cloning the contents of the `Ok` part. Requires `T: Clone`. * **Example**: ```rust let mut val = 12; let x: Result<&mut i32, i32> = Ok(&mut val); let cloned = x.cloned(); assert_eq!(cloned, Ok(12)); ``` ### `impl Result, E>` #### `transpose(self) -> Option>` * **Description**: Transposes 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(_))` respectively. * **Example**: ```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); ``` ### `impl Result, E>` #### `flatten(self) -> Result` * **Description**: Converts from `Result, E>` to `Result`, removing one level of nesting. * **Example**: ```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()); ``` ### `impl Result` #### `is_ok(&self) -> bool` * **Description**: Returns `true` if the result is `Ok`. * **Example**: ```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); ``` #### `is_ok_and(self, f: F) -> bool` where `F: FnOnce(T) -> bool` * **Description**: Returns `true` if the result is `Ok` and the value inside it matches a predicate. * **Example**: ```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); ``` #### `is_err(&self) -> bool` * **Description**: Returns `true` if the result is `Err`. ``` -------------------------------- ### Iterating Through Error Causes with `chain()` Source: https://docs.rs/anyhow/latest/anyhow/struct.Error.html Demonstrates how to use the `chain()` method to iterate over all source errors in an `anyhow::Error`'s cause chain. This is useful for inspecting or handling specific error types within the chain. ```rust use anyhow::Error; use std::io; pub fn underlying_io_error_kind(error: &Error) -> Option { for cause in error.chain() { if let Some(io_error) = cause.downcast_ref::() { return Some(io_error.kind()); } } None } ``` -------------------------------- ### Construct Error from Boxed StdError Source: https://docs.rs/anyhow/latest/src/anyhow/error.rs.html Used internally to construct an anyhow::Error from a boxed standard library error. Requires specific vtable setup for the boxed error type. ```rust unsafe { Error::construct(error, vtable, backtrace) } ``` -------------------------------- ### Using anyhow::Result in Functions Source: https://docs.rs/anyhow/latest/anyhow/type.Result.html Demonstrates how to use anyhow::Result as a return type in functions. It's equivalent to std::result::Result or std::result::Result. ```rust use anyhow::Result; fn demo1() -> Result {...} // ^ equivalent to std::result::Result fn demo2() -> Result {...} // ^ equivalent to std::result::Result ```