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
60
61
62
63
64
65
66
67
68
69
70
pub use crate::wait::NotifyReady;

use crate:: {
  error::Error,
  wait::Wait,
};

#[derive(Debug)]
pub struct Confirmation<T> {
  kind: ConfirmationKind<T>,
}

impl<T> Confirmation<T> {
  pub(crate) fn new(wait: Wait<T>) -> Self {
    Self { kind: ConfirmationKind::Wait(wait) }
  }

  pub(crate) fn new_error(error: Error) -> Self {
    Self { kind: ConfirmationKind::Error(error) }
  }

  pub(crate) fn as_error(self) -> Result<(), Error> {
    self.into_result().map(|_| ())
  }

  pub fn subscribe(&self, task: Box<dyn NotifyReady + Send>) {
    if let ConfirmationKind::Wait(ref wait) = self.kind {
      wait.subscribe(task);
    }
  }

  pub fn into_result(self) -> Result<Self, Error> {
    if let ConfirmationKind::Error(err) = self.kind {
      Err(err)
    } else {
      Ok(self)
    }
  }

  pub fn try_wait(&self) -> Option<T> {
    match &self.kind {
      ConfirmationKind::Wait(wait) => wait.try_wait(),
      ConfirmationKind::Error(_)   => None,
    }
  }

  pub fn wait(self) -> Result<T, Error> {
    Ok(match self.kind {
      ConfirmationKind::Wait(wait)   => wait.wait(),
      ConfirmationKind::Error(error) => return Err(error),
    })
  }
}

#[derive(Debug)]
enum ConfirmationKind<T> {
  Wait(Wait<T>),
  Error(Error),
}

impl<T> From<Result<Wait<T>, Error>> for Confirmation<T> {
  fn from(res: Result<Wait<T>, Error>) -> Self {
    Self {
      kind: match res {
        Ok(wait) => ConfirmationKind::Wait(wait),
        Err(err) => ConfirmationKind::Error(err),
      }
    }
  }
}