Struct rocket::State

source ·
pub struct State<'r, T: Send + Sync + 'static>(/* private fields */);
Expand description

Request guard to retrieve managed state.

This type can be used as a request guard to retrieve the state Rocket is managing for some type T. This allows for the sharing of state across any number of handlers. A value for the given type must previously have been registered to be managed by Rocket via Rocket::manage(). The type being managed must be thread safe and sendable across thread boundaries. In other words, it must implement Send + Sync + 'static.

§Example

Imagine you have some configuration struct of the type MyConfig that you’d like to initialize at start-up and later access it in several handlers. The following example does just this:

use rocket::State;

// In a real application, this would likely be more complex.
struct MyConfig {
    user_val: String
}

#[get("/")]
fn index(state: State<MyConfig>) -> String {
    format!("The config value is: {}", state.user_val)
}

#[get("/raw")]
fn raw_config_value<'r>(state: State<'r, MyConfig>) -> &'r str {
    // use `inner()` to get a lifetime longer than `deref` gives us
    state.inner().user_val.as_str()
}

fn main() {
    let config = MyConfig {
        user_val: "user input".to_string()
    };

    rocket::ignite()
        .mount("/", routes![index, raw_config_value])
        .manage(config)
        .launch();
}

§Within Request Guards

Because State is itself a request guard, managed state can be retrieved from another request guard’s implementation. In the following code example, Item retrieves the MyConfig managed state in its FromRequest implementation using the Request::guard() method.

use rocket::State;
use rocket::request::{self, Request, FromRequest};

struct Item(String);

impl<'a, 'r> FromRequest<'a, 'r> for Item {
    type Error = ();

    fn from_request(request: &'a Request<'r>) -> request::Outcome<Item, ()> {
        request.guard::<State<MyConfig>>()
            .map(|my_config| Item(my_config.user_val.clone()))
    }
}

§Testing with State

When unit testing your application, you may find it necessary to manually construct a type of State to pass to your functions. To do so, use the State::from() static method:

use rocket::State;

struct MyManagedState(usize);

#[get("/")]
fn handler(state: State<MyManagedState>) -> String {
    state.0.to_string()
}

let rocket = rocket::ignite().manage(MyManagedState(127));
let state = State::from(&rocket).expect("managing `MyManagedState`");
assert_eq!(handler(state), "127");

Implementations§

source§

impl<'r, T: Send + Sync + 'static> State<'r, T>

source

pub fn inner(&self) -> &'r T

Retrieve a borrow to the underlying value with a lifetime of 'r.

Using this method is typically unnecessary as State implements Deref with a Deref::Target of T. This means Rocket will automatically coerce a State<T> to an &T as required. This method should only be used when a longer lifetime is required.

§Example
use rocket::State;

struct MyConfig {
    user_val: String
}

// Use `inner()` to get a lifetime of `'r`
fn handler1<'r>(config: State<'r, MyConfig>) -> &'r str {
    &config.inner().user_val
}

// Use the `Deref` implementation which coerces implicitly
fn handler2(config: State<MyConfig>) -> String {
    config.user_val.clone()
}
source

pub fn from(rocket: &'r Rocket) -> Option<Self>

Returns the managed state value in rocket for the type T if it is being managed by rocket. Otherwise, returns None.

§Example
use rocket::State;

#[derive(Debug, PartialEq)]
struct Managed(usize);

#[derive(Debug, PartialEq)]
struct Unmanaged(usize);

let rocket = rocket::ignite().manage(Managed(7));

let state: Option<State<Managed>> = State::from(&rocket);
assert_eq!(state.map(|s| s.inner()), Some(&Managed(7)));

let state: Option<State<Unmanaged>> = State::from(&rocket);
assert_eq!(state, None);

Trait Implementations§

source§

impl<'r, T: Debug + Send + Sync + 'static> Debug for State<'r, T>

source§

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

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

impl<'r, T: Send + Sync + 'static> Deref for State<'r, T>

source§

type Target = T

The resulting type after dereferencing.
source§

fn deref(&self) -> &T

Dereferences the value.
source§

impl<'a, 'r, T: Send + Sync + 'static> FromRequest<'a, 'r> for State<'r, T>

source§

type Error = ()

The associated error to be returned if derivation fails.
source§

fn from_request(req: &'a Request<'r>) -> Outcome<State<'r, T>, ()>

Derives an instance of Self from the incoming request metadata. Read more
source§

impl<'r, T: Hash + Send + Sync + 'static> Hash for State<'r, T>

source§

fn hash<__H: Hasher>(&self, state: &mut __H)

Feeds this value into the given Hasher. Read more
1.3.0 · source§

fn hash_slice<H>(data: &[Self], state: &mut H)
where H: Hasher, Self: Sized,

Feeds a slice of this type into the given Hasher. Read more
source§

impl<'r, T: Ord + Send + Sync + 'static> Ord for State<'r, T>

source§

fn cmp(&self, other: &State<'r, T>) -> Ordering

This method returns an Ordering between self and other. Read more
1.21.0 · source§

fn max(self, other: Self) -> Self
where Self: Sized,

Compares and returns the maximum of two values. Read more
1.21.0 · source§

fn min(self, other: Self) -> Self
where Self: Sized,

Compares and returns the minimum of two values. Read more
1.50.0 · source§

fn clamp(self, min: Self, max: Self) -> Self
where Self: Sized + PartialOrd,

Restrict a value to a certain interval. Read more
source§

impl<'r, T: PartialEq + Send + Sync + 'static> PartialEq for State<'r, T>

source§

fn eq(&self, other: &State<'r, T>) -> bool

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

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

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

impl<'r, T: PartialOrd + Send + Sync + 'static> PartialOrd for State<'r, T>

source§

fn partial_cmp(&self, other: &State<'r, T>) -> Option<Ordering>

This method returns an ordering between self and other values if one exists. Read more
1.0.0 · source§

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

Tests less than (for self and other) and is used by the < operator. Read more
1.0.0 · source§

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

Tests less than or equal to (for self and other) and is used by the <= operator. Read more
1.0.0 · source§

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

Tests greater than (for self and other) and is used by the > operator. Read more
1.0.0 · source§

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

Tests greater than or equal to (for self and other) and is used by the >= operator. Read more
source§

impl<'r, T: Eq + Send + Sync + 'static> Eq for State<'r, T>

source§

impl<'r, T: Send + Sync + 'static> StructuralPartialEq for State<'r, T>

Auto Trait Implementations§

§

impl<'r, T> Freeze for State<'r, T>

§

impl<'r, T> RefUnwindSafe for State<'r, T>
where T: RefUnwindSafe,

§

impl<'r, T> Send for State<'r, T>

§

impl<'r, T> Sync for State<'r, T>

§

impl<'r, T> Unpin for State<'r, T>

§

impl<'r, T> UnwindSafe for State<'r, T>
where T: RefUnwindSafe,

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, I> AsResult<T, I> for T
where I: Input,

source§

fn as_result(self) -> Result<T, ParseErr<I>>

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

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

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

source§

type Output = T

Should always be Self
source§

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

source§

type Error = Infallible

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

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

Performs the conversion.
source§

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

source§

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

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

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

Performs the conversion.
source§

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

source§

fn get_type(&self) -> TypeId

Get the TypeId of this object.
source§

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

source§

fn vzip(self) -> V