Skip to content

Instantly share code, notes, and snippets.

@shadowmint
Created February 27, 2018 09:22
Show Gist options
  • Save shadowmint/0ddbb4ed0063152f8d2bab639763b2db to your computer and use it in GitHub Desktop.
Save shadowmint/0ddbb4ed0063152f8d2bab639763b2db to your computer and use it in GitHub Desktop.
Promise type for rust
#[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