swctx 0.3.0

One-shot channel with some special semantics.
Documentation
//! Error management module.

use std::fmt;

/// Errors that can be returned by the `swctx` library.
#[derive(Debug, PartialEq, Eq)]
pub enum Error<S, E> {
  /// The [`SetCtx`](super::SetCtx) was dropped while in state 'S'.
  Aborted(S),

  /// The [`WaitCtx`](super::WaitCtx) was dropped.
  ///
  /// This will be returned by [`SetCtx`](super::SetCtx) if it attempts to
  /// update the context if there's no longer a `WaitCtx` to receive the
  /// changes.
  LostWaiter,

  /// The [`SetCtx`](super::SetCtx) triggered an application-defined error.
  App(E)
}

impl<S, E> Error<S, E> {
  /// Return application-specific error, if set.
  ///
  /// If the error is not `Error::App(E)` then return `None`, otherwise return
  /// Some(E).
  pub fn into_apperr(self) -> Option<E> {
    match self {
      Self::App(e) => Some(e),
      _ => None
    }
  }

  /// Return application-specific error.
  ///
  /// # Panics
  /// This method will panic if the error is not `Error::App(E)`.
  pub fn unwrap_apperr(self) -> E {
    match self {
      Self::App(e) => e,
      _ => panic!("Not an Error::App")
    }
  }
}

impl<S: fmt::Debug, E> std::error::Error for Error<S, E> where
  E: std::error::Error
{
}

impl<S, E> fmt::Display for Error<S, E>
where
  E: std::error::Error
{
  fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
    match self {
      Self::Aborted(_) => {
        write!(f, "The set context was dropped prematurely")
      }
      Self::LostWaiter => write!(f, "WaitCtx disappeared"),
      Self::App(err) => write!(f, "Application error; {:?}", err)
    }
  }
}

// vim: set ft=rust et sw=2 ts=2 sts=2 cinoptions=2 tw=79 :