Struct rocket::Rocket

source ·
pub struct Rocket<P: Phase>(/* private fields */);
Expand description

The application server itself.

Phases

A Rocket instance represents a web server and its state. It progresses through three statically-enforced phases: build, ignite, orbit.

  • Build: application and server configuration

    This phase enables:

    • setting configuration options
    • mounting/registering routes/catchers
    • managing state
    • attaching fairings

    This is the only phase in which an instance can be modified. To finalize changes, an instance is ignited via Rocket::ignite(), progressing it into the ignite phase, or directly launched into orbit with Rocket::launch() which progress the instance through ignite into orbit.

  • Ignite: verification and finalization of configuration

    An instance in the Ignite phase is in its final configuration, available via Rocket::config(). Barring user-supplied interior mutation, application state is guaranteed to remain unchanged beyond this point. An instance in the ignite phase can be launched into orbit to serve requests via Rocket::launch().

  • Orbit: a running web server

    An instance in the Orbit phase represents a running application, actively serving requests.

Launching

To launch a Rocket application, the suggested approach is to return an instance of Rocket<Build> from a function named rocket marked with the #[launch] attribute:

#[launch]
fn rocket() -> _ {
    rocket::build()
}

This generates a main function with an async runtime that runs the returned Rocket instance.

  • Manual Launching

    To launch an instance of Rocket, it must progress through all three phases. To progress into the ignite or launch phases, a tokio async runtime is required. The #[main] attribute initializes a Rocket-specific tokio runtime and runs the attributed async fn inside of it:

    #[rocket::main]
    async fn main() -> Result<(), rocket::Error> {
        let _rocket = rocket::build()
            .ignite().await?
            .launch().await?;
    
        Ok(())
    }

    Note that Rocket::launch() automatically progresses an instance of Rocket from any phase into orbit:

    #[rocket::main]
    async fn main() -> Result<(), rocket::Error> {
        let _rocket = rocket::build().launch().await?;
        Ok(())
    }

    For extreme and rare cases in which #[main] imposes obstinate restrictions, use rocket::execute() to execute Rocket’s launch() future.

  • Automatic Launching

    Manually progressing an instance of Rocket though its phases is only necessary when either an instance’s finalized state is to be inspected (in the ignite phase) or the instance is expected to deorbit due to Rocket::shutdown(). In the more common case when neither is required, the #[launch] attribute can be used. When applied to a function that returns a Rocket<Build>, it automatically initializes an async runtime and launches the function’s returned instance:

    use rocket::{Rocket, Build};
    
    #[launch]
    fn rocket() -> Rocket<Build> {
        rocket::build()
    }

    To avoid needing to import any items in the common case, the launch attribute will infer a return type written as _ as Rocket<Build>:

    #[launch]
    fn rocket() -> _ {
        rocket::build()
    }

Implementations§

source§

impl Rocket<Build>

source

pub fn build() -> Self

Create a new Rocket application using the default configuration provider, Config::figment().

This method is typically called through the rocket::build() alias.

Examples
#[launch]
fn rocket() -> _ {
    rocket::build()
}
source

pub fn custom<T: Provider>(provider: T) -> Self

Creates a new Rocket application using the supplied configuration provider.

This method is typically called through the rocket::custom() alias.

Example
use rocket::figment::{Figment, providers::{Toml, Env, Format}};

#[launch]
fn rocket() -> _ {
    let figment = Figment::from(rocket::Config::default())
        .merge(Toml::file("MyApp.toml").nested())
        .merge(Env::prefixed("MY_APP_").global());

    rocket::custom(figment)
}
source

pub fn configure<T: Provider>(self, provider: T) -> Self

Sets the configuration provider in self to provider.

A Figment generated from the current provider can always be retrieved via Rocket::figment(). However, because the provider can be changed at any point prior to ignition, a Config can only be retrieved in the ignite or orbit phases, or by manually extracting one from a particular figment.

Example
use rocket::Config;

let config = Config {
    port: 7777,
    address: Ipv4Addr::new(18, 127, 0, 1).into(),
    temp_dir: "/tmp/config-example".into(),
    ..Config::debug_default()
};

let rocket = rocket::custom(&config).ignite().await?;
assert_eq!(rocket.config().port, 7777);
assert_eq!(rocket.config().address, Ipv4Addr::new(18, 127, 0, 1));
assert_eq!(rocket.config().temp_dir.relative(), Path::new("/tmp/config-example"));

// Create a new figment which modifies _some_ keys the existing figment:
let figment = rocket.figment().clone()
    .merge((Config::PORT, 8888))
    .merge((Config::ADDRESS, "171.64.200.10"));

