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 withRocket::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 viaRocket::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 viaRocket::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 tokioasync
runtime is required. The#[main]
attribute initializes a Rocket-specific tokio runtime and runs the attributedasync 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 ofRocket
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, userocket::execute()
to execute Rocket’slaunch()
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 aRocket<Build>
, it automatically initializes anasync
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_
asRocket<Build>
:#[launch] fn rocket() -> _ { rocket::build() }
Implementations§
source§impl Rocket<Build>
impl Rocket<Build>
sourcepub fn build() -> Self
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()
}
sourcepub fn custom<T: Provider>(provider: T) -> Self
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)
}
sourcepub fn reconfigure<T: Provider>(self, provider: T) -> Self
pub fn reconfigure<T: Provider>(self, provider: T) -> Self
Overrides the current configuration provider with provider
.
The default provider, or a provider previously set with
Rocket::custom()
or Rocket::reconfigure()
, is overridden by
provider
.
§Example
use rocket::config::{Config, Ident};
let config = Config {
ident: Ident::try_new("MyServer").expect("valid ident"),
temp_dir: "/tmp/config-example".into(),
..Config::debug_default()
};
let rocket = rocket::custom(&config).ignite().await?;
assert_eq!(rocket.config().ident.as_str(), Some("MyServer"));
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::IDENT, "Example"));
let rocket = rocket::custom(&config)
.reconfigure(figment)
.ignite().await?;
assert_eq!(rocket.config().ident.as_str(), Some("Example"));
assert_eq!(rocket.config().temp_dir.relative(), Path::new("/tmp/config-example"));
sourcepub fn mount<'a, B, R>(self, base: B, routes: R) -> Self
pub fn mount<'a, B, R>(self, base: B, routes: R) -> Self
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 point | route URI | effective 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])
}
sourcepub fn register<'a, B, C>(self, base: B, catchers: C) -> Self
pub fn register<'a, B, C>(self, base: B, catchers: C) -> Self
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])
}
sourcepub fn manage<T>(self, state: T) -> Self
pub fn manage<T>(self, state: T) -> Self
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])
}
sourcepub fn attach<F: Fairing>(self, fairing: F) -> Self
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 a singleton and a fairing of the same type has already been attached, this fairing replaces it. Otherwise the fairing gets attached without replacing any existing fairing.
§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!");
})))
}
sourcepub async fn ignite(self) -> Result<Rocket<Ignite>, Error>
pub async fn ignite(self) -> Result<Rocket<Ignite>, Error>
Returns a Future
that transitions this instance of Rocket
into the
ignite phase.
When await
ed, 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 fromRocket::figment()
. - If
secrets
are enabled, the extractedConfig
contains a safe secret key. - There are no
Route
orCatcher
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>
impl Rocket<Ignite>
sourcepub fn config(&self) -> &Config
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(())
}
sourcepub fn shutdown(&self) -> Shutdown ⓘ
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 ShutdownConfig
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>
impl Rocket<Orbit>
sourcepub fn config(&self) -> &Config
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());
})))
}
pub fn endpoints(&self) -> impl Iterator<Item = &Endpoint>
sourcepub fn shutdown(&self) -> Shutdown ⓘ
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
ShutdownConfig
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>
impl<P: Phase> Rocket<P>
sourcepub fn routes(&self) -> impl Iterator<Item = &Route>
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"));
sourcepub fn catchers(&self) -> impl Iterator<Item = &Catcher>
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() == "/"));
sourcepub fn state<T: Send + Sync + 'static>(&self) -> Option<&T>
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!"));
sourcepub fn fairing<F: Fairing>(&self) -> Option<&F>
pub fn fairing<F: Fairing>(&self) -> Option<&F>
Returns a reference to the first fairing of type F
if it is attached.
Otherwise, returns None
.
To retrieve a mutable reference to fairing F
, use
Rocket::fairing_mut()
instead.
§Example
// A regular, non-singleton fairing.
struct MyFairing(&'static str);
// A singleton fairing.
struct MySingletonFairing(&'static str);
// fairing is not attached, returns `None`
let rocket = rocket::build();
assert!(rocket.fairing::<MyFairing>().is_none());
assert!(rocket.fairing::<MySingletonFairing>().is_none());
// attach fairing, now returns `Some`
let rocket = rocket.attach(MyFairing("some state"));
assert!(rocket.fairing::<MyFairing>().is_some());
assert_eq!(rocket.fairing::<MyFairing>().unwrap().0, "some state");
// it returns the first fairing of a given type only
let rocket = rocket.attach(MyFairing("other state"));
assert_eq!(rocket.fairing::<MyFairing>().unwrap().0, "some state");
// attach fairing, now returns `Some`
let rocket = rocket.attach(MySingletonFairing("first"));
assert_eq!(rocket.fairing::<MySingletonFairing>().unwrap().0, "first");
// recall that new singletons replace existing attached singletons
let rocket = rocket.attach(MySingletonFairing("second"));
assert_eq!(rocket.fairing::<MySingletonFairing>().unwrap().0, "second");
sourcepub fn fairings<F: Fairing>(&self) -> impl Iterator<Item = &F>
pub fn fairings<F: Fairing>(&self) -> impl Iterator<Item = &F>
Returns an iterator over all attached fairings of type F
, if any.
§Example
// A regular, non-singleton fairing.
struct MyFairing(&'static str);
// A singleton fairing.
struct MySingletonFairing(&'static str);
let rocket = rocket::build();
assert_eq!(rocket.fairings::<MyFairing>().count(), 0);
assert_eq!(rocket.fairings::<MySingletonFairing>().count(), 0);
let rocket = rocket.attach(MyFairing("some state"))
.attach(MySingletonFairing("first"))
.attach(MySingletonFairing("second"))
.attach(MyFairing("other state"))
.attach(MySingletonFairing("third"));
let my_fairings: Vec<_> = rocket.fairings::<MyFairing>().collect();
assert_eq!(my_fairings.len(), 2);
assert_eq!(my_fairings[0].0, "some state");
assert_eq!(my_fairings[1].0, "other state");
let my_singleton: Vec<_> = rocket.fairings::<MySingletonFairing>().collect();
assert_eq!(my_singleton.len(), 1);
assert_eq!(my_singleton[0].0, "third");
sourcepub fn fairing_mut<F: Fairing>(&mut self) -> Option<&mut F>
pub fn fairing_mut<F: Fairing>(&mut self) -> Option<&mut F>
Returns a mutable reference to the first fairing of type F
if it is
attached. Otherwise, returns None
.
§Example
// A regular, non-singleton fairing.
struct MyFairing(&'static str);
// fairing is not attached, returns `None`
let mut rocket = rocket::build();
assert!(rocket.fairing_mut::<MyFairing>().is_none());
// attach fairing, now returns `Some`
let mut rocket = rocket.attach(MyFairing("some state"));
assert!(rocket.fairing_mut::<MyFairing>().is_some());
assert_eq!(rocket.fairing_mut::<MyFairing>().unwrap().0, "some state");
// we can modify the fairing
rocket.fairing_mut::<MyFairing>().unwrap().0 = "other state";
assert_eq!(rocket.fairing_mut::<MyFairing>().unwrap().0, "other state");
// it returns the first fairing of a given type only
let mut rocket = rocket.attach(MyFairing("yet more state"));
assert_eq!(rocket.fairing_mut::<MyFairing>().unwrap().0, "other state");
sourcepub fn fairings_mut<F: Fairing>(&mut self) -> impl Iterator<Item = &mut F>
pub fn fairings_mut<F: Fairing>(&mut self) -> impl Iterator<Item = &mut F>
Returns an iterator of mutable references to all attached fairings of
type F
, if any.
§Example
// A regular, non-singleton fairing.
struct MyFairing(&'static str);
let mut rocket = rocket::build()
.attach(MyFairing("some state"))
.attach(MyFairing("other state"))
.attach(MyFairing("yet more state"));
let mut fairings: Vec<_> = rocket.fairings_mut::<MyFairing>().collect();
assert_eq!(fairings.len(), 3);
assert_eq!(fairings[0].0, "some state");
assert_eq!(fairings[1].0, "other state");
assert_eq!(fairings[2].0, "yet more state");
// we can modify the fairings
fairings[1].0 = "modified state";
let fairings: Vec<_> = rocket.fairings::<MyFairing>().collect();
assert_eq!(fairings.len(), 3);
assert_eq!(fairings[0].0, "some state");
assert_eq!(fairings[1].0, "modified state");
assert_eq!(fairings[2].0, "yet more state");
sourcepub fn figment(&self) -> &Figment
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()
.
Note; A Figment
generated from the current provider
can always
be retrieved via this method. 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
let rocket = rocket::build();
let figment = rocket.figment();
sourcepub async fn launch(self) -> Result<Rocket<Ignite>, Error>
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 await
ed, 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 await
ed 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:
- graceful shutdown via
Shutdown::notify()
completes.
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.");
}
pub async fn launch_with<B: Bind>(self) -> Result<Rocket<Ignite>, Error>
pub async fn try_launch_on<L, F, E>( self, listener: F, ) -> Result<Rocket<Ignite>, Error>
pub async fn launch_on<L>(self, listener: L) -> Result<Rocket<Ignite>, Error>where
L: Listener + 'static,
Trait Implementations§
Auto Trait Implementations§
impl<P> Freeze for Rocket<P>
impl<P> RefUnwindSafe for Rocket<P>
impl<P> Send for Rocket<P>
impl<P> Sync for Rocket<P>
impl<P> Unpin for Rocket<P>
impl<P> UnwindSafe for Rocket<P>
Blanket Implementations§
source§impl<T> AsAny for Twhere
T: Any,
impl<T> AsAny for Twhere
T: Any,
fn as_any_ref(&self) -> &(dyn Any + 'static)
fn as_any_mut(&mut self) -> &mut (dyn Any + 'static)
source§impl<'a, T, E> AsTaggedExplicit<'a, E> for Twhere
T: 'a,
impl<'a, T, E> AsTaggedExplicit<'a, E> for Twhere
T: 'a,
source§impl<'a, T, E> AsTaggedImplicit<'a, E> for Twhere
T: 'a,
impl<'a, T, E> AsTaggedImplicit<'a, E> for Twhere
T: 'a,
source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
source§impl<T> Instrument for T
impl<T> Instrument for T
source§fn instrument(self, span: Span) -> Instrumented<Self> ⓘ
fn instrument(self, span: Span) -> Instrumented<Self> ⓘ
source§fn in_current_span(self) -> Instrumented<Self> ⓘ
fn in_current_span(self) -> Instrumented<Self> ⓘ
source§impl<T> IntoEither for T
impl<T> IntoEither for T
source§fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ
fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ
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 moresource§fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
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 moresource§impl<T> Paint for Twhere
T: ?Sized,
impl<T> Paint for Twhere
T: ?Sized,
source§fn fg(&self, value: Color) -> Painted<&T>
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 bright_black(&self) -> Painted<&T>
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>
fn bright_red(&self) -> Painted<&T>
source§fn bright_green(&self) -> Painted<&T>
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>
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>
fn bright_blue(&self) -> Painted<&T>
source§fn bright_magenta(&self) -> Painted<&T>
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>
fn bright_cyan(&self) -> Painted<&T>
source§fn bright_white(&self) -> Painted<&T>
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>
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>
fn on_primary(&self) -> Painted<&T>
source§fn on_magenta(&self) -> Painted<&T>
fn on_magenta(&self) -> Painted<&T>
source§fn on_bright_black(&self) -> Painted<&T>
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>
fn on_bright_red(&self) -> Painted<&T>
source§fn on_bright_green(&self) -> Painted<&T>
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>
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>
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>
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>
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>
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>
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 underline(&self) -> Painted<&T>
fn underline(&self) -> Painted<&T>
Returns self
with the
attr()
set to
Attribute::Underline
.
§Example
println!("{}", value.underline());
source§fn rapid_blink(&self) -> Painted<&T>
fn rapid_blink(&self) -> Painted<&T>
Returns self
with the
attr()
set to
Attribute::RapidBlink
.
§Example
println!("{}", value.rapid_blink());
source§fn quirk(&self, value: Quirk) -> Painted<&T>
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 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.
fn clear(&self) -> Painted<&T>
resetting()
due to conflicts with Vec::clear()
.
The clear()
method will be removed in a future release.source§fn whenever(&self, value: Condition) -> Painted<&T>
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);