blather 0.12.0

A talkative line-based protocol
Documentation
//! Error types and error management functions.

use std::fmt;

use tokio::io;


/// Specifies whether a parameter key or value is invalid.
#[derive(Debug)]
pub enum ParamError {
  /// The key is invalid.
  Key(String),

  /// The value is invalid.
  Value(String)
}

/// Error that `blather` can emit.
#[derive(Debug)]
pub enum Error {
  /// The input format of a buffer was incorrect.
  BadFormat(String),

  /// The specified size is invalid, or invalid in a specific context.
  InvalidSize(String),

  /// A `std::io` or `tokio::io` error has occurred.
  IO(std::io::Error),

  /// Invalid `Params` field.
  Param(ParamError),

  /// Unable to serialize a buffer.
  SerializeError(String),

  /// A "protcol error" implies that the Framed decoder detected an error
  /// while parsing incoming data.
  ///
  /// This can either mean that an unexpected format was detected while
  /// parsing the wire protocol, or that the `Codec` was found to be in an
  /// unepxcted state.
  Protocol(String)
}

impl Error {
  /// Factory for `Self::BadFormat`.
  pub fn bad_format(s: impl Into<String>) -> Self {
    Self::BadFormat(s.into())
  }
}

impl std::error::Error for Error {}

impl fmt::Display for Error {
  fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
    match self {
      Self::BadFormat(s) => write!(f, "Bad format; {s}"),
      Self::InvalidSize(s) => write!(f, "Invalid size; {s}"),
      Self::IO(e) => write!(f, "I/O error; {e}"),
      Self::Param(pe) => {
        if f.alternate() {
          match pe {
            ParamError::Key(s) => write!(f, "Invalid key; {s}"),
            ParamError::Value(s) => write!(f, "Invalid value; {s}")
          }
        } else {
          match pe {
            ParamError::Key(s) | ParamError::Value(s) => write!(f, "{s}")
          }
        }
      }
      Self::Protocol(s) => write!(f, "Protocol; {s}"),
      Self::SerializeError(s) => write!(f, "Unable to serialize; {s}")
    }
  }
}

impl From<io::Error> for Error {
  fn from(err: io::Error) -> Self {
    Self::IO(err)
  }
}

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