let rocket = rocket::custom(&config)
    .configure(figment)
    .ignite().await?;

assert_eq!(rocket.config().port, 8888);
assert_eq!(rocket.config().address, Ipv4Addr::new(171, 64, 200, 10));
assert_eq!(rocket.config().temp_dir.relative(), Path::new("/tmp/config-example"));
source

pub fn mount<'a, B, R>(self, base: B, routes: R) -> Selfwhere B: TryInto<Origin<'a>> + Clone + Display, B::Error: Display, R: Into<Vec<Route>>,

Mounts all of the routes at the given base mount point.

A route mounted at base has an effective URI of base/route, where route is the route URI. In other words, base is added as a prefix to the route’s URI. The URI resulting from joining the base URI and the route URI is called the route’s effective URI, as this is the URI used for request matching during routing.

A base URI is not allowed to have a query part. If a base does have a query part, it is ignored when producing the effective URI.

A base may have an optional trailing slash. A route with a URI path of / (and any optional query) mounted at a base has an effective URI equal to the base (plus any optional query). That is, if the base has a trailing slash, the effective URI path has a trailing slash, and otherwise it does not. Routes with URI paths other than / are not effected by trailing slashes in their corresponding mount point.

As concrete examples, consider the following table:

mount pointroute URIeffective URI
//foo/foo
//foo//foo/
/foo//foo
/foo/?bar/foo?bar
/foo/bar/foo/bar
/foo/bar//foo/bar/
/foo///foo/
/foo//bar/foo/bar
/foo//?bar/foo/?bar
/foo/bar//foo/bar
/foo/bar///foo/bar/
/foo/?bar//foo/
/foo/?bar/baz/foo/baz
/foo/?bar/baz//foo/baz/
Panics

Panics if either:

  • the base mount point is not a valid origin URI without dynamic parameters

  • any route URI is not a valid origin URI. (Note: This kind of panic is guaranteed not to occur if the routes were generated using Rocket’s code generation.)

Examples

Use the routes! macro to mount routes created using the code generation facilities. Requests to both /world and /hello/world URI will be dispatched to the hi route.

#[get("/world")]
fn hi() -> &'static str {
    "Hello!"
}

#[launch]
fn rocket() -> _ {
    rocket::build()
        .mount("/", routes![hi])
        .mount("/hello", routes![hi])
}

Manually create a route named hi at path "/world" mounted at base "/hello". Requests to the /hello/world URI will be dispatched to the hi route.

use rocket::{Request, Route, Data, route};
use rocket::http::Method;

fn hi<'r>(req: &'r Request, _: Data<'r>) -> route::BoxFuture<'r> {
    route::Outcome::from(req, "Hello!").pin()
}

#[launch]
fn rocket() -> _ {
    let hi_route = Route::new(Method::Get, "/world", hi);
    rocket::build().mount("/hello", vec![hi_route])
}
source

pub fn register<'a, B, C>(self, base: B, catchers: C) -> Selfwhere B: TryInto<Origin<'a>> + Clone + Display, B::Error: Display, C: Into<Vec<Catcher>>,

Registers all of the catchers in the supplied vector, scoped to base.

Panics

Panics if base is not a valid static path: a valid origin URI without dynamic parameters.

Examples
use rocket::Request;

#[catch(500)]
fn internal_error() -> &'static str {
    "Whoops! Looks like we messed up."
}

#[catch(404)]
fn not_found(req: &Request) -> String {
    format!("I couldn't find '{}'. Try something else?", req.uri())
}

#[launch]
fn rocket() -> _ {
    rocket::build().register("/", catchers![internal_error, not_found])
}
source

pub fn manage<T>(self, state: T) -> Selfwhere T: Send + Sync + 'static,

Add state to the state managed by this instance of Rocket.

This method can be called any number of times as long as each call refers to a different T.

Managed state can be retrieved by any request handler via the State request guard. In particular, if a value of type T is managed by Rocket, adding State<T> to the list of arguments in a request handler instructs Rocket to retrieve the managed value.

Panics

Panics if state of type T is already being managed.

Example
use rocket::State;

struct MyInt(isize);
struct MyString(String);

#[get("/int")]
fn int(state: &State<MyInt>) -> String {
    format!("The stateful int is: {}", state.0)
}

#[get("/string")]
fn string(state: &State<MyString>) -> &str {
    &state.0
}

