use crate::fetch::FetchError;
use crate::NeqAssign;
#[derive(Clone, PartialEq, Debug)]
pub enum FetchAction<T> {
NotFetching,
Fetching,
Fetched(T),
Failed(FetchError),
}
impl<T> Default for FetchAction<T> {
fn default() -> Self {
FetchAction::NotFetching
}
}
impl<T> FetchAction<T> {
pub fn success(&self) -> Option<&T> {
match self {
FetchAction::Fetched(value) => Some(value),
_ => None,
}
}
pub fn unwrap(self) -> T {
if let FetchAction::Fetched(value) = self {
value
} else {
panic!("Could not unwrap value of FetchState");
}
}
pub fn map<U, F: Fn(T) -> U>(self, f: F) -> FetchAction<U> {
match self {
FetchAction::NotFetching => FetchAction::NotFetching,
FetchAction::Fetching => FetchAction::NotFetching,
FetchAction::Fetched(t) => FetchAction::Fetched(f(t)),
FetchAction::Failed(e) => FetchAction::Failed(e),
}
}
pub fn alter<F: Fn(&mut T)>(&mut self, f: F) {
if let FetchAction::Fetched(t) = self {
f(t)
}
}
pub fn as_ref(&self) -> FetchAction<&T> {
match self {
FetchAction::NotFetching => FetchAction::NotFetching,
FetchAction::Fetching => FetchAction::NotFetching,
FetchAction::Fetched(t) => FetchAction::Fetched(t),
FetchAction::Failed(e) => FetchAction::Failed(e.clone()),
}
}
}
impl<T: PartialEq> FetchAction<T> {
pub fn set_fetching(&mut self) -> bool {
self.neq_assign(FetchAction::Fetching)
}
}