Struct rocket::local::asynchronous::LocalRequest
source · pub struct LocalRequest<'c> { /* private fields */ }
Expand description
An async
local request as returned by Client
.
For details, see the top-level documentation.
Example
The following snippet uses the available builder methods to construct and
dispatch a POST
request to /
with a JSON body:
use rocket::local::asynchronous::{Client, LocalRequest};
use rocket::http::{ContentType, Cookie};
let client = Client::tracked(rocket::build()).await.expect("valid rocket");
let req = client.post("/")
.header(ContentType::JSON)
.remote("127.0.0.1:8000".parse().unwrap())
.cookie(Cookie::new("name", "value"))
.body(r#"{ "value": 42 }"#);
let response = req.dispatch().await;
Implementations§
source§impl<'c> LocalRequest<'c>
impl<'c> LocalRequest<'c>
sourcepub fn inner(&self) -> &Request<'c>
pub fn inner(&self) -> &Request<'c>
Borrows the inner Request
as seen by Rocket.
Note that no routing has occurred and that there is no remote
address unless one has been explicitly set with
set_remote()
.
Example
use rocket::local::asynchronous::LocalRequest;
let request: LocalRequest = request;
let inner: &rocket::Request = request.inner();
sourcepub fn inner_mut(&mut self) -> &mut Request<'c>
pub fn inner_mut(&mut self) -> &mut Request<'c>
Mutably borrows the inner Request
as seen by Rocket.
Note that no routing has occurred and that there is no remote
address unless one has been explicitly set with
set_remote()
.
Example
use rocket::local::asynchronous::LocalRequest;
let mut request: LocalRequest = request;
let inner: &mut rocket::Request = request.inner_mut();
sourcepub fn header<H>(self, header: H) -> Selfwhere
H: Into<Header<'static>>,
pub fn header<H>(self, header: H) -> Selfwhere H: Into<Header<'static>>,
Add a header to this request.
Any type that implements Into<Header>
can be used here. Among
others, this includes ContentType
and Accept
.
Examples
Add the Content-Type header:
use rocket::local::asynchronous::LocalRequest;
use rocket::http::Header;
use rocket::http::ContentType;
let request: LocalRequest = request;
let req = request
.header(ContentType::JSON)
.header(Header::new("X-Custom", "custom-value"));
sourcepub fn add_header<H>(&mut self, header: H)where
H: Into<Header<'static>>,
pub fn add_header<H>(&mut self, header: H)where H: Into<Header<'static>>,
Adds a header to this request without consuming self
.
Examples
Add the Content-Type header:
use rocket::local::asynchronous::LocalRequest;
use rocket::http::ContentType;
let mut request: LocalRequest = request;
request.add_header(ContentType::JSON);
sourcepub fn remote(self, address: SocketAddr) -> Self
pub fn remote(self, address: SocketAddr) -> Self
Set the remote address of this request.
Examples
Set the remote address to “8.8.8.8:80”:
use rocket::local::asynchronous::LocalRequest;
let request: LocalRequest = request;
let address = "8.8.8.8:80".parse().unwrap();
let req = request.remote(address);
Add a cookie to this request.
Examples
Add user_id
cookie:
use rocket::local::asynchronous::LocalRequest;
use rocket::http::Cookie;
let request: LocalRequest = request;
let req = request
.cookie(Cookie::new("username", "sb"))
.cookie(Cookie::new("user_id", "12"));
Add all of the cookies in cookies
to this request.
Example
use rocket::local::asynchronous::LocalRequest;
use rocket::http::Cookie;
let request: LocalRequest = request;
let cookies = vec![Cookie::new("a", "b"), Cookie::new("c", "d")];
let req = request.cookies(cookies);
Available on crate feature secrets
only.
secrets
only.Add a private cookie to this request.
Examples
Add user_id
as a private cookie:
use rocket::local::asynchronous::LocalRequest;
use rocket::http::Cookie;
let request: LocalRequest = request;
let req = request.private_cookie(Cookie::new("user_id", "sb"));
sourcepub fn body<S: AsRef<[u8]>>(self, body: S) -> Self
pub fn body<S: AsRef<[u8]>>(self, body: S) -> Self
Sets the body data of the request. core/lib/src/local/request.rs
Examples
use rocket::local::asynchronous::LocalRequest;
use rocket::http::ContentType;
let request: LocalRequest = request;
let req = request
.header(ContentType::Text)
.body("Hello, world!");
sourcepub fn set_body<S: AsRef<[u8]>>(&mut self, body: S)
pub fn set_body<S: AsRef<[u8]>>(&mut self, body: S)
Set the body (data) of the request without consuming self
.
Examples
Set the body to be a JSON structure; also sets the Content-Type.
use rocket::local::asynchronous::LocalRequest;
use rocket::http::ContentType;
let request: LocalRequest = request;
let mut request = request.header(ContentType::JSON);
request.set_body(r#"{ "key": "value", "array": [1, 2, 3] }"#);
sourcepub async fn dispatch(self) -> LocalResponse<'c>
pub async fn dispatch(self) -> LocalResponse<'c>
Dispatches the request, returning the response.
This method consumes self
and is the preferred mechanism for
dispatching.
Example
use rocket::local::asynchronous::LocalRequest;
let request: LocalRequest = request;
let response = request.dispatch();
Methods from Deref<Target = Request<'c>>§
sourcepub fn method(&self) -> Method
pub fn method(&self) -> Method
Retrieve the method from self
.
Example
use rocket::http::Method;
assert_eq!(get("/").method(), Method::Get);
assert_eq!(post("/").method(), Method::Post);
sourcepub fn set_method(&mut self, method: Method)
pub fn set_method(&mut self, method: Method)
Set the method of self
to method
.
Example
use rocket::http::Method;
assert_eq!(request.method(), Method::Get);
request.set_method(Method::Post);
assert_eq!(request.method(), Method::Post);
sourcepub fn set_uri(&mut self, uri: Origin<'r>)
pub fn set_uri(&mut self, uri: Origin<'r>)
Set the URI in self
to uri
.
Example
use rocket::http::uri::Origin;
let uri = Origin::parse("/hello/Sergio?type=greeting").unwrap();
request.set_uri(uri);
assert_eq!(request.uri().path(), "/hello/Sergio");
assert_eq!(request.uri().query().unwrap(), "type=greeting");
let new_uri = request.uri().map_path(|p| format!("/foo{}", p)).unwrap();
request.set_uri(new_uri);
assert_eq!(request.uri().path(), "/foo/hello/Sergio");
assert_eq!(request.uri().query().unwrap(), "type=greeting");
sourcepub fn host(&self) -> Option<&Host<'r>>
pub fn host(&self) -> Option<&Host<'r>>
Returns the Host
identified in the request, if any.
If the request is made via HTTP/1.1 (or earlier), this method returns
the value in the HOST
header without the deprecated user_info
component. Otherwise, this method returns the contents of the
:authority
pseudo-header request field.
Note that this method only reflects the HOST
header in the initial
request and not any changes made thereafter. To change the value
returned by this method, use Request::set_host()
.
⚠️ DANGER ⚠️
Using the user-controlled host
to construct URLs is a security hazard!
Never do so without first validating the host against a whitelist. For
this reason, Rocket disallows constructing host-prefixed URIs with
uri!
. Always use uri!
to construct URIs.
Example
Retrieve the raw host, unusable to construct safe URIs:
use rocket::http::uri::Host;
assert_eq!(request.host(), None);
request.set_host(Host::from(uri!("rocket.rs")));
let host = request.host().unwrap();
assert_eq!(host.domain(), "rocket.rs");
assert_eq!(host.port(), None);
request.set_host(Host::from(uri!("rocket.rs:2392")));
let host = request.host().unwrap();
assert_eq!(host.domain(), "rocket.rs");
assert_eq!(host.port(), Some(2392));
Retrieve the raw host, check it against a whitelist, and construct a URI:
use rocket::http::uri::Host;
// A sensitive URI we want to prefix with safe hosts.
#[get("/token?<secret>")]
fn token(secret: Token) { /* .. */ }
// Whitelist of known hosts. In a real setting, you might retrieve this
// list from config at ignite-time using tools like `AdHoc::config()`.
const WHITELIST: [Host<'static>; 3] = [
Host::new(uri!("rocket.rs")),
Host::new(uri!("rocket.rs:443")),
Host::new(uri!("guide.rocket.rs:443")),
];
// A request with a host of "rocket.rs". Note the case-insensitivity.
request.set_host(Host::from(uri!("ROCKET.rs")));
let prefix = request.host().and_then(|h| h.to_absolute("https", &WHITELIST));
// `rocket.rs` is in the whitelist, so we'll get back a `Some`.
assert!(prefix.is_some());
if let Some(prefix) = prefix {
// We can use this prefix to safely construct URIs.
let uri = uri!(prefix, token("some-secret-token"));
assert_eq!(uri, "https://ROCKET.rs/token?secret=some-secret-token");
}
// A request with a host of "attacker-controlled.com".
request.set_host(Host::from(uri!("attacker-controlled.com")));
let prefix = request.host().and_then(|h| h.to_absolute("https", &WHITELIST));
// `attacker-controlled.come` is _not_ on the whitelist.
assert!(prefix.is_none());
assert!(request.host().is_some());
sourcepub fn set_host(&mut self, host: Host<'r>)
pub fn set_host(&mut self, host: Host<'r>)
Sets the host of self
to host
.
Example
Set the host to rocket.rs:443
.
use rocket::http::uri::Host;
assert_eq!(request.host(), None);
request.set_host(Host::from(uri!("rocket.rs:443")));
let host = request.host().unwrap();
assert_eq!(host.domain(), "rocket.rs");
assert_eq!(host.port(), Some(443));
sourcepub fn remote(&self) -> Option<SocketAddr>
pub fn remote(&self) -> Option<SocketAddr>
Returns the raw address of the remote connection that initiated this
request if the address is known. If the address is not known, None
is
returned.
Because it is common for proxies to forward connections for clients, the
remote address may contain information about the proxy instead of the
client. For this reason, proxies typically set a “X-Real-IP” header
ip_header
with the client’s true IP. To
extract this IP from the request, use the real_ip()
or
client_ip()
methods.
Example
use std::net::{SocketAddrV4, Ipv4Addr};
assert_eq!(request.remote(), None);
let localhost = SocketAddrV4::new(Ipv4Addr::LOCALHOST, 8000).into();
request.set_remote(localhost);
assert_eq!(request.remote(), Some(localhost));
sourcepub fn set_remote(&mut self, address: SocketAddr)
pub fn set_remote(&mut self, address: SocketAddr)
Sets the remote address of self
to address
.
Example
Set the remote address to be 127.0.0.1:8000:
use std::net::{SocketAddrV4, Ipv4Addr};
assert_eq!(request.remote(), None);
let localhost = SocketAddrV4::new(Ipv4Addr::LOCALHOST, 8000).into();
request.set_remote(localhost);
assert_eq!(request.remote(), Some(localhost));
sourcepub fn real_ip(&self) -> Option<IpAddr>
pub fn real_ip(&self) -> Option<IpAddr>
Returns the IP address of the configured
ip_header
of the request if such a header
is configured, exists and contains a valid IP address.
Example
use std::net::Ipv4Addr;
use rocket::http::Header;
assert_eq!(req.real_ip(), None);
// `ip_header` defaults to `X-Real-IP`.
let req = req.header(Header::new("X-Real-IP", "127.0.0.1"));
assert_eq!(req.real_ip(), Some(Ipv4Addr::LOCALHOST.into()));
sourcepub fn client_ip(&self) -> Option<IpAddr>
pub fn client_ip(&self) -> Option<IpAddr>
Attempts to return the client’s IP address by first inspecting the
ip_header
and then using the remote
connection’s IP address. Note that the built-in IpAddr
request guard
can be used to retrieve the same information in a handler:
use std::net::IpAddr;
#[get("/")]
fn get_ip(client_ip: IpAddr) { /* ... */ }
#[get("/")]
fn try_get_ip(client_ip: Option<IpAddr>) { /* ... */ }
If the ip_header
exists and contains a valid IP address, that address
is returned. Otherwise, if the address of the remote connection is
known, that address is returned. Otherwise, None
is returned.
Example
// starting without an "X-Real-IP" header or remote address
assert!(request.client_ip().is_none());
// add a remote address; this is done by Rocket automatically
request.set_remote("127.0.0.1:8000".parse().unwrap());
assert_eq!(request.client_ip(), Some("127.0.0.1".parse().unwrap()));
// now with an X-Real-IP header, the default value for `ip_header`.
request.add_header(Header::new("X-Real-IP", "8.8.8.8"));
assert_eq!(request.client_ip(), Some("8.8.8.8".parse().unwrap()));
Returns a wrapped borrow to the cookies in self
.
CookieJar
implements internal mutability, so this method allows you
to get and add/remove cookies in self
.
Example
Add a new cookie to a request’s cookies:
use rocket::http::Cookie;
req.cookies().add(Cookie::new("key", "val"));
req.cookies().add(Cookie::new("ans", format!("life: {}", 38 + 4)));
assert_eq!(req.cookies().get_pending("key").unwrap().value(), "val");
assert_eq!(req.cookies().get_pending("ans").unwrap().value(), "life: 42");
sourcepub fn add_header<'h: 'r, H: Into<Header<'h>>>(&mut self, header: H)
pub fn add_header<'h: 'r, H: Into<Header<'h>>>(&mut self, header: H)
Add header
to self
’s headers. The type of header
can be any type
that implements the Into<Header>
trait. This includes common types
such as ContentType
and Accept
.
Example
use rocket::http::ContentType;
assert!(request.headers().is_empty());
request.add_header(ContentType::HTML);
assert!(request.headers().contains("Content-Type"));
assert_eq!(request.headers().len(), 1);
sourcepub fn replace_header<'h: 'r, H: Into<Header<'h>>>(&mut self, header: H)
pub fn replace_header<'h: 'r, H: Into<Header<'h>>>(&mut self, header: H)
Replaces the value of the header with name header.name
with
header.value
. If no such header exists, header
is added as a header
to self
.
Example
use rocket::http::ContentType;
assert!(request.headers().is_empty());
request.add_header(ContentType::Any);
assert_eq!(request.headers().get_one("Content-Type"), Some("*/*"));
assert_eq!(request.content_type(), Some(&ContentType::Any));
request.replace_header(ContentType::PNG);
assert_eq!(request.headers().get_one("Content-Type"), Some("image/png"));
assert_eq!(request.content_type(), Some(&ContentType::PNG));
sourcepub fn content_type(&self) -> Option<&ContentType>
pub fn content_type(&self) -> Option<&ContentType>
Returns the Content-Type header of self
. If the header is not present,
returns None
.
Example
use rocket::http::ContentType;
assert_eq!(get("/").content_type(), None);
let req = get("/").header(ContentType::JSON);
assert_eq!(req.content_type(), Some(&ContentType::JSON));
sourcepub fn accept(&self) -> Option<&Accept>
pub fn accept(&self) -> Option<&Accept>
Returns the Accept header of self
. If the header is not present,
returns None
.
Example
use rocket::http::Accept;
assert_eq!(get("/").accept(), None);
assert_eq!(get("/").header(Accept::JSON).accept(), Some(&Accept::JSON));
sourcepub fn format(&self) -> Option<&MediaType>
pub fn format(&self) -> Option<&MediaType>
Returns the media type “format” of the request.
The “format” of a request is either the Content-Type, if the request
methods indicates support for a payload, or the preferred media type in
the Accept header otherwise. If the method indicates no payload and no
Accept header is specified, a media type of Any
is returned.
The media type returned from this method is used to match against the
format
route attribute.
Example
use rocket::http::{Accept, ContentType, MediaType};
// Non-payload-bearing: format is accept header.
let req = get("/").header(Accept::HTML);
assert_eq!(req.format(), Some(&MediaType::HTML));
let req = get("/").header(ContentType::JSON).header(Accept::HTML);
assert_eq!(req.format(), Some(&MediaType::HTML));
// Payload: format is content-type header.
let req = post("/").header(ContentType::HTML);
assert_eq!(req.format(), Some(&MediaType::HTML));
let req = post("/").header(ContentType::JSON).header(Accept::HTML);
assert_eq!(req.format(), Some(&MediaType::JSON));
// Non-payload-bearing method and no accept header: `Any`.
assert_eq!(get("/").format(), Some(&MediaType::Any));
sourcepub fn rocket(&self) -> &'r Rocket<Orbit>
pub fn rocket(&self) -> &'r Rocket<Orbit>
Returns the Rocket
instance that is handling this request.
Example
// Retrieve the application config via `Rocket::config()`.
let config = request.rocket().config();
// Retrieve managed state via `Rocket::state()`.
let state = request.rocket().state::<Pool>();
// Get a list of all of the registered routes and catchers.
let routes = request.rocket().routes();
let catchers = request.rocket().catchers();
sourcepub fn limits(&self) -> &'r Limits
pub fn limits(&self) -> &'r Limits
Returns the configured application data limits.
This is convenience function equivalent to:
&request.rocket().config().limits
Example
use rocket::data::ToByteUnit;
// This is the default `form` limit.
assert_eq!(request.limits().get("form"), Some(32.kibibytes()));
// Retrieve the limit for files with extension `.pdf`; etails to 1MiB.
assert_eq!(request.limits().get("file/pdf"), Some(1.mebibytes()));
sourcepub fn route(&self) -> Option<&'r Route>
pub fn route(&self) -> Option<&'r Route>
Get the presently matched route, if any.
This method returns Some
any time a handler or its guards are being
invoked. This method returns None
before routing has commenced; this
includes during request fairing callbacks.
Example
let route = request.route();
sourcepub fn guard<'z, 'a, T>(&'a self) -> BoxFuture<'z, Outcome<T, T::Error>>where
T: FromRequest<'a> + 'z,
'a: 'z,
'r: 'z,
pub fn guard<'z, 'a, T>(&'a self) -> BoxFuture<'z, Outcome<T, T::Error>>where T: FromRequest<'a> + 'z, 'a: 'z, 'r: 'z,
Invokes the request guard implementation for T
, returning its outcome.
Example
Assuming a User
request guard exists, invoke it:
let outcome = request.guard::<User>().await;
sourcepub fn local_cache<T, F>(&self, f: F) -> &Twhere
F: FnOnce() -> T,
T: Send + Sync + 'static,
pub fn local_cache<T, F>(&self, f: F) -> &Twhere F: FnOnce() -> T, T: Send + Sync + 'static,
Retrieves the cached value for type T
from the request-local cached
state of self
. If no such value has previously been cached for this
request, f
is called to produce the value which is subsequently
returned.
Different values of the same type cannot be cached without using a
proxy, wrapper type. To avoid the need to write these manually, or for
libraries wishing to store values of public types, use the
local_cache!
or
local_cache_once!
macros to
generate a locally anonymous wrapper type, store, and retrieve the
wrapped value from request-local cache.
Example
// The first store into local cache for a given type wins.
let value = request.local_cache(|| "hello");
assert_eq!(*request.local_cache(|| "hello"), "hello");
// The following return the cached, previously stored value for the type.
assert_eq!(*request.local_cache(|| "goodbye"), "hello");
sourcepub async fn local_cache_async<'a, T, F>(&'a self, fut: F) -> &'a Twhere
F: Future<Output = T>,
T: Send + Sync + 'static,
pub async fn local_cache_async<'a, T, F>(&'a self, fut: F) -> &'a Twhere F: Future<Output = T>, T: Send + Sync + 'static,
Retrieves the cached value for type T
from the request-local cached
state of self
. If no such value has previously been cached for this
request, fut
is await
ed to produce the value which is subsequently
returned.
Example
async fn current_user<'r>(request: &Request<'r>) -> User {
// validate request for a given user, load from database, etc
}
let current_user = request.local_cache_async(async {
current_user(&request).await
}).await;
sourcepub fn param<'a, T>(&'a self, n: usize) -> Option<Result<T, T::Error>>where
T: FromParam<'a>,
pub fn param<'a, T>(&'a self, n: usize) -> Option<Result<T, T::Error>>where T: FromParam<'a>,
Retrieves and parses into T
the 0-indexed n
th non-empty segment from
the routed request, that is, the n
th segment after the mount
point. If the request has not been routed, then this is simply the n
th
non-empty request URI segment.
Returns None
if n
is greater than the number of non-empty segments.
Returns Some(Err(T::Error))
if the parameter type T
failed to be
parsed from the n
th dynamic parameter.
This method exists only to be used by manual routing. To retrieve parameters from a request, use Rocket’s code generation facilities.
Example
use rocket::error::Empty;
assert_eq!(get("/a/b/c").param(0), Some(Ok("a")));
assert_eq!(get("/a/b/c").param(1), Some(Ok("b")));
assert_eq!(get("/a/b/c").param(2), Some(Ok("c")));
assert_eq!(get("/a/b/c").param::<&str>(3), None);
assert_eq!(get("/1/b/3").param(0), Some(Ok(1)));
assert!(get("/1/b/3").param::<usize>(1).unwrap().is_err());
assert_eq!(get("/1/b/3").param(2), Some(Ok(3)));
assert_eq!(get("/").param::<&str>(0), Some(Err(Empty)));
sourcepub fn segments<'a, T>(&'a self, n: RangeFrom<usize>) -> Result<T, T::Error>where
T: FromSegments<'a>,
pub fn segments<'a, T>(&'a self, n: RangeFrom<usize>) -> Result<T, T::Error>where T: FromSegments<'a>,
Retrieves and parses into T
all of the path segments in the request
URI beginning and including the 0-indexed n
th non-empty segment
after the mount point.,that is, the n
th segment after the mount
point. If the request has not been routed, then this is simply the n
th
non-empty request URI segment.
T
must implement FromSegments
, which is used to parse the
segments. If there are no non-empty segments, the Segments
iterator
will be empty.
This method exists only to be used by manual routing. To retrieve segments from a request, use Rocket’s code generation facilities.
Example
use std::path::PathBuf;
assert_eq!(get("/").segments(0..), Ok(PathBuf::new()));
assert_eq!(get("/").segments(2..), Ok(PathBuf::new()));
// Empty segments are skipped.
assert_eq!(get("///").segments(2..), Ok(PathBuf::new()));
assert_eq!(get("/a/b/c").segments(0..), Ok(PathBuf::from("a/b/c")));
assert_eq!(get("/a/b/c").segments(1..), Ok(PathBuf::from("b/c")));
assert_eq!(get("/a/b/c").segments(2..), Ok(PathBuf::from("c")));
assert_eq!(get("/a/b/c").segments(3..), Ok(PathBuf::new()));
assert_eq!(get("/a/b/c").segments(4..), Ok(PathBuf::new()));
sourcepub fn query_value<'a, T>(&'a self, name: &str) -> Option<Result<'a, T>>where
T: FromForm<'a>,
pub fn query_value<'a, T>(&'a self, name: &str) -> Option<Result<'a, T>>where T: FromForm<'a>,
Retrieves and parses into T
the query value with field name name
.
T
must implement FromForm
, which is used to parse the query’s
value. Key matching is performed case-sensitively.
Warning
This method exists only to be used by manual routing and should never be used in a regular Rocket application. It is much more expensive to use this method than to retrieve query parameters via Rocket’s codegen. To retrieve query values from a request, always prefer to use Rocket’s code generation facilities.
Error
If a query segment with name name
isn’t present, returns None
. If
parsing the value fails, returns Some(Err(_))
.
Example
use rocket::form::FromForm;
#[derive(Debug, PartialEq, FromForm)]
struct Dog<'r> {
name: &'r str,
age: usize
}
let req = get("/?a=apple&z=zebra&a=aardvark");
assert_eq!(req.query_value::<&str>("a").unwrap(), Ok("apple"));
assert_eq!(req.query_value::<&str>("z").unwrap(), Ok("zebra"));
assert_eq!(req.query_value::<&str>("b"), None);
let a_seq = req.query_value::<Vec<&str>>("a");
assert_eq!(a_seq.unwrap().unwrap(), ["apple", "aardvark"]);
let req = get("/?dog.name=Max+Fido&dog.age=3");
let dog = req.query_value::<Dog>("dog");
assert_eq!(dog.unwrap().unwrap(), Dog { name: "Max Fido", age: 3 });
Trait Implementations§
source§impl<'c> Clone for LocalRequest<'c>
impl<'c> Clone for LocalRequest<'c>
source§impl Debug for LocalRequest<'_>
impl Debug for LocalRequest<'_>
source§impl<'c> Deref for LocalRequest<'c>
impl<'c> Deref for LocalRequest<'c>
Auto Trait Implementations§
impl<'c> !RefUnwindSafe for LocalRequest<'c>
impl<'c> Send for LocalRequest<'c>
impl<'c> Sync for LocalRequest<'c>
impl<'c> Unpin for LocalRequest<'c>
impl<'c> !UnwindSafe for LocalRequest<'c>
Blanket Implementations§
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> IntoCollection<T> for T
impl<T> IntoCollection<T> for T
source§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>
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>
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>
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 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);