#[launch]
fn rocket() -> _ {
    rocket::build()
        .manage(MyInt(10))
        .manage(MyString("Hello, managed state!".to_string()))
        .mount("/", routes![int, string])
}
source

pub fn attach<F: Fairing>(self, fairing: F) -> Self

Attaches a fairing to this instance of Rocket. No fairings are eagerly executed; fairings are executed at their appropriate time.

If the attached fairing is fungible and a fairing of the same name already exists, this fairing replaces it.

Example
use rocket::Rocket;
use rocket::fairing::AdHoc;

#[launch]
fn rocket() -> _ {
    rocket::build()
        .attach(AdHoc::on_liftoff("Liftoff Message", |_| Box::pin(async {
            println!("We have liftoff!");
        })))
}
source

pub async fn ignite(self) -> Result<Rocket<Ignite>, Error>

Returns a Future that transitions this instance of Rocket into the ignite phase.

When awaited, the future runs all ignite fairings in serial, attach order, and verifies that self represents a valid instance of Rocket ready for launch. This means that:

  • All ignite fairings succeeded.
  • A valid Config was extracted from Rocket::figment().
  • If secrets are enabled, the extracted Config contains a safe secret key.
  • There are no Route or Catcher collisions.
  • No Sentinel triggered an abort.

If any of these conditions fail to be met, a respective Error is returned.

Example
use rocket::fairing::AdHoc;

#[rocket::main]
async fn main() -> Result<(), rocket::Error> {
    let rocket = rocket::build()
        .attach(AdHoc::on_ignite("Manage State", |rocket| async move {
            rocket.manage(String::from("managed string"))
        }));

    // No fairings are run until ignition occurs.
    assert!(rocket.state::<String>().is_none());

    let rocket = rocket.ignite().await?;
    assert_eq!(rocket.state::<String>().unwrap(), "managed string");

    Ok(())
}
source§

impl Rocket<Ignite>

source

pub fn config(&self) -> &Config

Returns the finalized, active configuration. This is guaranteed to remain stable through ignition and into orbit.

Example
#[rocket::main]
async fn main() -> Result<(), rocket::Error> {
    let rocket = rocket::build().ignite().await?;
    let config = rocket.config();
    Ok(())
}
source

pub fn shutdown(&self) -> Shutdown

Returns a handle which can be used to trigger a shutdown and detect a triggered shutdown.

A completed graceful shutdown resolves the future returned by Rocket::launch(). If Shutdown::notify() is called before an instance is launched, it will be immediately shutdown after liftoff. See Shutdown and config::Shutdown for details on graceful shutdown.

Example
use rocket::tokio::{self, time};

#[rocket::main]
async fn main() -> Result<(), rocket::Error> {
    let rocket = rocket::build().ignite().await?;

    let shutdown = rocket.shutdown();
    tokio::spawn(async move {
        time::sleep(time::Duration::from_secs(5)).await;
        shutdown.notify();
    });

    // The `launch()` future resolves after ~5 seconds.
    let result = rocket.launch().await;
    assert!(result.is_ok());

    Ok(())
}
source§

impl Rocket<Orbit>

source

pub fn config(&self) -> &Config

Returns the finalized, active configuration. This is guaranteed to remain stable after Rocket::ignite(), through ignition and into orbit.

Example
use rocket::fairing::AdHoc;

#[launch]
fn rocket() -> _ {
    rocket::build()
        .attach(AdHoc::on_liftoff("Config", |rocket| Box::pin(async move {
            println!("Rocket launch config: {:?}", rocket.config());
        })))
}
source

pub fn shutdown(&self) -> Shutdown

Returns a handle which can be used to trigger a shutdown and detect a triggered shutdown.

A completed graceful shutdown resolves the future returned by Rocket::launch(). See Shutdown and config::Shutdown for details on graceful shutdown.

Example
use rocket::tokio::{self, time};
use rocket::fairing::AdHoc;

#[launch]
fn rocket() -> _ {
    rocket::build()
        .attach(AdHoc::on_liftoff("Shutdown", |rocket| Box::pin(async move {
            let shutdown = rocket.shutdown();
            tokio::spawn(async move {
                time::sleep(time::Duration::from_secs(5)).await;
                shutdown.notify();
            });
        })))
}
source§

impl<P: Phase> Rocket<P>

source

pub fn routes(&self) -> impl Iterator<Item = &Route>

Returns an iterator over all of the routes mounted on this instance of Rocket. The order is unspecified.

Example
use rocket::Rocket;
use rocket::fairing::AdHoc;

#[get("/hello")]
fn hello() -> &'static str {
    "Hello, world!"
}

