Created
February 27, 2018 09:22
-
-
Save shadowmint/0ddbb4ed0063152f8d2bab639763b2db to your computer and use it in GitHub Desktop.
Promise type for rust
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#[derive(PartialEq)] | |
pub enum State { | |
Pending, | |
Resolved, | |
Rejected, | |
} | |
pub struct Promise<T, TErr> { | |
value: Option<Result<T, TErr>>, | |
state: State, | |
} | |
impl<T, TErr> Promise<T, TErr> { | |
pub fn new() -> Promise<T, TErr> { | |
return Promise { | |
state: State::Pending, | |
value: None, | |
}; | |
} | |
pub fn is_resolved(&self) -> bool { | |
return self.state == State::Resolved; | |
} | |
pub fn is_rejected(&self) -> bool { | |
return self.state == State::Rejected; | |
} | |
pub fn is_pending(&self) -> bool { | |
return self.state == State::Pending; | |
} | |
pub fn resolve(&mut self, value: T) -> bool { | |
if !self.is_pending() { | |
return false; | |
} | |
self.value = Some(Ok(value)); | |
self.state = State::Resolved; | |
return true; | |
} | |
pub fn reject(&mut self, err: TErr) -> bool { | |
if !self.is_pending() { | |
return false; | |
} | |
self.value = Some(Err(err)); | |
self.state = State::Rejected; | |
return true; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment