Skip to main content

Report

Struct Report 

pub struct Report<C>
where C: ?Sized,
{ /* private fields */ }
Expand description

Contains a [Frame] stack consisting of Error contexts and attachments.

Attachments can be added by using attach_opaque(). The [Frame] stack can be iterated by using frames().

When creating a Report by using new(), the passed Error context is used to set the current context on the Report. To provide a new one, use change_context().

Attachments, and objects provided by a Error context, are directly retrievable by calling request_ref() or request_value().

§Formatting

Report implements Display and Debug. When utilizing the Display implementation, the current context of the Report is printed, e.g. println!("{report}"). For the alternate Display output ("{:#}"), all Error contexts are printed. To print the full stack of Error contexts and attachments, use the Debug implementation ("{:?}"). To customize the output of the attachments in the Debug output, please see the error_stack::fmt module.

Please see the examples below for more information.

§Multiple Errors

Report comes in two variants: Report<C> which represents a single error context, and Report<[C]> which can represent multiple error contexts. To combine multiple errors, first convert a Report<C> to Report<[C]> using expand(), then use push() to add additional errors. This allows for representing complex error scenarios with multiple related simultaneous errors.

§Backtrace and SpanTrace

Report is able to provide a Backtrace and a [SpanTrace], which can be retrieved by calling request_ref::<Backtrace>() or request_ref::<SpanTrace>() (downcast_ref::<SpanTrace>() on stable) respectively. If the root context provides a Backtrace or a [SpanTrace], those are returned, otherwise, if configured, an attempt is made to capture them when creating a Report. To enable capturing of the backtrace, make sure RUST_BACKTRACE or RUST_LIB_BACKTRACE is set according to the Backtrace documentation. To enable capturing of the span trace, an ErrorLayer has to be enabled. Please also see the Feature Flags section. A single Report can have multiple Backtraces and [SpanTrace]s, depending on the amount of related errors the Report consists of. Therefore it isn’t guaranteed that request_ref() will only ever return a single Backtrace or [SpanTrace].

§Examples

§Provide a context for an error

use error_stack::ResultExt;

let config_path = "./path/to/config.file";
let content = std::fs::read_to_string(config_path)
    .attach_with(|| format!("failed to read config file {config_path:?}"))?;

...

§Enforce a context for an error

use std::{error::Error, fmt, path::{Path, PathBuf}};

use error_stack::{Report, ResultExt};

#[derive(Debug)]
enum RuntimeError {
    InvalidConfig(PathBuf),
    ...
}

#[derive(Debug)]
enum ConfigError {
    IoError,
    ...
}

impl fmt::Display for RuntimeError {
    ...
}
impl fmt::Display for ConfigError {
    ...
}

impl Error for RuntimeError {}
impl Error for ConfigError {}

fn read_config(path: impl AsRef<Path>) -> Result<String, Report<ConfigError>> {
    std::fs::read_to_string(path.as_ref()).change_context(ConfigError::IoError)
}

fn main() -> Result<(), Report<RuntimeError>> {
    let config_path = "./path/to/config.file";
    let config = read_config(config_path)
            .change_context_lazy(|| RuntimeError::InvalidConfig(PathBuf::from(config_path)))?;

    ...
}

§Formatting

For the example from above, the report could be formatted as follows:

If the Display implementation of Report will be invoked, this will print something like:


