intrepid_core/extract/extractor.rs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
use std::convert::Infallible;
use crate::{Context, Frame};
use super::ExtractorError;
/// A convenience type for a tuple containing an action context and a state.
// pub type ExtractContext<State> = (ActionContext<State>, State);
/// Implement extract to allow for extracting values from an action.
pub trait Extractor<State> {
/// The error type for this extractor. Anything that can be converted into an extractor error
/// can be used as an error type.
///
/// Types that can be converted into an extractor error are:
///
/// - `String`
/// - `Infallible`
/// - `tower::BoxError`
///
type Error: Into<ExtractorError>;
/// Take an frame and a state and return a result containing the extracted value or the frame.
fn extract(frame: Frame, context: &Context<State>) -> Result<Self, Self::Error>
where
Self: Sized;
/// Extract a value from a frame and state, returning a result containing the extracted value
/// or an error coerced into a `crate::Error`.
fn extract_from_frame_and_state(frame: Frame, context: &Context<State>) -> crate::Result<Self>
where
Self: Sized,
Self::Error: Into<ExtractorError>,
{
match Self::extract(frame, context) {
Ok(value) => Ok(value),
Err(error) => Err(error.into().into()),
}
}
}
impl<State> Extractor<State> for Frame {
type Error = Infallible;
fn extract(
frame: Frame,
_: &Context<State>,
) -> Result<Self, <crate::Frame as Extractor<State>>::Error> {
Ok(frame)
}
}
impl<State> Extractor<State> for String {
type Error = ExtractorError;
fn extract(frame: Frame, _: &Context<State>) -> Result<Self, Self::Error> {
Ok(frame.into())
}
}