let rocket = rocket::build()
    .mount("/", routes![hello])
    .mount("/hi", routes![hello]);

assert_eq!(rocket.routes().count(), 2);
assert!(rocket.routes().any(|r| r.uri == "/hello"));
assert!(rocket.routes().any(|r| r.uri == "/hi/hello"));
source

pub fn catchers(&self) -> impl Iterator<Item = &Catcher>

Returns an iterator over all of the catchers registered on this instance of Rocket. The order is unspecified.

Example
use rocket::Rocket;
use rocket::fairing::AdHoc;

#[catch(404)] fn not_found() -> &'static str { "Nothing here, sorry!" }
#[catch(500)] fn just_500() -> &'static str { "Whoops!?" }
#[catch(default)] fn some_default() -> &'static str { "Everything else." }

let rocket = rocket::build()
    .register("/foo", catchers![not_found])
    .register("/", catchers![just_500, some_default]);

assert_eq!(rocket.catchers().count(), 3);
assert!(rocket.catchers().any(|c| c.code == Some(404) && c.base() == "/foo"));
assert!(rocket.catchers().any(|c| c.code == Some(500) && c.base() == "/"));
assert!(rocket.catchers().any(|c| c.code == None && c.base() == "/"));
source

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

Returns Some of the managed state value for the type T if it is being managed by self. Otherwise, returns None.

Example
#[derive(PartialEq, Debug)]
struct MyState(&'static str);

let rocket = rocket::build().manage(MyState("hello!"));
assert_eq!(rocket.state::<MyState>().unwrap(), &MyState("hello!"));
source

pub fn figment(&self) -> &Figment

Returns the figment derived from the configuration provider set for self. To extract a typed config, prefer to use AdHoc::config().

Example
let rocket = rocket::build();
let figment = rocket.figment();
source

pub async fn launch(self) -> Result<Rocket<Ignite>, Error>

Returns a Future that transitions this instance of Rocket from any phase into the orbit phase. When awaited, the future drives the server forward, listening for and dispatching requests to mounted routes and catchers.

In addition to all of the processes that occur during ignition, a successful launch results in liftoff fairings being executed after binding to any respective network interfaces but before serving the first request. Liftoff fairings are run concurrently; resolution of all fairings is awaited before resuming request serving.

The Future resolves as an Err if any of the following occur:

  • there is an error igniting; see Rocket::ignite().
  • there is an I/O error starting the server.
  • an unrecoverable, system-level error occurs while running.

The Future resolves as an Ok if any of the following occur:

The returned value on Ok(()) is previously running instance.

The Future does not resolve otherwise.

Error

If there is a problem starting the application or the application fails unexpectedly while running, an Error is returned. Note that a value of type Error panics if dropped without first being inspected. See the Error documentation for more information.

Example
#[rocket::main]
async fn main() {
    let result = rocket::build().launch().await;

    // this is reachable only after `Shutdown::notify()` or `Ctrl+C`.
    println!("Rocket: deorbit.");
}

Trait Implementations§

source§

impl<P: Phase> Debug for Rocket<P>

source§

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

Formats the value using the given formatter. Read more

Auto Trait Implementations§

§

impl<P> RefUnwindSafe for Rocket<P>where <P as Phase>::State: RefUnwindSafe,

§

impl<P> Send for Rocket<P>

§

impl<P> Sync for Rocket<P>

§

impl<P> Unpin for Rocket<P>

§

impl<P> UnwindSafe for Rocket<P>where <P as Phase>::State: UnwindSafe,

Blanket Implementations§

source§

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

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

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

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

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

source§

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

Mutably borrows from an owned value. Read more
source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

source§

impl<T> Instrument for T

source§

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

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

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 Twhere 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> IntoCollection<T> for T

source§

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

Converts self into a collection.
source§

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

source§

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

source§

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();
source§

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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();
source§

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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();
source§

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

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

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

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

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

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

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

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

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

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());
source§

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

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

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

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

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

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

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

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

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

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();
source§

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Create a new Painted with a default Style. Read more
source§

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<T> for T

§

type Output = T

Should always be Self
source§

impl<T, U> TryFrom<U> for Twhere 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 Twhere 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.
source§

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

source§

fn vzip(self) -> V

source§

impl<T> WithSubscriber for T

source§

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

fn with_current_subscriber(self) -> WithDispatch<Self>

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

impl<T> Formattable for Twhere T: Deref, <T as Deref>::Target: Formattable,

source§

impl<T> Parsable for Twhere T: Deref, <T as Deref>::Target: Parsable,