### Box from() method example Source: https://docs.rs/pingora-error/0.8.0/pingora_error/type.BError.html Demonstrates how to convert a value of type T into a Box using the `from` method. This allocates memory on the heap. ```rust let x = 5; let boxed = Box::new(5); assert_eq!(Box::from(x), boxed); ``` -------------------------------- ### Box::from_raw Example - Manual Allocation Source: https://docs.rs/pingora-error/0.8.0/pingora_error/type.BError.html Illustrates manually creating a Box from scratch using the global allocator and a raw pointer. This requires careful handling of memory allocation and deallocation. ```rust use std::alloc::{alloc, Layout}; unsafe { let ptr = alloc(Layout::new::()) as *mut i32; // In general .write is required to avoid attempting to destruct // the (uninitialized) previous contents of `ptr`, though for this // simple example `*ptr = 5` would have worked as well. ptr.write(5); let x = Box::from_raw(ptr); } ``` -------------------------------- ### Box::from_non_null Example - Manual Allocation Source: https://docs.rs/pingora-error/0.8.0/pingora_error/type.BError.html Demonstrates manually creating a Box from scratch using the global allocator and a NonNull pointer. This is a nightly-only experimental API and requires careful memory management. ```rust #![feature(box_vec_non_null)] use std::alloc::{alloc, Layout}; use std::ptr::NonNull; unsafe { let non_null = NonNull::new(alloc(Layout::new::()).cast::()) .expect("allocation failed"); // In general .write is required to avoid attempting to destruct // the (uninitialized) previous contents of `non_null`. non_null.write(5); let x = Box::from_non_null(non_null); } ``` -------------------------------- ### Box::from_non_null Example - Recreate Box Source: https://docs.rs/pingora-error/0.8.0/pingora_error/type.BError.html Shows how to recreate a Box from a NonNull pointer, typically obtained from Box::into_non_null. This is a nightly-only experimental API. ```rust #![feature(box_vec_non_null)] let x = Box::new(5); let non_null = Box::into_non_null(x); let x = unsafe { Box::from_non_null(non_null) }; ``` -------------------------------- ### Box::from_raw Example - Recreate Box Source: https://docs.rs/pingora-error/0.8.0/pingora_error/type.BError.html Demonstrates recreating a Box from a raw pointer obtained via Box::into_raw. This is useful for managing memory and ensuring proper cleanup. ```rust let x = Box::new(5); let ptr = Box::into_raw(x); let x = unsafe { Box::from_raw(ptr) }; ``` -------------------------------- ### Box::into_raw Example - Automatic Cleanup Source: https://docs.rs/pingora-error/0.8.0/pingora_error/type.BError.html Illustrates converting a Box into a raw pointer using Box::into_raw and then back into a Box using Box::from_raw for automatic memory cleanup. ```rust let x = Box::new(String::from("Hello")); let ptr = Box::into_raw(x); let x = unsafe { Box::from_raw(ptr) }; ``` -------------------------------- ### Error Display Example Source: https://docs.rs/pingora-error/0.8.0/pingora_error/trait.ErrorTrait.html Demonstrates how error messages should be concise lowercase sentences without trailing punctuation, using a parsing error as an example. ```rust let err = "NaN".parse::().unwrap_err(); assert_eq!(err.to_string(), "invalid digit found in string"); ``` -------------------------------- ### Box::into_raw Example - Manual Cleanup Source: https://docs.rs/pingora-error/0.8.0/pingora_error/type.BError.html Shows how to manually clean up memory after converting a Box into a raw pointer using Box::into_raw. This involves explicitly dropping the value and deallocating memory. ```rust use std::alloc::{dealloc, Layout}; use std::ptr; let x = Box::new(String::from("Hello")); let ptr = Box::into_raw(x); unsafe { ptr::drop_in_place(ptr); dealloc(ptr as *mut u8, Layout::new::()); } Note: This is equivalent to the following: let x = Box::new(String::from("Hello")); let ptr = Box::into_raw(x); unsafe { drop(Box::from_raw(ptr)); } ``` -------------------------------- ### Getting File Metadata with and_then Source: https://docs.rs/pingora-error/0.8.0/pingora_error/type.Result.html Shows how to use `and_then` to chain fallible operations, specifically for getting file metadata and its modification time. Handles potential errors like file not found. ```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); ``` -------------------------------- ### Get Reason and Source as String Source: https://docs.rs/pingora-error/0.8.0/src/pingora_error/lib.rs.html Methods to get the error type and source as string slices. These provide a human-readable representation of the error's nature and origin. ```rust pub fn reason_str(&self) -> &str { self.etype.as_str() } ``` ```rust pub fn source_str(&self) -> &str { self.esource.as_str() } ``` -------------------------------- ### Safely get Ok value (nightly) Source: https://docs.rs/pingora-error/0.8.0/pingora_error/type.Result.html Returns the contained Ok value, never panics. This is an experimental API. ```Rust fn only_good_news() -> Result { Ok("this is fine".into()) } let s: String = only_good_news().into_ok(); println!("{s}"); ``` -------------------------------- ### fn take(self, limit: u64) -> Take Source: https://docs.rs/pingora-error/0.8.0/pingora_error/type.BError.html Creates an adapter which will read at most `limit` bytes from this `Read` stream. If `limit` is 0, no bytes will be read. ```APIDOC ## fn take(self, limit: u64) -> Take ### Description Creates an adapter that limits the number of bytes read from this `Read` stream to a specified `limit`. ### Parameters - `limit` (*u64*): The maximum number of bytes to read. ### Returns - `Take`: A `Take` adapter that limits the read operation. ``` -------------------------------- ### Get Error Type and Source Source: https://docs.rs/pingora-error/0.8.0/src/pingora_error/lib.rs.html Methods to retrieve the `ErrorType` and `ErrorSource` of a `BError`. These are read-only accessors. ```rust pub fn etype(&self) -> &ErrorType { &self.etype } ``` ```rust pub fn esource(&self) -> &ErrorSource { &self.esource } ``` -------------------------------- ### Box::new_uninit_in Source: https://docs.rs/pingora-error/0.8.0/pingora_error/type.BError.html Constructs a new Box with uninitialized contents using the provided allocator. This is a nightly-only experimental API. ```APIDOC ## pub fn new_uninit_in(alloc: A) -> Box, A> ### Description Constructs a new box with uninitialized contents in the provided allocator. ### Method Associated function (call as `Box::::new_uninit_in(allocator)`) ### Parameters * **alloc** (A) - The allocator to use. ### Returns * **Box, A>** - A Box containing uninitialized memory. ### Examples ```rust #![feature(allocator_api)] use std::alloc::System; let mut five = Box::::new_uninit_in(System); // Deferred initialization: five.write(5); let five = unsafe { five.assume_init() }; assert_eq!(*five, 5) ``` ``` -------------------------------- ### Safely get Err value (nightly) Source: https://docs.rs/pingora-error/0.8.0/pingora_error/type.Result.html Returns the contained Err value, never panics. This is an experimental API. ```Rust fn only_bad_news() -> Result { Err("Oops, it failed".into()) } let error: String = only_bad_news().into_err(); println!("{error}"); ``` -------------------------------- ### fn stream_position(&mut self) -> Result Source: https://docs.rs/pingora-error/0.8.0/pingora_error/type.BError.html Returns the current seek position from the start of the stream. ```APIDOC ## fn stream_position(&mut self) -> Result ### Description Returns the current position within the stream, measured in bytes from the beginning of the stream. ### Returns - `Result`: On success, returns the current stream position. On failure, returns an `Error`. ``` -------------------------------- ### Manually Create Box from Scratch Source: https://docs.rs/pingora-error/0.8.0/pingora_error/type.BError.html Manually creates a Box from scratch using the system allocator. This involves allocating memory, writing the value, and then constructing the Box. ```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); } ``` -------------------------------- ### report() method for Termination Source: https://docs.rs/pingora-error/0.8.0/pingora_error/type.Result.html The `report` method is called to get the representation of the Result value as a status code, which is then returned to the operating system. ```rust fn report(self) -> ExitCode ``` -------------------------------- ### Manual Cleanup via Box::from_non_null (Equivalent) Source: https://docs.rs/pingora-error/0.8.0/pingora_error/type.BError.html Shows an alternative manual cleanup method that leverages `Box::from_non_null` within a `drop` call, achieving the same result as explicit deallocation. ```rust #![feature(box_vec_non_null)] let x = Box::new(String::from("Hello")); let non_null = Box::into_non_null(x); unsafe { drop(Box::from_non_null(non_null)); } ``` -------------------------------- ### downcast_ref Source: https://docs.rs/pingora-error/0.8.0/pingora_error/trait.ErrorTrait.html Attempts to get a reference to the inner error value if it matches the specified type T. Returns None if the type does not match. ```APIDOC ## pub fn downcast_ref(&self) -> Option<&T> ### Description Returns some reference to the inner value if it is of type `T`, or `None` if it isn’t. ### Method `downcast_ref` ### Parameters #### Type Parameters - **T**: The target type to downcast to. Must implement `Error + 'static`. ### Returns - `Option<&T>`: A reference to the inner value if it matches `T`, otherwise `None`. ``` -------------------------------- ### Get Reference to Underlying Allocator Source: https://docs.rs/pingora-error/0.8.0/pingora_error/type.BError.html Returns a reference to the allocator used by the Box. This is an associated function to avoid conflicts with methods on the inner type. ```rust let mut b = Box::new(0); let alloc_ref = Box::allocator(&b); ``` -------------------------------- ### CloneToUninit Implementation (Nightly) Source: https://docs.rs/pingora-error/0.8.0/pingora_error/enum.ErrorSource.html An experimental, nightly-only API for performing copy-assignment from `self` to an uninitialized destination. ```rust unsafe fn clone_to_uninit(&self, dest: *mut u8) ``` -------------------------------- ### downcast_mut Source: https://docs.rs/pingora-error/0.8.0/pingora_error/trait.ErrorTrait.html Attempts to get a mutable reference to the inner error value if it matches the specified type T. Returns None if the type does not match. ```APIDOC ## pub fn downcast_mut(&mut self) -> Option<&mut T> ### Description Returns some mutable reference to the inner value if it is of type `T`, or `None` if it isn’t. ### Method `downcast_mut` ### Parameters #### Type Parameters - **T**: The target type to downcast to. Must implement `Error + 'static`. ### Returns - `Option<&mut T>`: A mutable reference to the inner value if it matches `T`, otherwise `None`. ``` -------------------------------- ### Box::new_uninit Source: https://docs.rs/pingora-error/0.8.0/pingora_error/type.BError.html Constructs a new Box with uninitialized contents. This is useful for deferred initialization. ```APIDOC ## Box::new_uninit ### Description Constructs a new box with uninitialized contents. ### Method Associated function ### Parameters None ### Response - **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) ``` ``` -------------------------------- ### fold Source: https://docs.rs/pingora-error/0.8.0/pingora_error/type.BError.html Applies a closure to each element of the iterator, accumulating a result. It starts with an initial value and repeatedly applies the closure to the current accumulator and the next element. ```APIDOC ## fn fold(self, init: B, f: F) -> B ### Description Folds every element into an accumulator by applying an operation, returning the final result. ### Parameters - `init`: The initial value of the accumulator. - `f`: A closure that takes the current accumulator value and the next item, returning the updated accumulator value. ### Type Parameters - `B`: The type of the accumulator. - `F`: The type of the closure. ### Returns The final accumulated value of type `B`. ``` -------------------------------- ### Automatic Cleanup with Box::from_non_null Source: https://docs.rs/pingora-error/0.8.0/pingora_error/type.BError.html Demonstrates how to convert a Box to a NonNull pointer and then back to a Box using `Box::from_non_null` for automatic memory management and cleanup. ```rust #![feature(box_vec_non_null)] let x = Box::new(String::from("Hello")); let non_null = Box::into_non_null(x); let x = unsafe { Box::from_non_null(non_null) }; ``` -------------------------------- ### Box::try_new_uninit_in Source: https://docs.rs/pingora-error/0.8.0/pingora_error/type.BError.html Attempts to construct a new Box with uninitialized contents using the provided allocator, returning an error if the allocation fails. This is a nightly-only experimental API. ```APIDOC ## pub fn try_new_uninit_in(alloc: A) -> Result, A>, AllocError> ### Description Constructs a new box with uninitialized contents in the provided allocator, returning an error if the allocation fails. ### Method Associated function (call as `Box::::try_new_uninit_in(allocator)`) ### Parameters * **alloc** (A) - The allocator to use. ### Returns * **Result, A>, AllocError>** - A Result containing the Box if successful, or an AllocError if the allocation failed. ### Examples ```rust #![feature(allocator_api)] use std::alloc::System; let mut five = Box::::try_new_uninit_in(System)?; // Deferred initialization: five.write(5); let five = unsafe { five.assume_init() }; assert_eq!(*five, 5); ``` ``` -------------------------------- ### Attempt to create an uninitialized Box> with Box::try_new_uninit (nightly) Source: https://docs.rs/pingora-error/0.8.0/pingora_error/type.BError.html Constructs a new box with uninitialized contents on the heap, returning an error if the allocation fails. This is a nightly-only experimental API. ```rust #![feature(allocator_api)] let mut five = Box::::try_new_uninit()?; // Deferred initialization: five.write(5); let five = unsafe { five.assume_init() }; assert_eq!(*five, 5); ``` -------------------------------- ### Iterator Collection with Early Error Exit Source: https://docs.rs/pingora-error/0.8.0/pingora_error/type.Result.html Shows how `collect()` on an iterator of Results stops processing further elements once an Err is encountered. The example verifies that a shared variable is not updated after 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); ``` -------------------------------- ### try_new_zeroed_in Source: https://docs.rs/pingora-error/0.8.0/pingora_error/type.BError.html Constructs a new Box with uninitialized contents, filling the memory with 0 bytes using the provided allocator. Returns an error if allocation fails. This is a nightly-only experimental API. ```APIDOC ## pub fn try_new_zeroed_in(alloc: A) -> Result, A>, AllocError> ### Description Constructs a new `Box` with uninitialized contents, with the memory being filled with `0` bytes in the provided allocator, returning an error if the allocation fails. ### Parameters #### Path Parameters - **alloc** (A) - Required - The allocator to use for memory allocation. ### Response #### Success Response - **Box, A>** - A Box containing uninitialized memory filled with zeros. #### Error Response - **AllocError** - Returned if the memory allocation fails. ``` -------------------------------- ### Box::try_new_uninit Source: https://docs.rs/pingora-error/0.8.0/pingora_error/type.BError.html Constructs a new box with uninitialized contents on the heap, returning an error if the allocation fails. This is an experimental API. ```APIDOC ## Box::try_new_uninit ### Description Constructs a new box with uninitialized contents on the heap, returning an error if the allocation fails. This is a nightly-only experimental API. ### Method Associated function ### Parameters None ### Response - **Result>, AllocError>** - Ok containing the Box if allocation succeeds, or an Err containing an AllocError if it fails. ### Example ```rust #![feature(allocator_api)] let mut five = Box::::try_new_uninit()?; // Deferred initialization: five.write(5); let five = unsafe { five.assume_init() }; assert_eq!(*five, 5); ``` ``` -------------------------------- ### Cloning a Box Source: https://docs.rs/pingora-error/0.8.0/pingora_error/type.BError.html Demonstrates how to clone a Box to create a new box with identical contents. It also verifies that the cloned boxes are unique objects. ```rust let x = Box::new(5); let y = x.clone(); // The value is the same assert_eq!(x, y); // But they are unique objects assert_ne!(&*x as *const i32, &*y as *const i32); ``` -------------------------------- ### Get immutable references from Result Source: https://docs.rs/pingora-error/0.8.0/pingora_error/type.Result.html Use `as_ref` to convert a `&Result` into a `Result<&T, &E>`. This allows you to inspect the contents of a `Result` without consuming it, producing references to the contained 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")); ``` -------------------------------- ### into_ok Source: https://docs.rs/pingora-error/0.8.0/pingora_error/type.Result.html Returns the contained `Ok` value, but never panics. This is a nightly-only experimental API. ```APIDOC ## pub const fn into_ok(self) -> T ### Description Returns the contained `Ok` value, but never panics. Unlike `unwrap`, this method is known to never panic on the result types it is implemented for. Therefore, 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. ### Method `into_ok` ### Examples ```rust fn only_good_news() -> Result { Ok("this is fine".into()) } let s: String = only_good_news().into_ok(); println!("{s}"); ``` ``` -------------------------------- ### Box::clone_from_ref Source: https://docs.rs/pingora-error/0.8.0/pingora_error/type.BError.html Allocates memory on the heap then clones src into it. This is an experimental API. ```APIDOC ## Box::clone_from_ref ### Description Allocates memory on the heap then clones `src` into it. This doesn’t actually allocate if `src` is zero-sized. This is a nightly-only experimental API. ### Method Associated function ### Parameters - **src**: &T - The reference to the value to clone. ### Response - **Box** - A new Box containing a clone of `src`. ### Example ```rust #![feature(clone_from_ref)] let hello: Box = Box::clone_from_ref("hello"); ``` ``` -------------------------------- ### Get Raw Pointer to Box Contents (Aliasing Guarantee) Source: https://docs.rs/pingora-error/0.8.0/pingora_error/type.BError.html Returns a raw pointer to the Box's contents. This pointer remains valid when mixed with other calls to as_ptr and as_mut_ptr, provided no writes occur. ```rust #![feature(box_as_ptr)] unsafe { let mut v = Box::new(0); let ptr1 = Box::as_ptr(&v); let ptr2 = Box::as_mut_ptr(&mut v); let _val = ptr2.read(); // No write to this memory has happened yet, so `ptr1` is still valid. let _val = ptr1.read(); // However, once we do a write... ptr2.write(1); // ... `ptr1` is no longer valid. // This would be UB: let _val = ptr1.read(); } ``` -------------------------------- ### Attempt to create a zeroed Box> with Box::try_new_zeroed (nightly) Source: https://docs.rs/pingora-error/0.8.0/pingora_error/type.BError.html Constructs a new Box with uninitialized contents, with the memory being filled with 0 bytes on the heap. This is a nightly-only experimental API. ```rust #![feature(allocator_api)] let zero = Box::::try_new_zeroed()?; let zero = unsafe { zero.assume_init() }; assert_eq!(*zero, 0); ``` -------------------------------- ### Create an uninitialized Box> with Box::new_uninit Source: https://docs.rs/pingora-error/0.8.0/pingora_error/type.BError.html Constructs a new box with uninitialized contents. Deferred initialization is required before use. ```rust let mut five = Box::::new_uninit(); // Deferred initialization: five.write(5); let five = unsafe { five.assume_init() }; assert_eq!(*five, 5) ``` -------------------------------- ### Collecting Results with Error Handling Source: https://docs.rs/pingora-error/0.8.0/pingora_error/type.Result.html Demonstrates how to collect an iterator of Results into a single Result. If any element is an Err, it's returned immediately. Otherwise, a container with all Ok values is returned. This example shows overflow checking. ```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])); ``` -------------------------------- ### Box::try_clone_from_ref Source: https://docs.rs/pingora-error/0.8.0/pingora_error/type.BError.html Allocates memory on the heap then clones src into it, returning an error if allocation fails. This is an experimental API. ```APIDOC ## Box::try_clone_from_ref ### Description Allocates memory on the heap then clones `src` into it, returning an error if allocation fails. This doesn’t actually allocate if `src` is zero-sized. This is a nightly-only experimental API. ### Method Associated function ### Parameters - **src**: &T - The reference to the value to clone. ### Response - **Result, AllocError>** - Ok containing the Box if allocation succeeds, or an Err containing an AllocError if it fails. ### Example ```rust #![feature(clone_from_ref)] #![feature(allocator_api)] let hello: Box = Box::try_clone_from_ref("hello")?; ``` ``` -------------------------------- ### Get Mutable Raw Pointer to Box Contents (Aliasing Guarantee) Source: https://docs.rs/pingora-error/0.8.0/pingora_error/type.BError.html Returns a raw mutable pointer to the Box's contents. This pointer is valid even when mixed with other calls to as_ptr and as_mut_ptr due to aliasing guarantees. ```rust #![feature(box_as_ptr)] unsafe { let mut b = Box::new(0); let ptr1 = Box::as_mut_ptr(&mut b); ptr1.write(1); let ptr2 = Box::as_mut_ptr(&mut b); ptr2.write(2); // Notably, the write to `ptr2` did *not* invalidate `ptr1`: ptr1.write(3); } ``` -------------------------------- ### Get mutable references from Result Source: https://docs.rs/pingora-error/0.8.0/pingora_error/type.Result.html Use `as_mut` to convert a `&mut Result` into a `Result<&mut T, &mut E>`. This enables in-place modification of the `Result`'s contents, allowing you to change the `Ok` value or the `Err` value directly. ```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); ``` -------------------------------- ### fn by_ref(&mut self) -> &mut Self Source: https://docs.rs/pingora-error/0.8.0/pingora_error/type.BError.html Creates a “by reference” adapter for this instance of `Write`. This allows borrowing the writer without consuming it. ```APIDOC ## fn by_ref(&mut self) -> &mut Self ### Description Creates a "by reference" adapter for this instance of `Write`. This adapter allows you to use the `Write` methods on a mutable reference to the writer, without consuming the original writer. ### Returns - `&mut Self`: A mutable reference to a `Write` adapter. ``` -------------------------------- ### Leaking a Box to Get a Mutable Reference Source: https://docs.rs/pingora-error/0.8.0/pingora_error/type.BError.html Use Box::leak to consume a Box and obtain a mutable reference to the contained data. The returned reference must be managed carefully to avoid memory leaks; wrap it with Box::from_raw to properly deallocate. ```rust let x = Box::new(41); let static_ref: &'static mut usize = Box::leak(x); *static_ref += 1; assert_eq!(*static_ref, 42); ``` -------------------------------- ### AsFd Implementation Source: https://docs.rs/pingora-error/0.8.0/pingora_error/type.BError.html Provides a method to borrow the file descriptor associated with the Box. ```APIDOC ## fn as_fd(&self) -> BorrowedFd<'_> ### Description Borrows the file descriptor. ### Method `as_fd` ``` -------------------------------- ### Experimental `provide` Method for Error Context Access Source: https://docs.rs/pingora-error/0.8.0/pingora_error/trait.ErrorTrait.html Illustrates the nightly-only experimental `provide` method for accessing specific error context using `Request`. ```rust #![feature(error_generic_member_access)] use core::fmt; use core::error::{request_ref, Request}; #[derive(Debug)] enum MyLittleTeaPot { Empty, } #[derive(Debug)] struct MyBacktrace { // ... } impl MyBacktrace { fn new() -> MyBacktrace { // ... } } #[derive(Debug)] struct Error { backtrace: MyBacktrace, } impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "Example Error") } } impl std::error::Error for Error { fn provide<'a>(&'a self, request: &mut Request<'a>) { request .provide_ref::(&self.backtrace); } } fn main() { let backtrace = MyBacktrace::new(); let error = Error { backtrace }; let dyn_error = &error as &dyn std::error::Error; let backtrace_ref = request_ref::(dyn_error).unwrap(); assert!(core::ptr::eq(&error.backtrace, backtrace_ref)); assert!(request_ref::(dyn_error).is_none()); } ``` -------------------------------- ### Attempt to create a Box with Box::try_new (nightly) Source: https://docs.rs/pingora-error/0.8.0/pingora_error/type.BError.html Allocates memory on the heap and places a value into it, returning an error if the allocation fails. This is a nightly-only experimental API. ```rust #![feature(allocator_api)] let five = Box::try_new(5)?; ``` -------------------------------- ### take Source: https://docs.rs/pingora-error/0.8.0/pingora_error/type.BError.html Consumes the Box without consuming its allocation, returning the wrapped value and a Box to the uninitialized memory where the wrapped value used to live. This can be used together with `write` to reuse the allocation for multiple boxed values. This is a nightly-only experimental API. ```APIDOC ## pub fn take(boxed: Box) -> (T, Box, A>) ### Description Consumes the `Box` without consuming its allocation, returning the wrapped value and a `Box` to the uninitialized memory where the wrapped value used to live. ### Parameters #### Path Parameters - **boxed** (Box) - Required - The Box to take the value from. ### Response #### Success Response - **(T, Box, A>)** - A tuple containing the original value and a Box to the uninitialized memory. ``` -------------------------------- ### Using the `source` Method for Error Chaining Source: https://docs.rs/pingora-error/0.8.0/pingora_error/trait.ErrorTrait.html Shows how to implement and use the `source` method to return the lower-level error in a chain. ```rust use std::error::Error; use std::fmt; #[derive(Debug)] struct SuperError { source: SuperErrorSideKick, } impl fmt::Display for SuperError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "SuperError is here!") } } impl Error for SuperError { fn source(&self) -> Option<&(dyn Error + 'static)> { Some(&self.source) } } #[derive(Debug)] struct SuperErrorSideKick; impl fmt::Display for SuperErrorSideKick { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "SuperErrorSideKick is here!") } } impl Error for SuperErrorSideKick {} fn get_super_error() -> Result<(), SuperError> { Err(SuperError { source: SuperErrorSideKick }) } fn main() { match get_super_error() { Err(e) => { println!("Error: {e}"); println!("Caused by: {}", e.source().unwrap()); } _ => println!("No error"), } } ``` -------------------------------- ### Handling Options with `or_err` and `or_err_with` Source: https://docs.rs/pingora-error/0.8.0/src/pingora_error/lib.rs.html Demonstrates how to convert an `Option` into a `Result` using `or_err` and `or_err_with`, providing an error type and context when the option is `None`. ```rust let m = Some(2); let o = m.or_err(ErrorType::InternalError, "some is not an error!"); assert_eq!(2, o.unwrap()); ``` ```rust let m = Some(2); let o = m.or_err_with(ErrorType::InternalError, || "some is not an error!"); assert_eq!(2, o.unwrap()); ``` ```rust let m: Option = None; let e1 = m.or_err(ErrorType::InternalError, "none is an error!"); assert_eq!(format!("{}", e1.unwrap_err()), " InternalError context: none is an error!"); ``` ```rust let m: Option = None; let e1 = m.or_err_with(ErrorType::InternalError, || "none is an error!"); assert_eq!(format!("{}", e1.unwrap_err()), " InternalError context: none is an error!"); ``` -------------------------------- ### Box::try_new Source: https://docs.rs/pingora-error/0.8.0/pingora_error/type.BError.html Allocates memory on the heap then places x into it, returning an error if the allocation fails. This is an experimental API. ```APIDOC ## Box::try_new ### Description Allocates memory on the heap then places `x` into it, returning an error if the allocation fails. This doesn’t actually allocate if `T` is zero-sized. This is a nightly-only experimental API. ### Method Associated function ### Parameters - **x**: T - The value to place in the Box. ### Response - **Result, AllocError>** - Ok containing the Box if allocation succeeds, or an Err containing an AllocError if it fails. ### Example ```rust #![feature(allocator_api)] let five = Box::try_new(5)?; ``` ``` -------------------------------- ### Grow Memory Block Zeroed with Allocator API Source: https://docs.rs/pingora-error/0.8.0/pingora_error/type.BError.html Behaves like `grow`, but also ensures that the new contents are set to zero before being returned. This is a nightly-only experimental API. ```rust use std::alloc::{Layout, AllocError, NonNull}; // Assuming 'self' is an instance of Box implementing Allocator // let result: Result, AllocError> = unsafe { self.grow_zeroed(ptr, old_layout, new_layout) }; ``` -------------------------------- ### Box::try_new_zeroed Source: https://docs.rs/pingora-error/0.8.0/pingora_error/type.BError.html Constructs a new Box with uninitialized contents, with the memory being filled with 0 bytes on the heap. This is an experimental API. ```APIDOC ## Box::try_new_zeroed ### Description Constructs a new `Box` with uninitialized contents, with the memory being filled with `0` bytes on the heap. This is a nightly-only experimental API. ### Method Associated function ### Parameters None ### Response - **Result>, AllocError>** - Ok containing the Box if allocation succeeds, or an Err containing an AllocError if it fails. ### Example ```rust #![feature(allocator_api)] let zero = Box::::try_new_zeroed()?; let zero = unsafe { zero.assume_init() }; assert_eq!(*zero, 0); ``` ``` -------------------------------- ### Box::new_zeroed_in Source: https://docs.rs/pingora-error/0.8.0/pingora_error/type.BError.html Constructs a new Box with uninitialized contents, with the memory being filled with 0 bytes in the provided allocator. This is a nightly-only experimental API. ```APIDOC ## pub fn new_zeroed_in(alloc: A) -> Box, A> ### Description Constructs a new `Box` with uninitialized contents, with the memory being filled with `0` bytes in the provided allocator. ### Method Associated function (call as `Box::::new_zeroed_in(allocator)`) ### Parameters * **alloc** (A) - The allocator to use. ### Returns * **Box, A>** - A Box containing zeroed memory. ### Examples ```rust #![feature(allocator_api)] use std::alloc::System; let zero = Box::::new_zeroed_in(System); let zero = unsafe { zero.assume_init() }; ``` ``` -------------------------------- ### impl Fn for Box Source: https://docs.rs/pingora-error/0.8.0/pingora_error/type.BError.html Allows calling a boxed function with arguments. ```APIDOC ## extern "rust-call" fn call( &self, args: Args, ) -> as FnOnce>::Output ### Description Performs the call operation. This is a nightly-only experimental API. ### Method call ### Parameters - `args` (Args): The arguments to pass to the function. ### Returns - ` as FnOnce>::Output`: The output of the function call. ``` -------------------------------- ### Create a Box with Box::new Source: https://docs.rs/pingora-error/0.8.0/pingora_error/type.BError.html Allocates memory on the heap and places a value into it. No allocation occurs for zero-sized types. ```rust let five = Box::new(5); ``` -------------------------------- ### try_clone_from_ref_in Source: https://docs.rs/pingora-error/0.8.0/pingora_error/type.BError.html Allocates memory in the given allocator then clones src into it, returning an error if allocation fails. This doesn’t actually allocate if src is zero-sized. This is a nightly-only experimental API. ```APIDOC ## pub fn try_clone_from_ref_in(src: &T, alloc: A) -> Result, AllocError> ### Description Allocates memory in the given allocator then clones `src` into it, returning an error if allocation fails. ### Parameters #### Path Parameters - **src** (&T) - Required - The value to clone. - **alloc** (A) - Required - The allocator to use for memory allocation. ### Response #### Success Response - **Box** - A new Box containing a clone of `src`. #### Error Response - **AllocError** - Returned if the memory allocation fails. ``` -------------------------------- ### impl FnOnce for Box Source: https://docs.rs/pingora-error/0.8.0/pingora_error/type.BError.html Allows consuming calls to a boxed function with arguments. ```APIDOC ## extern "rust-call" fn call_once( self, args: Args, ) -> as FnOnce>::Output ### Description Performs the call operation once, consuming the boxed function. This is a nightly-only experimental API. ### Method call_once ### Parameters - `args` (Args): The arguments to pass to the function. ### Returns - ` as FnOnce>::Output`: The output of the function call. ``` -------------------------------- ### Box::new_in Source: https://docs.rs/pingora-error/0.8.0/pingora_error/type.BError.html Allocates memory using the provided allocator and places the given value into it. This is a nightly-only experimental API. ```APIDOC ## pub fn new_in(x: T, alloc: A) -> Box ### Description Allocates memory in the given allocator then places `x` into it. This doesn’t actually allocate if `T` is zero-sized. ### Method Associated function (call as `Box::new_in(value, allocator)`) ### Parameters * **x** (T) - The value to place in the Box. * **alloc** (A) - The allocator to use. ### Returns * **Box** - A Box containing the value, allocated using the specified allocator. ### Examples ```rust #![feature(allocator_api)] use std::alloc::System; let five = Box::new_in(5, System); ``` ``` -------------------------------- ### fn chain(self, next: R) -> Chain Source: https://docs.rs/pingora-error/0.8.0/pingora_error/type.BError.html Creates an adapter which will chain this stream with another `Read` stream. Reads will be made from `self` until EOF, then from `next`. ```APIDOC ## fn chain(self, next: R) -> Chain ### Description Creates an adapter that chains this `Read` stream with another `Read` stream. Data is read from the first stream until it reaches EOF, after which data is read from the second stream. ### Parameters - `next` (*R*): The next `Read` stream to chain. ### Returns - `Chain`: A `Chain` adapter that combines two `Read` streams. ``` -------------------------------- ### fn write_fmt(&mut self, fmt: Arguments<'_>) -> Result<(), Error> Source: https://docs.rs/pingora-error/0.8.0/pingora_error/type.BError.html Writes a formatted string into this writer, returning any error encountered. ```APIDOC ## fn write_fmt(&mut self, fmt: Arguments<'_>) -> Result<(), Error> ### Description Writes a formatted string, similar to `println!` or `write!`, to the writer. ### Parameters - `fmt` (*Arguments<'_>*): The formatted string arguments to write. ### Returns - `Result<(), Error>`: Returns `Ok(())` on success. Returns an `Error` if the write operation fails. ``` -------------------------------- ### fn by_ref(&mut self) -> &mut Self Source: https://docs.rs/pingora-error/0.8.0/pingora_error/type.BError.html Creates a “by reference” adapter for this instance of `Read`. This allows borrowing the reader without consuming it. ```APIDOC ## fn by_ref(&mut self) -> &mut Self ### Description Creates a "by reference" adapter for this instance of `Read`. This adapter allows you to use the `Read` methods on a mutable reference to the reader, without consuming the original reader. ### Returns - `&mut Self`: A mutable reference to a `Read` adapter. ``` -------------------------------- ### impl Write for Box Source: https://docs.rs/pingora-error/0.8.0/pingora_error/type.BError.html Provides `Write` functionality for `Box` where `W` implements `Write`. ```APIDOC ## impl Write for Box ### Description This implementation block provides `Write` trait methods for `Box` types, where `W` itself is a type that implements the `Write` trait. This allows writing operations on boxed writers. ``` -------------------------------- ### Clone a value into a Box with Box::clone_from_ref (nightly) Source: https://docs.rs/pingora-error/0.8.0/pingora_error/type.BError.html Allocates memory on the heap and clones the source value into it. No allocation occurs for zero-sized types. This is a nightly-only experimental API. ```rust #![feature(clone_from_ref)] let hello: Box = Box::clone_from_ref("hello"); ``` -------------------------------- ### Manually Create Box from NonNull Pointer Source: https://docs.rs/pingora-error/0.8.0/pingora_error/type.BError.html Manually creates a Box from scratch using the system allocator and a NonNull pointer. This involves allocating memory, casting, writing the value, and then constructing the Box. ```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); } ``` -------------------------------- ### Construct Box with Zeroed Contents in Allocator Source: https://docs.rs/pingora-error/0.8.0/pingora_error/type.BError.html Constructs a new Box with uninitialized contents, filling the memory with 0 bytes using the provided allocator. Returns an error if the allocation fails. This is a nightly-only experimental API. ```rust #![feature(allocator_api)] use std::alloc.System; let zero = Box::::try_new_zeroed_in(System)?; let zero = unsafe { zero.assume_init() }; assert_eq!(*zero, 0); ``` -------------------------------- ### clone_from_ref_in Source: https://docs.rs/pingora-error/0.8.0/pingora_error/type.BError.html Allocates memory in the given allocator then clones src into it. This doesn’t actually allocate if src is zero-sized. This is a nightly-only experimental API. ```APIDOC ## pub fn clone_from_ref_in(src: &T, alloc: A) -> Box ### Description Allocates memory in the given allocator then clones `src` into it. ### Parameters #### Path Parameters - **src** (&T) - Required - The value to clone. - **alloc** (A) - Required - The allocator to use for memory allocation. ### Response #### Success Response - **Box** - A new Box containing a clone of `src`. ``` -------------------------------- ### Box::new Source: https://docs.rs/pingora-error/0.8.0/pingora_error/type.BError.html Allocates memory on the heap and places a value into it. This method does not allocate if the type is zero-sized. ```APIDOC ## Box::new ### Description Allocates memory on the heap and then places `x` into it. This doesn’t actually allocate if `T` is zero-sized. ### Method Associated function ### Parameters - **x**: T - The value to place in the Box. ### Response - **Box** - A Box containing the value `x`. ### Example ```rust let five = Box::new(5); ``` ``` -------------------------------- ### Attempt to clone a value into a Box with Box::try_clone_from_ref (nightly) Source: https://docs.rs/pingora-error/0.8.0/pingora_error/type.BError.html Allocates memory on the heap and clones the source value into it, returning an error if allocation fails. No allocation occurs for zero-sized types. This is a nightly-only experimental API. ```rust #![feature(clone_from_ref)] #![feature(allocator_api)] let hello: Box = Box::try_clone_from_ref("hello")?; ``` -------------------------------- ### Clone Implementation for Box Source: https://docs.rs/pingora-error/0.8.0/pingora_error/type.BError.html Provides methods for cloning Box instances. The clone method creates a new box with a clone of the contents, while clone_from copies contents without a new allocation. ```APIDOC ## fn clone(&self) -> Box ### Description Returns a new box with a `clone()` of this box’s contents. ### Examples ```rust let x = Box::new(5); let y = x.clone(); // The value is the same assert_eq!(x, y); // But they are unique objects assert_ne!(&*x as *const i32, &*y as *const i32); ``` ``` ```APIDOC ## fn clone_from(&mut self, source: &Box) ### Description Copies `source`’s contents into `self` without creating a new allocation. ### Examples ```rust let x = Box::new(5); let mut y = Box::new(10); let yp: *const i32 = &*y; y.clone_from(&x); // The value is the same assert_eq!(x, y); // And no allocation occurred assert_eq!(yp, &*y); ``` ``` -------------------------------- ### Attempting to Create a Box with Uninitialized Contents in a Specific Allocator Source: https://docs.rs/pingora-error/0.8.0/pingora_error/type.BError.html Use Box::try_new_uninit_in to attempt creating a Box with uninitialized contents using a specified allocator. It returns a Result, yielding an AllocError on allocation failure. Deferred initialization is supported. ```rust #![feature(allocator_api)] use std::alloc.System; let mut five = Box::::try_new_uninit_in(System)?; // Deferred initialization: five.write(5); let five = unsafe { five.assume_init() }; assert_eq!(*five, 5); ``` -------------------------------- ### Cloning from another Box Source: https://docs.rs/pingora-error/0.8.0/pingora_error/type.BError.html Shows how to copy the contents of one Box into another using clone_from, without allocating new memory. This is useful for updating the contents of an existing box. ```rust let x = Box::new(5); let mut y = Box::new(10); let yp: *const i32 = &*y; y.clone_from(&x); // The value is the same assert_eq!(x, y); // And no allocation occurred assert_eq!(yp, &*y); ``` -------------------------------- ### Implement From for T Source: https://docs.rs/pingora-error/0.8.0/pingora_error/enum.ErrorType.html Provides the `from` method, which returns the argument unchanged. This is a basic identity conversion. ```rust impl From for T ``` -------------------------------- ### Allocate Zeroed Memory with Allocator API Source: https://docs.rs/pingora-error/0.8.0/pingora_error/type.BError.html Behaves like `allocate`, but also ensures that the returned memory is zero-initialized. This is a nightly-only experimental API. ```rust use std::alloc::{Layout, AllocError, NonNull}; // Assuming 'self' is an instance of Box implementing Allocator // let result: Result, AllocError> = self.allocate_zeroed(layout); ```