pub struct HttpApiProblem {
    pub type_url: Option<String>,
    pub status: Option<StatusCode>,
    pub title: Option<String>,
    pub detail: Option<String>,
    pub instance: Option<String>,
    /* private fields */
}
Expand description

Description of a problem that can be returned by an HTTP API based on RFC7807

Example

{
   "type": "https://example.com/probs/out-of-credit",
   "title": "You do not have enough credit.",
   "detail": "Your current balance is 30, but that costs 50.",
   "instance": "/account/12345/msgs/abc",
}

Purpose

The purpose of HttpApiProblem is to generate a meaningful response for clients. It is not intended to be used as a replacement for a proper Error struct within applications.

For a struct which can be returned by HTTP handlers use ApiError which can be enabled with the feature toggle api-error. ApiError can be directly converted into HttpApiProblem.

Status Codes and Responses

Prefer to use one of the constructors which ensure that a StatusCode is set. If no StatusCode is set and a transformation to a response of a web framework is made a StatusCode becomes mandatory which in this case will default to 500.

When receiving an HttpApiProblem there might be an invalid StatusCode contained. In this case the status field will be empty. This is a trade off so that the recipient does not have to deal with another error and can still have access to the remaining fields of the struct.

Fields§

§type_url: Option<String>

A URI reference RFC3986 that identifies the problem type. This specification encourages that, when dereferenced, it provide human-readable documentation for the problem type (e.g., using HTML [W3C.REC-html5-20141028]). When this member is not present, its value is assumed to be “about:blank”.

§status: Option<StatusCode>

The HTTP status code RFC7231, Section 6 generated by the origin server for this occurrence of the problem.

§title: Option<String>

