tosic_http/extractors/
data.rs

1//! Extractors for Shared state in the server
2
3use crate::extractors::ExtractionError;
4use crate::futures::{err, ok, Ready};
5use crate::request::{HttpPayload, HttpRequest};
6use crate::traits::from_request::FromRequest;
7use std::fmt::Debug;
8use std::ops::Deref;
9use std::sync::Arc;
10
11#[derive(Clone)]
12/// The `Data` extractor
13pub struct Data<T: Send + Sync + 'static>(pub Arc<T>);
14
15impl<T: Send + Sync + 'static> Data<T> {
16    #[inline]
17    /// Creates a new `Data`
18    pub(crate) fn new(data: Arc<T>) -> Self {
19        Data(data)
20    }
21    #[inline]
22    /// Returns the inner value
23    pub fn into_inner(self) -> Arc<T> {
24        Arc::clone(&self.0)
25    }
26}
27
28impl<T: Send + Sync + 'static> FromRequest for Data<T> {
29    type Error = ExtractionError;
30    type Future = Ready<Result<Data<T>, Self::Error>>;
31
32    #[inline]
33    fn from_request(req: &HttpRequest, _: &mut HttpPayload) -> Self::Future {
34        let data = &req.data;
35
36        match data.get::<T>() {
37            Some(state) => ok(Data::new(state)),
38            None => err(ExtractionError::DataNotFound),
39        }
40    }
41}
42
43impl<T: Send + Sync + 'static> Deref for Data<T> {
44    type Target = T;
45
46    #[inline]
47    fn deref(&self) -> &Self::Target {
48        &self.0
49    }
50}
51
52impl<T: Send + Sync + 'static> Debug for Data<T> {
53    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
54        f.debug_struct("Data").finish()
55    }
56}