enum_extract_error/
lib.rs

1//! Companion crate for [`enum-extract`](https://crates.io/crates/enum-extract).
2//!
3//! This crate provides the `EnumExtractError` type, which is used by `enum-extract` to report errors.
4//! It must be a separate crate because `enum-extract` is a `proc-macro` crate,
5//! which are only allowed to export procedural macros.
6//!
7//! # Example Message
8//!
9//! ```rust
10//! use enum_extract_error::EnumExtractError;
11//!
12//! let error: EnumExtractError = EnumExtractError::new("One", "Three");
13//! assert_eq!(error.to_string(), "expected One, got Three");
14//! ```
15
16#![warn(missing_docs)]
17
18use thiserror::Error;
19
20/// An error that occurs when the actual variant does not match the expected variant.
21#[derive(Error, Debug, Clone)]
22#[error("expected {expected}, got {actual}")]
23pub struct EnumExtractError {
24    /// The name of the expected variant.
25    pub expected: &'static str,
26    /// The name of the actual variant.
27    pub actual: &'static str,
28}
29
30impl EnumExtractError {
31    /// Create a new [`EnumExtractError`].
32    pub fn new(expected: &'static str, actual: &'static str) -> Self {
33        Self { expected, actual }
34    }
35}
36
37/// An error that occurs when the actual variant does not match the expected variant.
38///
39/// This error is only produced by functions that consume the value,
40/// and therefore holds on to the value in case it is needed.
41#[derive(Error, Debug)]
42#[error("{source}")]
43pub struct EnumExtractValueError<T> {
44    /// The inner extraction error.
45    #[source]
46    pub source: EnumExtractError,
47
48    /// The value of the actual variant.
49    pub value: T,
50}
51
52impl<T> EnumExtractValueError<T> {
53    /// Create a new [`EnumExtractError`].
54    pub fn from_plain_error(extract_error: EnumExtractError, value: T) -> Self {
55        Self {
56            source: extract_error,
57            value,
58        }
59    }
60
61    /// Create a new [`EnumExtractError`].
62    pub fn new(expected: &'static str, actual: &'static str, value: T) -> Self {
63        Self {
64            source: EnumExtractError::new(expected, actual),
65            value,
66        }
67    }
68}
69
70impl<T> From<EnumExtractValueError<T>> for EnumExtractError {
71    fn from(value: EnumExtractValueError<T>) -> Self {
72        value.source
73    }
74}