If the alternate Display implementation of Report is invoked ({report:#}), this will print something like:


The Debug implementation of Report will print something like:


§Get the attached Backtrace and [SpanTrace]:

use error_stack::{ResultExt, Report};

let config_path = "./path/to/config.file";
let content = std::fs::read_to_string(config_path)
    .attach_with(|| format!("failed to read config file {config_path:?}"));

let content = match content {
    Err(err) => {
        for backtrace in err.request_ref::<std::backtrace::Backtrace>() {
            println!("backtrace: {backtrace}");
        }

        for span_trace in err.request_ref::<tracing_error::SpanTrace>() {
            println!("span trace: {span_trace}")
        }

        return Err(err)
    }

    Ok(ok) => ok
};

...

Implementations§

§

impl<C> Report<C>

pub fn new(context: C) -> Report<C>
where C: Error + Send + Sync + 'static,

Creates a new Report<Context> from a provided scope.

If context does not provide Backtrace/[SpanTrace] then this attempts to capture them directly. Please see the Backtrace and SpanTrace section of the Report documentation for more information.

pub fn expand(self) -> Report<[C]>

Converts a Report with a single context into a Report with multiple contexts.

This function allows for the transformation of a Report<C> into a Report<[C]>, enabling the report to potentially hold multiple current contexts of the same type.

§Example
use error_stack::Report;

#[derive(Debug)]
struct SystemFailure;

impl std::fmt::Display for SystemFailure {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str("System failure occured")
    }
}

impl core::error::Error for SystemFailure {}

// Type annotations are used here to illustrate the types used, these are not required
let failure: Report<SystemFailure> = Report::new(SystemFailure);
let mut failures: Report<[SystemFailure]> = failure.expand();

assert_eq!(failures.current_frames().len(), 1);

let another_failure = Report::new(SystemFailure);
failures.push(another_failure);

assert_eq!(failures.current_frames().len(), 2);

pub fn current_frame(&self) -> &Frame

Returns the direct current frames of this report.

To get an iterator over the topological sorting of all frames refer to frames().

This is not the same as Report::current_context, this function gets the underlying frames that make up this report, while Report::current_context traverses the stack of frames to find the current context. A Report and be made up of multiple [Frame]s, which stack on top of each other. Considering PrintableA<PrintableA<Context>>, Report::current_frame will return the “outer” layer PrintableA, while Report::current_context will return the underlying Error (the current type parameter of this Report).

A report can be made up of multiple stacks of frames and builds a “group” of them, this can be achieved through first calling Report::expand and then either using Extend or Report::push.

pub fn current_context(&self) -> &C
where C: Send + Sync + 'static,

Returns the current context of the Report.

If the user want to get the latest context, current_context can be called. If the user wants to handle the error, the context can then be used to directly access the context’s type. This is only possible for the latest context as the Report does not have multiple generics as this would either require variadic generics or a workaround like tuple-list.

This is one disadvantage of the library in comparison to plain Errors, as in these cases, all context types are known.

§Example
use std::io;

fn read_file(path: impl AsRef<Path>) -> Result<String, Report<io::Error>> {
    ...
}

let report = read_file("test.txt").unwrap_err();
let io_error = report.current_context();
assert_eq!(io_error.kind(), io::ErrorKind::NotFound);

pub fn into_error(self) -> impl Error + Send + Sync + 'static
where C: 'static,

Converts this Report to an Error.

pub fn as_error(&self) -> &(impl Error + Send + Sync + 'static)
where C: 'static,

Returns this Report as an Error.

§

impl<C> Report<C>
where C: ?Sized,

pub fn attach<A>(self, attachment: A) -> Report<C>
where A: Attachment,

Adds additional (printable) information to the [Frame] stack.

This behaves like attach_opaque() but the display implementation will be called when printing the Report.

Note: attach_opaque() will be deprecated when specialization is stabilized and it becomes possible to merge these two methods.

§Example
use core::fmt;
use std::fs;

use error_stack::ResultExt;

#[derive(Debug)]
pub struct Suggestion(&'static str);

impl fmt::Display for Suggestion {
    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt.write_str(self.0)
    }
}

let error = fs::read_to_string("config.txt")
    .attach(Suggestion("better use a file which exists next time!"));
let report = error.unwrap_err();
let suggestion = report.request_ref::<Suggestion>().next().unwrap();

assert_eq!(suggestion.0, "better use a file which exists next time!");

pub fn attach_opaque<A>(self, attachment: A) -> Report<C>
where A: OpaqueAttachment,

Adds additional information to the [Frame] stack.

This behaves like attach() but will not be shown when printing the Report. To benefit from seeing attachments in normal error outputs, use attach().

Note: This will be deprecated in favor of attach() when specialization is stabilized it becomes possible to merge these two methods.

pub fn change_context<T>(self, context: T) -> Report<T>
where T: Error + Send + Sync + 'static,

Add a new Error object to the top of the [Frame] stack, changing the type of the Report.

Please see the Error documentation for more information.

pub fn frames(&self) -> Frames<'_>

Returns an iterator over the [Frame] stack of the report.

pub fn frames_mut( &mut self, visitor: impl FnMut(&mut Frame) -> ControlFlow<()>, ) -> ControlFlow<()>

Visits every [Frame] of the report mutably, in the same order as frames().

Returning ControlFlow::Break from visitor stops the traversal early. The break is propagated to the caller, a full traversal returns ControlFlow::Continue.

This is deliberately not an Iterator: an iterator over &mut Frame hands out references whose lifetimes are independent of each other, so a frame and one of its sources (reachable via [Frame::sources_mut]) could be borrowed mutably at the same time. Scoping mutable access to a visitor rules that out.

§Example
let mut report = read_file("test.txt").unwrap_err();
let flow = report.frames_mut(|frame| {
    if let Some(io_error) = frame.downcast_mut::<io::Error>() {
        *io_error = io::Error::from(io::ErrorKind::Other);
        return ControlFlow::Break(());
    }
    ControlFlow::Continue(())
});
assert!(flow.is_break());

pub fn contains<T>(&self) -> bool
where T: Send + Sync + 'static,

Returns if T is the type held by any frame inside of the report.

T could either be an attachment or a Error context.

§Example
fn read_file(path: impl AsRef<Path>) -> Result<String, Report<io::Error>> {
    ...
}

let report = read_file("test.txt").unwrap_err();
assert!(report.contains::<io::Error>());

pub fn downcast_ref<T>(&self) -> Option<&T>
where T: Send + Sync + 'static,

Searches the frame stack for a context provider T and returns the most recent context found.

T can either be an attachment or a new Error context.

§Example
use std::io;

fn read_file(path: impl AsRef<Path>) -> Result<String, Report<io::Error>> {
    ...
}

let report = read_file("test.txt").unwrap_err();
let io_error = report.downcast_ref::<io::Error>().unwrap();
assert_eq!(io_error.kind(), io::ErrorKind::NotFound);

pub fn downcast_mut<T>(&mut self) -> Option<&mut T>
where T: Send + Sync + 'static,

Searches the frame stack for an instance of type T, returning the most recent one found.

T can either be an attachment or a new Error context.

§

impl<C> Report<[C]>

pub fn current_frames(&self) -> &[Frame]

Returns the direct current frames of this report.

To get an iterator over the topological sorting of all frames refer to frames().

This is not the same as Report::current_context, this function gets the underlying frames that make up this report, while Report::current_context traverses the stack of frames to find the current context. A Report and be made up of multiple [Frame]s, which stack on top of each other. Considering PrintableA<PrintableA<Context>>, Report::current_frames will return the “outer” layer PrintableA, while Report::current_context will return the underlying Error (the current type parameter of this Report).

Using Extend, push() and append(), a Report can additionally be made up of multiple stacks of frames and builds a “group” of them, therefore this function returns a slice instead, while Report::current_context only returns a single reference.

pub fn push(&mut self, report: Report<C>)

Pushes a new context to the Report.

This function adds a new [Frame] to the current frames with the frame from the given Report.

§Example
use std::{fmt, path::Path};

use error_stack::{Report, ResultExt};

#[derive(Debug)]
struct IoError;

impl fmt::Display for IoError {
            ...
}


fn read_config(path: impl AsRef<Path>) -> Result<String, Report<IoError>> {
    std::fs::read_to_string(path.as_ref())
        .change_context(IoError)
}

let mut error1 = read_config("config.txt").unwrap_err().expand();
let error2 = read_config("config2.txt").unwrap_err();
let error3 = read_config("config3.txt").unwrap_err();

error1.push(error2);
error1.push(error3);

pub fn append(&mut self, report: Report<[C]>)

Appends the frames from another Report to this one.

This method combines the frames of the current Report with those of the provided Report, effectively merging the two error reports.

§Example
use std::{fmt, path::Path};

use error_stack::{Report, ResultExt};

#[derive(Debug)]
struct IoError;

impl fmt::Display for IoError {
            ...
}


fn read_config(path: impl AsRef<Path>) -> Result<String, Report<IoError>> {
    std::fs::read_to_string(path.as_ref())
        .change_context(IoError)
}

let mut error1 = read_config("config.txt").unwrap_err().expand();
let error2 = read_config("config2.txt").unwrap_err();
let mut error3 = read_config("config3.txt").unwrap_err().expand();

error1.push(error2);
error3.append(error1);

pub fn current_contexts(&self) -> impl Iterator<Item = &C>
where C: Send + Sync + 'static,

Returns an iterator over the current contexts of the Report.

This method is similar to current_context, but instead of returning a single context, it returns an iterator over all contexts in the Report.

The order of the contexts should not be relied upon, as it is not guaranteed to be stable.

§Example
use std::io;

fn read_file(path: impl AsRef<Path>) -> Result<String, Report<io::Error>> {
    ...
}

let mut a = read_file("test.txt").unwrap_err().expand();
let b = read_file("test2.txt").unwrap_err();

a.push(b);

let io_error = a.current_contexts();
assert_eq!(io_error.count(), 2);
§

impl Report<()>

pub fn set_charset(charset: Charset)

Sets the charset preference.

The value defaults to [Charset::Utf8].

§Example
use std::io::{Error, ErrorKind};

use error_stack::{Report, IntoReport};
use error_stack::fmt::{Charset};

struct Suggestion(&'static str);

Report::install_debug_hook::<Suggestion>(|Suggestion(value), context| {
    match context.charset() {
        Charset::Utf8 => context.push_body(format!("📝 {value}")),
        Charset::Ascii => context.push_body(format!("suggestion: {value}"))
    };
});

let report =
    Error::from(ErrorKind::InvalidInput).into_report().attach_opaque(Suggestion("oh no, try again"));

Report::set_charset(Charset::Utf8);
println!("{report:?}");

Report::set_charset(Charset::Ascii);
println!("{report:?}");

Which will result in something like:


§

impl Report<()>

pub fn set_color_mode(mode: ColorMode)

Sets the color mode preference.

If no [ColorMode] is set, it defaults to [ColorMode::Emphasis].

§Example
use std::io::{Error, ErrorKind};
use owo_colors::OwoColorize;

use error_stack::{Report, IntoReport};
use error_stack::fmt::ColorMode;

struct Suggestion(&'static str);

Report::install_debug_hook::<Suggestion>(|Suggestion(value), context| {
    let body = format!("suggestion: {value}");
    match context.color_mode() {
        ColorMode::Color => context.push_body(body.green().to_string()),
        ColorMode::Emphasis => context.push_body(body.italic().to_string()),
        ColorMode::None => context.push_body(body)
    };
});

let report =
    Error::from(ErrorKind::InvalidInput).into_report().attach_opaque(Suggestion("oh no, try again"));

Report::set_color_mode(ColorMode::None);
println!("{report:?}");

Report::set_color_mode(ColorMode::Emphasis);
println!("{report:?}");

Report::set_color_mode(ColorMode::Color);
println!("{report:?}");

Which will result in something like:



§

impl Report<()>

pub fn install_debug_hook<T>( hook: impl Fn(&T, &mut HookContext<T>) + Send + Sync + 'static, )
where T: Send + Sync + 'static,

Can be used to globally set a Debug format hook, for a specific type T.

This hook will be called on every Debug call, if an attachment with the same type has been found.

§Examples
use std::io::{Error, ErrorKind};

use error_stack::{
    Report, IntoReport,
};

struct Suggestion(&'static str);

Report::install_debug_hook::<Suggestion>(|value, context| {
    context.push_body(format!("suggestion: {}", value.0));
});

let report =
    Error::from(ErrorKind::InvalidInput).into_report().attach_opaque(Suggestion("oh no, try again"));

println!("{report:?}");

Which will result in something like:


This example showcases the ability of hooks to be invoked for values provided via the Provider API using Error::provide.

#![feature(error_generic_member_access)]

use core::error::{Request, Error};
use core::fmt;
use error_stack::{Report, IntoReport};

struct Suggestion(&'static str);

#[derive(Debug)]
struct ErrorCode(u64);


#[derive(Debug)]
struct UserError {
    code: ErrorCode
}

impl fmt::Display for UserError {
    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt.write_str("invalid user input")
    }
}

impl Error for UserError {
 fn provide<'a>(&'a self, req: &mut Request<'a>) {
   req.provide_value(Suggestion("try better next time!"));
   req.provide_ref(&self.code);
 }
}

Report::install_debug_hook::<Suggestion>(|Suggestion(value), context| {
    context.push_body(format!("suggestion: {value}"));
});
Report::install_debug_hook::<ErrorCode>(|ErrorCode(value), context| {
    context.push_body(format!("error code: {value}"));
});

let report = UserError {code: ErrorCode(420)}.into_report();

println!("{report:?}");

Which will result in something like:


error-stack comes with some built-in hooks which can be overwritten. This is useful if you want to change the output of the built-in hooks, or if you want to add additional information to the output. For example, you can override the built-in hook for Location to hide the file path:

use std::{
    io::{Error, ErrorKind},
    panic::Location,
};

use error_stack::IntoReport;

error_stack::Report::install_debug_hook::<Location>(|_location, _context| {
    // Intentionally left empty so nothing will be printed
});

let report = Error::from(ErrorKind::InvalidInput).into_report();

println!("{report:?}");

Which will result in something like:


Trait Implementations§

§

impl<C> Debug for Report<C>
where C: ?Sized,

§

fn fmt(&self, fmt: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
§

impl<C> Display for Report<C>
where C: ?Sized,

§

fn fmt(&self, fmt: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
§

impl<C> Extend<Report<[C]>> for Report<[C]>

§

fn extend<T>(&mut self, iter: T)
where T: IntoIterator<Item = Report<[C]>>,

Extends a collection with the contents of an iterator. Read more
Source§

fn extend_one(&mut self, item: A)

🔬This is a nightly-only experimental API. (extend_one)
Extends a collection with exactly one element.
Source§

fn extend_reserve(&mut self, additional: usize)

🔬This is a nightly-only experimental API. (extend_one)
Reserves capacity in a collection for the given number of additional elements. Read more
§

impl<C> Extend<Report<C>> for Report<[C]>

§

fn extend<T>(&mut self, iter: T)
where T: IntoIterator<Item = Report<C>>,

Extends a collection with the contents of an iterator. Read more
Source§

fn extend_one(&mut self, item: A)

🔬This is a nightly-only experimental API. (extend_one)
Extends a collection with exactly one element.
Source§

fn extend_reserve(&mut self, additional: usize)

🔬This is a nightly-only experimental API. (extend_one)
Reserves capacity in a collection for the given number of additional elements. Read more
§

impl<C> From<C> for Report<C>
where C: Error + Send + Sync + 'static,

§

fn from(context: C) -> Report<C>

Converts to this type from the input type.
§

impl<C> From<Report<C>> for Box<dyn Error>
where C: 'static,

§

fn from(report: Report<C>) -> Box<dyn Error>

Converts to this type from the input type.
§

impl<C> From<Report<C>> for Box<dyn Error + Send>
where C: 'static,

§

fn from(report: Report<C>) -> Box<dyn Error + Send>

Converts to this type from the input type.
§

impl<C> From<Report<C>> for Box<dyn Error + Sync + Send>
where C: 'static,

§

fn from(report: Report<C>) -> Box<dyn Error + Sync + Send>

Converts to this type from the input type.
§

impl<C> From<Report<C>> for Box<dyn Error + Sync>
where C: 'static,

§

fn from(report: Report<C>) -> Box<dyn Error + Sync>

Converts to this type from the input type.
§

impl<C> From<Report<C>> for Report<[C]>

§

fn from(report: Report<C>) -> Report<[C]>

Converts to this type from the input type.
§

impl<C> FromIterator<Report<[C]>> for Option<Report<[C]>>

§

fn from_iter<T>(iter: T) -> Option<Report<[C]>>
where T: IntoIterator<Item = Report<[C]>>,

Creates a value from an iterator. Read more
§

impl<C> FromIterator<Report<C>> for Option<Report<[C]>>

§

fn from_iter<T>(iter: T) -> Option<Report<[C]>>
where T: IntoIterator<Item = Report<C>>,

Creates a value from an iterator. Read more
§

impl<C> IntoReport for Report<C>
where C: ?Sized,

§

type Context = C

The context type that will be used in the resulting Report.
§

fn into_report(self) -> Report<<Report<C> as IntoReport>::Context>

Converts this value into a Report.
§

impl<C> Termination for Report<C>

Available on crate feature std only.
§

fn report(self) -> ExitCode

Is called to get the representation of the value as status code. This status code is returned to the operating system.

Auto Trait Implementations§

§

impl<C> Freeze for Report<C>
where C: ?Sized,

§

impl<C> !RefUnwindSafe for Report<C>

§

impl<C> Send for Report<C>
where C: ?Sized,

§

impl<C> Sync for Report<C>
where C: ?Sized,

§

impl<C> Unpin for Report<C>
where C: ?Sized,

§

impl<C> UnsafeUnpin for Report<C>
where C: ?Sized,

§

impl<C> !UnwindSafe for Report<C>

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

impl<T, U> AsBindGroupShaderType<U> for T
where U: ShaderType, &'a T: for<'a> Into<U>,

§

fn as_bind_group_shader_type(&self, _images: &RenderAssets<GpuImage>) -> U

Return the T [ShaderType] for self. When used in [AsBindGroup] derives, it is safe to assume that all images in self exist.
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
§

impl<T> ByRef<T> for T

§

fn by_ref(&self) -> &T

§

impl<T> Downcast<T> for T

§

fn downcast(&self) -> &T

§

impl<T> Downcast for T
where T: Any,

§

fn into_any(self: Box<T>) -> Box<dyn Any>

Converts Box<dyn Trait> (where Trait: Downcast) to Box<dyn Any>, which can then be downcast into Box<dyn ConcreteType> where ConcreteType implements Trait.
§

fn into_any_rc(self: Rc<T>) -> Rc<dyn Any>

Converts Rc<Trait> (where Trait: Downcast) to Rc<Any>, which can then be further downcast into Rc<ConcreteType> where ConcreteType implements Trait.
§

fn as_any(&self) -> &(dyn Any + 'static)

Converts &Trait (where Trait: Downcast) to &Any. This is needed since Rust cannot generate &Any’s vtable from &Trait’s.
§

fn as_any_mut(&mut self) -> &mut (dyn Any + 'static)

Converts &mut Trait (where Trait: Downcast) to &Any. This is needed since Rust cannot generate &mut Any’s vtable from &mut Trait’s.
§

impl<T> Downcast for T
where T: Any,

§

fn into_any(self: Box<T>) -> Box<dyn Any>

Convert Box<dyn Trait> (where Trait: Downcast) to Box<dyn Any>. Box<dyn Any> can then be further downcast into Box<ConcreteType> where ConcreteType implements Trait.
§

fn into_any_rc(self: Rc<T>) -> Rc<dyn Any>

Convert Rc<Trait> (where Trait: Downcast) to Rc<Any>. Rc<Any> can then be further downcast into Rc<ConcreteType> where ConcreteType implements Trait.
§

fn as_any(&self) -> &(dyn Any + 'static)

Convert &Trait (where Trait: Downcast) to &Any. This is needed since Rust cannot generate &Any’s vtable from &Trait’s.
§

fn as_any_mut(&mut self) -> &mut (dyn Any + 'static)

Convert &mut Trait (where Trait: Downcast) to &Any. This is needed since Rust cannot generate &mut Any’s vtable from &mut Trait’s.
§

impl<T> DowncastSend for T
where T: Any + Send,

§

fn into_any_send(self: Box<T>) -> Box<dyn Any + Send>

Converts Box<Trait> (where Trait: DowncastSend) to Box<dyn Any + Send>, which can then be downcast into Box<ConcreteType> where ConcreteType implements Trait.
§

impl<T> DowncastSync for T
where T: Any + Send + Sync,

§

fn into_any_arc(self: Arc<T>) -> Arc<dyn Any + Sync + Send>

Convert Arc<Trait> (where Trait: Downcast) to Arc<Any>. Arc<Any> can then be further downcast into Arc<ConcreteType> where ConcreteType implements Trait.
§

impl<T> Fmt for T
where T: Display,

§

fn fg<C>(self, color: C) -> Foreground<Self>
where C: Into<Option<Color>>, Self: Display,

Give this value the specified foreground colour.
§

fn bg<C>(self, color: C) -> Background<Self>
where C: Into<Option<Color>>, Self: Display,

Give this value the specified background colour.
Source§

impl<T> From<!> for T

Source§

fn from(t: !) -> T

Converts to this type from the input type.
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

§

impl<S> FromSample<S> for S

§

fn from_sample_(s: S) -> S

§

impl<T, W> HasTypeWitness<W> for T
where W: MakeTypeWitness<Arg = T>, T: ?Sized,

§

const WITNESS: W = W::MAKE

A constant of the type witness
§

impl<T> Identity for T
where T: ?Sized,

§

const TYPE_EQ: TypeEq<T, <T as Identity>::Type> = TypeEq::NEW

Proof that Self is the same type as Self::Type, provides methods for casting between Self and Self::Type.
§

type Type = T

The same type as Self, used to emulate type equality bounds (T == U) with associated type equality constraints (T: Identity<Type = U>).
§

impl<T> Instrument for T

§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an Instrumented wrapper. Read more
§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
§

impl<'src, T> IntoMaybe<'src, T> for T
where T: 'src,

§

type Proj<U: 'src> = U

§

fn map_maybe<R>( self, _f: impl FnOnce(&'src T) -> &'src R, g: impl FnOnce(T) -> R, ) -> <T as IntoMaybe<'src, T>>::Proj<R>
where R: 'src,

§

impl<T> IntoResult<T> for T

§

fn into_result(self) -> Result<T, RunSystemError>

Converts this type into the system output type.
§

impl<A> Is for A
where A: Any,

§

fn is<T>() -> bool
where T: Any,

Checks if the current type “is” another type, using a TypeId equality comparison. This is most useful in the context of generic logic. Read more
§

impl<T> Paint for T
where T: ?Sized,

§

fn fg(&self, value: Color) -> Painted<&T>

Returns a styled value derived from self with the foreground set to value.

This method should be used rarely. Instead, prefer to use color-specific builder methods like red() and green(), which have the same functionality but are pithier.

§Example

Set foreground color to white using fg():

use yansi::{Paint, Color};

painted.fg(Color::White);

Set foreground color to white using white().

use yansi::Paint;

painted.white();
§

fn primary(&self) -> Painted<&T>

Returns self with the fg() set to [Color :: Primary].

§Example
println!("{}", value.primary());
§

fn fixed(&self, color: u8) -> Painted<&T>

Returns self with the fg() set to [Color :: Fixed].

§Example
println!("{}", value.fixed(color));
§

fn rgb(&self, r: u8, g: u8, b: u8) -> Painted<&T>

Returns self with the fg() set to [Color :: Rgb].

§Example
println!("{}", value.rgb(r, g, b));
§

fn black(&self) -> Painted<&T>

Returns self with the fg() set to [Color :: Black].

§Example
println!("{}", value.black());
§

fn red(&self) -> Painted<&T>

Returns self with the fg() set to [Color :: Red].

§Example
println!("{}", value.red());
§

fn green(&self) -> Painted<&T>

Returns self with the fg() set to [Color :: Green].

§Example
println!("{}", value.green());
§

fn yellow(&self) -> Painted<&T>

Returns self with the fg() set to [Color :: Yellow].

§Example
println!("{}", value.yellow());
§

fn blue(&self) -> Painted<&T>

Returns self with the fg() set to [Color :: Blue].

§Example
println!("{}", value.blue());
§

fn magenta(&self) -> Painted<&T>

Returns self with the fg() set to [Color :: Magenta].

§Example
println!("{}", value.magenta());
§

fn cyan(&self) -> Painted<&T>

Returns self with the fg() set to [Color :: Cyan].

§Example
println!("{}", value.cyan());
§

fn white(&self) -> Painted<&T>

Returns self with the fg() set to [Color :: White].

§Example
println!("{}", value.white());
§

fn bright_black(&self) -> Painted<&T>

Returns self with the fg() set to [Color :: BrightBlack].

§Example
println!("{}", value.bright_black());
§

fn bright_red(&self) -> Painted<&T>

Returns self with the fg() set to [Color :: BrightRed].

§Example
println!("{}", value.bright_red());
§

fn bright_green(&self) -> Painted<&T>

Returns self with the fg() set to [Color :: BrightGreen].

§Example
println!("{}", value.bright_green());
§

fn bright_yellow(&self) -> Painted<&T>

Returns self with the fg() set to [Color :: BrightYellow].

§Example
println!("{}", value.bright_yellow());
§

fn bright_blue(&self) -> Painted<&T>

Returns self with the fg() set to [Color :: BrightBlue].

§Example
println!("{}", value.bright_blue());
§

fn bright_magenta(&self) -> Painted<&T>

Returns self with the fg() set to [Color :: BrightMagenta].

§Example
println!("{}", value.bright_magenta());
§

fn bright_cyan(&self) -> Painted<&T>

Returns self with the fg() set to [Color :: BrightCyan].

§Example
println!("{}", value.bright_cyan());
§

fn bright_white(&self) -> Painted<&T>

Returns self with the fg() set to [Color :: BrightWhite].

§Example
println!("{}", value.bright_white());
§

fn bg(&self, value: Color) -> Painted<&T>

Returns a styled value derived from self with the background set to value.

This method should be used rarely. Instead, prefer to use color-specific builder methods like on_red() and on_green(), which have the same functionality but are pithier.

§Example

Set background color to red using fg():

use yansi::{Paint, Color};

painted.bg(Color::Red);

Set background color to red using on_red().

use yansi::Paint;

painted.on_red();
§

fn on_primary(&self) -> Painted<&T>

Returns self with the bg() set to [Color :: Primary].

§Example
println!("{}", value.on_primary());
§

fn on_fixed(&self, color: u8) -> Painted<&T>

Returns self with the bg() set to [Color :: Fixed].

§Example
println!("{}", value.on_fixed(color));
§

fn on_rgb(&self, r: u8, g: u8, b: u8) -> Painted<&T>

Returns self with the bg() set to [Color :: Rgb].

§Example
println!("{}", value.on_rgb(r, g, b));
§

fn on_black(&self) -> Painted<&T>

Returns self with the bg() set to [Color :: Black].

§Example
println!("{}", value.on_black());
§

fn on_red(&self) -> Painted<&T>

Returns self with the bg() set to [Color :: Red].

§Example
println!("{}", value.on_red());
§

fn on_green(&self) -> Painted<&T>

Returns self with the bg() set to [Color :: Green].

§Example
println!("{}", value.on_green());
§

fn on_yellow(&self) -> Painted<&T>

Returns self with the bg() set to [Color :: Yellow].

§Example
println!("{}", value.on_yellow());
§

fn on_blue(&self) -> Painted<&T>

Returns self with the bg() set to [Color :: Blue].

§Example
println!("{}", value.on_blue());
§

fn on_magenta(&self) -> Painted<&T>

Returns self with the bg() set to [Color :: Magenta].

§Example
println!("{}", value.on_magenta());
§

fn on_cyan(&self) -> Painted<&T>

Returns self with the bg() set to [Color :: Cyan].

§Example
println!("{}", value.on_cyan());
§

fn on_white(&self) -> Painted<&T>

Returns self with the bg() set to [Color :: White].

§Example
println!("{}", value.on_white());
§

fn on_bright_black(&self) -> Painted<&T>

Returns self with the bg() set to [Color :: BrightBlack].

§Example
println!("{}", value.on_bright_black());
§

fn on_bright_red(&self) -> Painted<&T>

Returns self with the bg() set to [Color :: BrightRed].

§Example
println!("{}", value.on_bright_red());
§

fn on_bright_green(&self) -> Painted<&T>

Returns self with the bg() set to [Color :: BrightGreen].

§Example
println!("{}", value.on_bright_green());
§

fn on_bright_yellow(&self) -> Painted<&T>

Returns self with the bg() set to [Color :: BrightYellow].

§Example
println!("{}", value.on_bright_yellow());
§

fn on_bright_blue(&self) -> Painted<&T>

Returns self with the bg() set to [Color :: BrightBlue].

§Example
println!("{}", value.on_bright_blue());
§

fn on_bright_magenta(&self) -> Painted<&T>

Returns self with the bg() set to [Color :: BrightMagenta].

§Example
println!("{}", value.on_bright_magenta());
§

fn on_bright_cyan(&self) -> Painted<&T>

Returns self with the bg() set to [Color :: BrightCyan].

§Example
println!("{}", value.on_bright_cyan());
§

fn on_bright_white(&self) -> Painted<&T>

Returns self with the bg() set to [Color :: BrightWhite].

§Example
println!("{}", value.on_bright_white());
§

fn attr(&self, value: Attribute) -> Painted<&T>

Enables the styling [Attribute] value.

This method should be used rarely. Instead, prefer to use attribute-specific builder methods like bold() and underline(), which have the same functionality but are pithier.

§Example

Make text bold using attr():

use yansi::{Paint, Attribute};

painted.attr(Attribute::Bold);

Make text bold using using bold().

use yansi::Paint;

painted.bold();
§

fn bold(&self) -> Painted<&T>

Returns self with the attr() set to [Attribute :: Bold].

§Example
println!("{}", value.bold());
§

fn dim(&self) -> Painted<&T>

Returns self with the attr() set to [Attribute :: Dim].

§Example
println!("{}", value.dim());
§

fn italic(&self) -> Painted<&T>

Returns self with the attr() set to [Attribute :: Italic].

§Example
println!("{}", value.italic());
§

fn underline(&self) -> Painted<&T>

Returns self with the attr() set to [Attribute :: Underline].

§Example
println!("{}", value.underline());

Returns self with the attr() set to [Attribute :: Blink].

§Example
println!("{}", value.blink());

Returns self with the attr() set to [Attribute :: RapidBlink].

§Example
println!("{}", value.rapid_blink());
§

fn invert(&self) -> Painted<&T>

Returns self with the attr() set to [Attribute :: Invert].

§Example
println!("{}", value.invert());
§

fn conceal(&self) -> Painted<&T>

Returns self with the attr() set to [Attribute :: Conceal].

§Example
println!("{}", value.conceal());
§

fn strike(&self) -> Painted<&T>

Returns self with the attr() set to [Attribute :: Strike].

§Example
println!("{}", value.strike());
§

fn quirk(&self, value: Quirk) -> Painted<&T>

Enables the yansi [Quirk] value.

This method should be used rarely. Instead, prefer to use quirk-specific builder methods like mask() and wrap(), which have the same functionality but are pithier.

§Example

Enable wrapping using .quirk():

use yansi::{Paint, Quirk};

painted.quirk(Quirk::Wrap);

Enable wrapping using wrap().

use yansi::Paint;

painted.wrap();
§

fn mask(&self) -> Painted<&T>

Returns self with the quirk() set to [Quirk :: Mask].

§Example
println!("{}", value.mask());
§

fn wrap(&self) -> Painted<&T>

Returns self with the quirk() set to [Quirk :: Wrap].

§Example
println!("{}", value.wrap());
§

fn linger(&self) -> Painted<&T>

Returns self with the quirk() set to [Quirk :: Linger].

§Example
println!("{}", value.linger());
§

fn clear(&self) -> Painted<&T>

👎Deprecated since 1.0.1:

renamed to resetting() due to conflicts with Vec::clear(). The clear() method will be removed in a future release.

Returns self with the quirk() set to [Quirk :: Clear].

§Example
println!("{}", value.clear());
§

fn resetting(&self) -> Painted<&T>

Returns self with the quirk() set to [Quirk :: Resetting].

§Example
println!("{}", value.resetting());
§

fn bright(&self) -> Painted<&T>

Returns self with the quirk() set to [Quirk :: Bright].

§Example
println!("{}", value.bright());
§

fn on_bright(&self) -> Painted<&T>

Returns self with the quirk() set to [Quirk :: OnBright].

§Example
println!("{}", value.on_bright());
§

fn whenever(&self, value: Condition) -> Painted<&T>

Conditionally enable styling based on whether the [Condition] value applies. Replaces any previous condition.

See the crate level docs for more details.

§Example

Enable styling painted only when both stdout and stderr are TTYs:

use yansi::{Paint, Condition};

painted.red().on_yellow().whenever(Condition::STDOUTERR_ARE_TTY);
§

fn new(self) -> Painted<Self>
where Self: Sized,

Create a new [Painted] with a default [Style]. Read more
§

fn paint<S>(&self, style: S) -> Painted<&Self>
where S: Into<Style>,

Apply a style wholesale to self. Any previous style is replaced. Read more
§

impl<T> Pointable for T

§

const ALIGN: usize

The alignment of pointer.
§

type Init = T

The type for initializers.
§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
§

impl<T, S> SpanWrap<S> for T
where S: WrappingSpan<T>,

§

fn with_span(self, span: S) -> <S as WrappingSpan<Self>>::Spanned

Invokes [WrappingSpan::make_wrapped] to wrap an AST node in a span.
§

impl<T> StdoutFmt for T
where T: Display,

§

fn fg<C>(self, color: C) -> Foreground<Self>
where C: Into<Option<Color>>,

Give this value the specified foreground colour, when color is enabled for stdout.
§

fn bg<C>(self, color: C) -> Background<Self>
where C: Into<Option<Color>>,

Give this value the specified background colour, when color is enabled for stdout.
§

impl<SS, SP> SupersetOf<SS> for SP
where SS: SubsetOf<SP>,

§

fn to_subset(&self) -> Option<SS>

The inverse inclusion map: attempts to construct self from the equivalent element of its superset. Read more
§

fn is_in_subset(&self) -> bool

Checks if self is actually part of its subset T (and can be converted to it).
§

fn to_subset_unchecked(&self) -> SS

Use with care! Same as self.to_subset but without any property checks. Always succeeds.
§

fn from_subset(element: &SS) -> SP

The inclusion map: converts self to the equivalent element of its superset.
§

impl<T, U> ToSample<U> for T
where U: FromSample<T>,

§

fn to_sample_(self) -> U

§

impl<T> ToSmolStr for T
where T: Display + ?Sized,

§

fn to_smolstr(&self) -> SmolStr

Source§

impl<T> ToString for T
where T: Display + ?Sized,

Source§

fn to_string(&self) -> String

Converts the given value to a String. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
§

impl<T> Upcast<T> for T

§

fn upcast(&self) -> Option<&T>

§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

§

fn vzip(self) -> V

§

impl<T> WithSubscriber for T

§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a [WithDispatch] wrapper. Read more
§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a [WithDispatch] wrapper. Read more
§

impl<T> Attachment for T
where T: OpaqueAttachment + Display + Debug,

§

impl<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
where ST: ?Sized, DT: ?Sized,

§

impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
where ST: ?Sized, DT: ?Sized,

§

impl<T> ConditionalSend for T
where T: Send,

§

impl<S, T> Duplex<S> for T
where T: FromSample<S> + ToSample<S>,

§

impl<T> ErasedDestructor for T
where T: 'static,

§

impl<T> HitDataExtra for T
where T: Send + Sync + Debug + Any + 'static,

§

impl<T, U> Imply<T> for U
where T: ?Sized, U: ?Sized,

§

impl<T> OpaqueAttachment for T
where T: Send + Sync + 'static,

§

impl<T> Read<Exclusive, BecauseExclusive> for T
where T: ?Sized,

§

impl<T> Settings for T
where T: 'static + Send + Sync,

§

impl<T> WasmNotSend for T
where T: Send,

§

impl<T> WasmNotSendSync for T
where T: WasmNotSend + WasmNotSync,

§

impl<T> WasmNotSync for T
where T: Sync,