Struct rocket::State[][src]

#[repr(transparent)]
pub struct State<T: Send + Sync + 'static>(_);
Expand description

Request guard to retrieve managed state.

A reference &State<T> type is a request guard which retrieves the managed state managing for some type T. 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 as multiple handlers in multiple threads may be accessing the value at once. 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(state: &State<MyConfig>) -> &str {
    &state.user_val
}

#[launch]
fn rocket() -> _ {
    rocket::build()
        .mount("/", routes![index, raw_config_value])
        .manage(MyConfig { user_val: "user input".to_string() })
}

Within Request Guards

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

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

struct Item<'r>(&'r str);

#[rocket::async_trait]
impl<'r> FromRequest<'r> for Item<'r> {
    type Error = ();

    async fn from_request(request: &'r Request<'_>) -> request::Outcome<Self, ()> {
        // Using `State` as a request guard. Use `inner()` to get an `'r`.
        let outcome = request.guard::<&State<MyConfig>>().await
            .map(|my_config| Item(&my_config.user_val));

        // Or alternatively, using `Rocket::state()`:
        let outcome = request.rocket().state::<MyConfig>()
            .map(|my_config| Item(&my_config.user_val))
            .or_forward(());

        outcome
    }
}

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::get() static method or the From<&T> implementation:

use rocket::State;

struct MyManagedState(usize);

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

let mut rocket = rocket::build().manage(MyManagedState(127));
let state = State::get(&rocket).expect("managed `MyManagedState`");
assert_eq!(handler(state), "127");

let managed = MyManagedState(77);
assert_eq!(handler(State::from(&managed)), "77");

Implementations

impl<T: Send + Sync + 'static> State<T>[src]

pub fn get<P: Phase>(rocket: &Rocket<P>) -> Option<&State<T>>[src]

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::build().manage(Managed(7));

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

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

pub fn inner(&self) -> &T[src]

Borrow the inner value.

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;

#[derive(Clone)]
struct MyConfig {
    user_val: String
}

fn handler1<'r>(config: &State<MyConfig>) -> String {
    let config = config.inner().clone();
    config.user_val
}

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

Trait Implementations

impl<T: Debug + Send + Sync + 'static> Debug for State<T>[src]

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

Formats the value using the given formatter. Read more

impl<T: Send + Sync + 'static> Deref for State<T>[src]

type Target = T

The resulting type after dereferencing.

fn deref(&self) -> &T[src]

Dereferences the value.

impl<T: Send + Sync + Display + 'static> Display for State<T>[src]

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

Formats the value using the given formatter. Read more

impl<'r, T: Send + Sync + 'static> From<&'r T> for &'r State<T>[src]