A short, human-readable summary of the problem type. It SHOULD NOT change from occurrence to occurrence of the problem, except for purposes of localization (e.g., using proactive content negotiation; see RFC7231, Section 3.4.

§detail: Option<String>

A human-readable explanation specific to this occurrence of the problem.

§instance: Option<String>

A URI reference that identifies the specific occurrence of the problem. It may or may not yield further information if dereferenced.

Implementations§

source§

impl HttpApiProblem

source

pub fn new<T: Into<StatusCode>>(status: T) -> Self

Creates a new instance with the given StatusCode.

#Example

use http_api_problem::*;

let p = HttpApiProblem::new(StatusCode::INTERNAL_SERVER_ERROR);

assert_eq!(Some(StatusCode::INTERNAL_SERVER_ERROR), p.status);
assert_eq!(None, p.title);
assert_eq!(None, p.detail);
assert_eq!(None, p.type_url);
assert_eq!(None, p.instance);
source

pub fn try_new<T: TryInto<StatusCode>>( status: T ) -> Result<Self, InvalidStatusCode>

Creates a new instance with the given StatusCode.

Fails if the argument can not be converted into a StatusCode.

#Example

use http_api_problem::*;

let p = HttpApiProblem::try_new(500).unwrap();

assert_eq!(Some(StatusCode::INTERNAL_SERVER_ERROR), p.status);
assert_eq!(None, p.title);
assert_eq!(None, p.detail);
assert_eq!(None, p.type_url);
assert_eq!(None, p.instance);
source

pub fn with_title<T: Into<StatusCode>>(status: T) -> Self

Creates a new instance with title derived from a StatusCode.

#Example

use http_api_problem::*;

let p = HttpApiProblem::with_title(StatusCode::NOT_FOUND);

assert_eq!(Some(StatusCode::NOT_FOUND), p.status);
assert_eq!(Some("Not Found"), p.title.as_deref());
assert_eq!(None, p.detail);
assert_eq!(None, p.type_url);
assert_eq!(None, p.instance);
source

pub fn try_with_title<T: TryInto<StatusCode>>( status: T ) -> Result<Self, InvalidStatusCode>

Creates a new instance with title derived from a StatusCode.

Fails if the argument can not be converted into a StatusCode.

#Example

use http_api_problem::*;

let p = HttpApiProblem::try_with_title(404).unwrap();

assert_eq!(Some(StatusCode::NOT_FOUND), p.status);
assert_eq!(Some("Not Found"), p.title.as_deref());
assert_eq!(None, p.detail);
assert_eq!(None, p.type_url);
assert_eq!(None, p.instance);
source

pub fn with_title_and_type<T: Into<StatusCode>>(status: T) -> Self

Creates a new instance with the title and type_url derived from the StatusCode.

#Example

use http_api_problem::*;

let p = HttpApiProblem::with_title_and_type(StatusCode::SERVICE_UNAVAILABLE);

assert_eq!(Some(StatusCode::SERVICE_UNAVAILABLE), p.status);
assert_eq!(Some("Service Unavailable"), p.title.as_deref());
assert_eq!(None, p.detail);
assert_eq!(Some("https://httpstatuses.com/503".to_string()), p.type_url);
assert_eq!(None, p.instance);
Examples found in repository?
examples/additional_fields.rs (line 12)
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
fn main() {
    let problem = HttpApiProblem::with_title_and_type(StatusCode::INTERNAL_SERVER_ERROR)
        .value("error", &"this sucks")
        .value("everything", &42)
        .value(
            "person",
            &Person {
                name: "Peter".into(),
                age: 77,
            },
        );

    let json = problem.json_string();

    println!("{}", json);

    let parsed: HttpApiProblem = serde_json::from_str(&json).unwrap();

    println!("\n\n{:#?}", parsed);
}
source

pub fn try_with_title_and_type<T: TryInto<StatusCode>>( status: T ) -> Result<Self, InvalidStatusCode>

Creates a new instance with the title and type_url derived from the StatusCode.

Fails if the argument can not be converted into a StatusCode.

#Example

use http_api_problem::*;

let p = HttpApiProblem::try_with_title_and_type(503).unwrap();

assert_eq!(Some(StatusCode::SERVICE_UNAVAILABLE), p.status);
assert_eq!(Some("Service Unavailable"), p.title.as_deref());
assert_eq!(None, p.detail);
assert_eq!(Some("https://httpstatuses.com/503".to_string()), p.type_url);
assert_eq!(None, p.instance);
source

pub fn empty() -> Self

Creates a new instance without any field set.

Prefer to use one of the other constructors which ensure that a StatusCode is set. If no StatusCode is set and a transformation to a response of a web framework is made a StatusCode becomes mandatory which in this case will default to 500.

source

pub fn status<T: Into<StatusCode>>(self, status: T) -> Self

Sets the status

#Example

use http_api_problem::*;

let p = HttpApiProblem::new(StatusCode::NOT_FOUND).title("Error");

assert_eq!(Some(StatusCode::NOT_FOUND), p.status);
assert_eq!(Some("Error"), p.title.as_deref());
assert_eq!(None, p.detail);
assert_eq!(None, p.type_url);
assert_eq!(None, p.instance);
source

pub fn type_url<T: Into<String>>(self, type_url: T) -> Self

Sets the type_url

#Example

use http_api_problem::*;

let p = HttpApiProblem::new(StatusCode::NOT_FOUND).type_url("http://example.com/my/real_error");

assert_eq!(Some(StatusCode::NOT_FOUND), p.status);
assert_eq!(None, p.title);
assert_eq!(None, p.detail);
assert_eq!(Some("http://example.com/my/real_error".to_string()), p.type_url);
assert_eq!(None, p.instance);
source

pub fn try_status<T: TryInto<StatusCode>>( self, status: T ) -> Result<Self, InvalidStatusCode>

Tries to set the status

Fails if the argument can not be converted into a StatusCode.

#Example

use http_api_problem::*;

let p = HttpApiProblem::try_new(404).unwrap().title("Error");

assert_eq!(Some(StatusCode::NOT_FOUND), p.status);
assert_eq!(Some("Error"), p.title.as_deref());
assert_eq!(None, p.detail);
assert_eq!(None, p.type_url);
assert_eq!(None, p.instance);
source

pub fn title<T: Into<String>>(self, title: T) -> Self

Sets the title

#Example

use http_api_problem::*;

let p = HttpApiProblem::new(StatusCode::NOT_FOUND).title("Another Error");

assert_eq!(Some(StatusCode::NOT_FOUND), p.status);
assert_eq!(Some("Another Error"), p.title.as_deref());
assert_eq!(None, p.detail);
assert_eq!(None, p.type_url);
assert_eq!(None, p.instance);
source

pub fn detail<T: Into<String>>(self, detail: T) -> HttpApiProblem

Sets the detail

#Example

use http_api_problem::*;

let p = HttpApiProblem::new(StatusCode::NOT_FOUND).detail("a detailed description");

assert_eq!(Some(StatusCode::NOT_FOUND), p.status);
assert_eq!(None, p.title);
assert_eq!(Some("a detailed description".to_string()), p.detail);
assert_eq!(None, p.type_url);
assert_eq!(None, p.instance);
source

pub fn instance<T: Into<String>>(self, instance: T) -> HttpApiProblem

Sets the instance

#Example

use http_api_problem::*;

let p = HttpApiProblem::new(StatusCode::NOT_FOUND).instance("/account/1234/withdraw");

assert_eq!(Some(StatusCode::NOT_FOUND), p.status);
assert_eq!(None, p.title);
assert_eq!(None, p.detail);
assert_eq!(None, p.type_url);
assert_eq!(Some("/account/1234/withdraw".to_string()), p.instance);
source

pub fn try_value<K, V>( self, key: K, value: &V ) -> Result<Self, Box<dyn Error + Send + Sync + 'static>>
where V: Serialize, K: Into<String>,

Add a value that must be serializable.

The key must not be one of the field names of this struct.

These values get serialized into the JSON on top level.

source

pub fn value<K, V>(self, key: K, value: &V) -> Self
where V: Serialize, K: Into<String>,

Add a value that must be serializable.

The key must not be one of the field names of this struct. If the key is a field name or the value is not serializable nothing happens.

These values get serialized into the JSON on top level.

Examples found in repository?
examples/additional_fields.rs (line 13)
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
fn main() {
    let problem = HttpApiProblem::with_title_and_type(StatusCode::INTERNAL_SERVER_ERROR)
        .value("error", &"this sucks")
        .value("everything", &42)
        .value(
            "person",
            &Person {
                name: "Peter".into(),
                age: 77,
            },
        );

    let json = problem.json_string();

    println!("{}", json);

    let parsed: HttpApiProblem = serde_json::from_str(&json).unwrap();

    println!("\n\n{:#?}", parsed);
}
source

pub fn set_value<K, V>(&mut self, key: K, value: &V)
where V: Serialize, K: Into<String>,

Add a value that must be serializable.

The key must not be one of the field names of this struct. If the key is a field name or the value is not serializable nothing happens.

These values get serialized into the JSON on top level.

source

pub fn get_value<K, V>(&self, key: &str) -> Option<V>

Returns the deserialized field for the given key.

If the key does not exist or the field is not deserializable to the target type None is returned

source

pub fn try_set_value<K, V>( &mut self, key: K, value: &V ) -> Result<(), Box<dyn Error + Send + Sync + 'static>>
where V: Serialize, K: Into<String>,

source

pub fn additional_fields(&self) -> &HashMap<String, Value>

Returns a reference to the serialized fields

If the key does not exist or the field is not deserializable to the target type None is returned

source

pub fn additional_fields_mut(&mut self) -> &mut HashMap<String, Value>

Returns a mutable reference to the serialized fields

If the key does not exist or the field is not deserializable to the target type None is returned

source

pub fn keys<K, V>(&self) -> impl Iterator<Item = &String>

source

pub fn json_value(&self, key: &str) -> Option<&Value>

Returns the serde_json::Value for the given key if the key exists.

source

pub fn json_bytes(&self) -> Vec<u8>

Serialize to a JSON Vec<u8>

source

pub fn json_string(&self) -> String

Serialize to a JSON String

Examples found in repository?
examples/additional_fields.rs (line 23)
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
fn main() {
    let problem = HttpApiProblem::with_title_and_type(StatusCode::INTERNAL_SERVER_ERROR)
        .value("error", &"this sucks")
        .value("everything", &42)
        .value(
            "person",
            &Person {
                name: "Peter".into(),
                age: 77,
            },
        );

    let json = problem.json_string();

    println!("{}", json);

    let parsed: HttpApiProblem = serde_json::from_str(&json).unwrap();

    println!("\n\n{:#?}", parsed);
}
source

pub fn to_hyper_response(&self) -> Response<Body>

Creates a hyper response.

If status is None 500 - Internal Server Error is the default.

Requires the hyper feature

source

pub fn to_axum_response(&self) -> Response

Creates an axum Response.

If status is None 500 - Internal Server Error is the default.

Requires the axum feature

source

pub fn to_actix_response(&self) -> HttpResponse

Creates an actix response.

If status is None or not convertible to an actix status 500 - Internal Server Error is the default.

Requires the actix-web feature

source

pub fn to_rocket_response(&self) -> Response<'static>

Creates a rocket response.

If status is None 500 - Internal Server Error is the default.

Requires the rocket feature

source

pub fn to_salvo_response(&self) -> Response

Creates a salvo response.

If status is None 500 - Internal Server Error is the default.

Requires the salvo feature

source

pub fn to_tide_response(&self) -> Response

Creates a tide response.

If status is None 500 - Internal Server Error is the default.

Requires the tide feature

source

pub fn with_title_from_status<T: Into<StatusCode>>(status: T) -> Self

👎Deprecated since 0.50.0: please use with_title instead
source

pub fn with_title_and_type_from_status<T: Into<StatusCode>>(status: T) -> Self

👎Deprecated since 0.50.0: please use with_title_and_type instead
source

pub fn set_status<T: Into<StatusCode>>(self, status: T) -> Self

👎Deprecated since 0.50.0: please use status instead
source

pub fn set_title<T: Into<String>>(self, title: T) -> Self

👎Deprecated since 0.50.0: please use title instead
source

pub fn set_detail<T: Into<String>>(self, detail: T) -> Self

👎Deprecated since 0.50.0: please use detail instead
source

pub fn set_type_url<T: Into<String>>(self, type_url: T) -> Self

👎Deprecated since 0.50.0: please use type_url instead
source

pub fn set_instance<T: Into<String>>(self, instance: T) -> Self

👎Deprecated since 0.50.0: please use instance instead

Trait Implementations§

source§

impl Clone for HttpApiProblem

source§

fn clone(&self) -> HttpApiProblem

Returns a copy of the value. Read more
1.0.0 · source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
source§

impl Debug for HttpApiProblem

source§

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

Formats the value using the given formatter. Read more
source§

impl<'de> Deserialize<'de> for HttpApiProblem

source§

fn deserialize<__D>(__deserializer: __D) -> Result<Self, __D::Error>
where __D: Deserializer<'de>,

Deserialize this value from the given Serde deserializer. Read more
source§

impl Display for HttpApiProblem

source§

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

Formats the value using the given formatter. Read more
source§

impl Error for HttpApiProblem

source§

fn source(&self) -> Option<&(dyn Error + 'static)>

The lower-level source of this error, if any. Read more
1.0.0 · source§

fn description(&self) -> &str

👎Deprecated since 1.42.0: use the Display impl or to_string()
1.0.0 · source§

fn cause(&self) -> Option<&dyn Error>

👎Deprecated since 1.33.0: replaced by Error::source, which can support downcasting
source§

fn provide<'a>(&'a self, request: &mut Request<'a>)

🔬This is a nightly-only experimental API. (error_generic_member_access)
Provides type based access to context intended for error reports. Read more
source§

impl From<ApiError> for HttpApiProblem

source§

fn from(error: ApiError) -> Self

Converts to this type from the input type.
source§

impl From<HttpApiProblem> for HttpResponse

source§

fn from(problem: HttpApiProblem) -> HttpResponse

Converts to this type from the input type.
source§

impl From<HttpApiProblem> for Response

source§

fn from(problem: HttpApiProblem) -> Response

Converts to this type from the input type.
source§

impl From<HttpApiProblem> for Response<'static>

source§

fn from(problem: HttpApiProblem) -> Response<'static>

Converts to this type from the input type.
source§

impl From<HttpApiProblem> for Response

source§

fn from(problem: HttpApiProblem) -> Response

Converts to this type from the input type.
source§

impl From<HttpApiProblem> for Response<Body>

source§

fn from(problem: HttpApiProblem) -> Response<Body>

Converts to this type from the input type.
source§

impl From<HttpApiProblem> for Response

source§

fn from(problem: HttpApiProblem) -> Response

Converts to this type from the input type.
source§

impl From<Infallible> for HttpApiProblem

source§

fn from(error: Infallible) -> HttpApiProblem

Converts to this type from the input type.
source§

impl From<StatusCode> for HttpApiProblem

source§

fn from(status: StatusCode) -> HttpApiProblem

Converts to this type from the input type.
source§

impl IntoResponse for HttpApiProblem

source§

fn into_response(self) -> Response

Create a response.
source§

impl JsonSchema for HttpApiProblem

source§

fn schema_name() -> String

The name of the generated JSON Schema. Read more
source§

fn schema_id() -> Cow<'static, str>

Returns a string that uniquely identifies the schema produced by this type. Read more
source§

fn json_schema(gen: &mut SchemaGenerator) -> Schema

Generates a JSON Schema for this type. Read more
source§

fn is_referenceable() -> bool

Whether JSON Schemas generated for this type should be re-used where possible using the $ref keyword. Read more
source§

impl OpenApiResponderInner for HttpApiProblem

source§

fn responses(gen: &mut OpenApiGenerator) -> Result<Responses>

Create the responses type, which is a list of responses that can be rendered in openapi.json format.
source§

impl PartialEq for HttpApiProblem

source§

fn eq(&self, other: &HttpApiProblem) -> bool

This method tests for self and other values to be equal, and is used by ==.
1.0.0 · source§

fn ne(&self, other: &Rhs) -> bool

This method tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
source§

impl<'r> Responder<'r, 'static> for HttpApiProblem

source§

fn respond_to(self, _request: &Request<'_>) -> Result<'static>

Returns Ok if a Response could be generated successfully. Otherwise, returns an Err with a failing Status. Read more
source§

impl Serialize for HttpApiProblem

source§

fn serialize<__S>(&self, __serializer: __S) -> Result<__S::Ok, __S::Error>
where __S: Serializer,

Serialize this value into the given Serde serializer. Read more
source§

impl Eq for HttpApiProblem

source§

impl Reject for HttpApiProblem

source§

impl StructuralEq for HttpApiProblem

source§

impl StructuralPartialEq for HttpApiProblem

Auto Trait Implementations§

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
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
source§

impl<T> DynClone for T
where T: Clone,

source§

fn __clone_box(&self, _: Private) -> *mut ()

source§

impl<Q, K> Equivalent<K> for Q
where Q: Eq + ?Sized, K: Borrow<Q> + ?Sized,

source§

fn equivalent(&self, key: &K) -> bool

Compare self to key and return true if they are equal.
§

impl<Q, K> Equivalent<K> for Q
where Q: Eq + ?Sized, K: Borrow<Q> + ?Sized,

§

fn equivalent(&self, key: &K) -> bool

Checks if this value is equivalent to the given key. Read more
§

impl<Q, K> Equivalent<K> for Q
where Q: Eq + ?Sized, K: Borrow<Q> + ?Sized,

§

fn equivalent(&self, key: &K) -> bool

Compare self to key and return true if they are equal.
source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

source§

impl<T> FromRef<T> for T
where T: Clone,

source§

fn from_ref(input: &T) -> T

Converts to this type from a reference to the input type.
§

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.

§

impl<T> IntoCollection<T> for T

§

fn into_collection<A>(self) -> SmallVec<A>
where A: Array<Item = T>,

Converts self into a collection.
§

fn mapped<U, F, A>(self, f: F) -> SmallVec<A>
where F: FnMut(T) -> U, A: Array<Item = U>,

source§

impl<'a, 'r, T> OpenApiResponder<'a, 'r> for T
where 'r: 'a, T: OpenApiResponderInner + Responder<'a, 'r>,

source§

fn responses(gen: &mut OpenApiGenerator) -> Result<Responses, OpenApiError>

Create the responses type, which is a list of responses that can be rendered in openapi.json format.
§

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>

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

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

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
source§

impl<T> Same for T

§

type Output = T

Should always be Self
source§

impl<T> ToOwned for T
where T: Clone,

§

type Owned = T

The resulting type after obtaining ownership.
source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
source§

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

source§

default 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>,

§

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>,

§

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<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
source§

impl<T> DeserializeOwned for T
where T: for<'de> Deserialize<'de>,