fn from(reference: &'r T) -> Self[src]

Performs the conversion.

impl<'r, T: Send + Sync + 'static> FromRequest<'r> for &'r State<T>[src]

type Error = ()

The associated error to be returned if derivation fails.

fn from_request<'life0, 'async_trait>(
    req: &'r Request<'life0>
) -> Pin<Box<dyn Future<Output = Outcome<Self, ()>> + Send + 'async_trait>> where
    'r: 'async_trait,
    'life0: 'async_trait,
    Self: 'async_trait, 
[src]

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

impl<T: Hash + Send + Sync + 'static> Hash for State<T>[src]

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

Feeds this value into the given Hasher. Read more

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

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

impl<T: Ord + Send + Sync + 'static> Ord for State<T>[src]

fn cmp(&self, other: &State<T>) -> Ordering[src]

This method returns an Ordering between self and other. Read more

#[must_use]
fn max(self, other: Self) -> Self
1.21.0[src]

Compares and returns the maximum of two values. Read more

#[must_use]
fn min(self, other: Self) -> Self
1.21.0[src]

Compares and returns the minimum of two values. Read more

#[must_use]
fn clamp(self, min: Self, max: Self) -> Self
1.50.0[src]

Restrict a value to a certain interval. Read more

impl<T: PartialEq + Send + Sync + 'static> PartialEq<State<T>> for State<T>[src]

fn eq(&self, other: &State<T>) -> bool[src]

This method tests for self and other values to be equal, and is used by ==. Read more

fn ne(&self, other: &State<T>) -> bool[src]

This method tests for !=.

impl<T: PartialOrd + Send + Sync + 'static> PartialOrd<State<T>> for State<T>[src]

fn partial_cmp(&self, other: &State<T>) -> Option<Ordering>[src]

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

#[must_use]
fn lt(&self, other: &Rhs) -> bool
1.0.0[src]

This method tests less than (for self and other) and is used by the < operator. Read more

#[must_use]
fn le(&self, other: &Rhs) -> bool
1.0.0[src]

This method tests less than or equal to (for self and other) and is used by the <= operator. Read more

#[must_use]
fn gt(&self, other: &Rhs) -> bool
1.0.0[src]

This method tests greater than (for self and other) and is used by the > operator. Read more

#[must_use]
fn ge(&self, other: &Rhs) -> bool
1.0.0[src]

This method tests greater than or equal to (for self and other) and is used by the >= operator. Read more

impl<T: Send + Sync + 'static> RefCast for State<T>[src]

type From = T

fn ref_cast(_from: &Self::From) -> &Self[src]

fn ref_cast_mut(_from: &mut Self::From) -> &mut Self[src]

impl<T: Send + Sync + 'static> Sentinel for &State<T>[src]

fn abort(rocket: &Rocket<Ignite>) -> bool[src]

Returns true if launch should be aborted and false otherwise.

impl<T: Eq + Send + Sync + 'static> Eq for State<T>[src]

impl<T: Send + Sync + 'static> StructuralEq for State<T>[src]

impl<T: Send + Sync + 'static> StructuralPartialEq for State<T>[src]

Auto Trait Implementations

impl<T> RefUnwindSafe for State<T> where
    T: RefUnwindSafe

impl<T> Send for State<T>

impl<T> Sync for State<T>

impl<T> Unpin for State<T> where
    T: Unpin

impl<T> UnwindSafe for State<T> where
    T: UnwindSafe

Blanket Implementations

impl<T> Any for T where
    T: 'static + ?Sized
[src]

pub fn type_id(&self) -> TypeId[src]

Gets the TypeId of self. Read more

impl<T> Borrow<T> for T where
    T: ?Sized
[src]

pub fn borrow(&self) -> &T[src]

Immutably borrows from an owned value. Read more

impl<T> BorrowMut<T> for T where
    T: ?Sized
[src]

pub fn borrow_mut(&mut self) -> &mut T[src]

Mutably borrows from an owned value. Read more

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

pub fn equivalent(&self, key: &K) -> bool[src]

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

impl<T> From<T> for T[src]

pub fn from(t: T) -> T[src]

Performs the conversion.

impl<T> Instrument for T[src]

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

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

fn in_current_span(self) -> Instrumented<Self>[src]

Instruments this type with the current Span, returning an Instrumented wrapper. Read more

impl<T, U> Into<U> for T where
    U: From<T>, 
[src]

pub fn into(self) -> U[src]

Performs the conversion.

impl<T> IntoCollection<T> for T

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

Converts self into a collection.

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

impl<T> Same<T> for T

type Output = T

Should always be Self

impl<T> ToString for T where
    T: Display + ?Sized
[src]

pub default fn to_string(&self) -> String[src]

Converts the given value to a String. Read more

impl<T, U> TryFrom<U> for T where
    U: Into<T>, 
[src]

type Error = Infallible

The type returned in the event of a conversion error.

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

Performs the conversion.

impl<T, U> TryInto<U> for T where
    U: TryFrom<T>, 
[src]

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

The type returned in the event of a conversion error.

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

Performs the conversion.

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

pub fn vzip(self) -> V