ComparisonError

Struct ComparisonError 

Source
pub struct ComparisonError<T: PartialOrd> { /* private fields */ }
Expand description

Compare the partial ordering of two or three values and format the result into a message.

The constructor ComparisonError::new compares two to three input values with each other using the given ComparisonOperators and returns an instance of this struct as an Result::Err(ComparisonError) if the comparison returned “false” (otherwise, ComparisonError::new returns Result::Ok(())). This is done in order to allow seamless operation with the ? operator.

§Examples

use compare_variables::{ComparisonError, ComparisonValue, ComparisonOperator};

fn my_checked_sub(first: usize, second: usize) -> Result<usize, ComparisonError<usize>> {
    ComparisonError::new(
        ComparisonValue::new(first, None),
        ComparisonOperator::Greater,
        ComparisonValue::new(second, None),
        ComparisonOperator::Equal,
        None,
    )?;
    return Ok(first - second);
}

assert_eq!(my_checked_sub(2, 1).unwrap(), 1);
let err = my_checked_sub(1, 2).unwrap_err();
assert_eq!(err.to_string(), "`1 > 2` is false");

§Variable names

It is possible to specify variable names which are then included in the error message string:

use compare_variables::{ComparisonError, ComparisonValue, ComparisonOperator};

let err = ComparisonError::new(
    ComparisonValue::new(1, Some("x")),
    ComparisonOperator::Greater,
    ComparisonValue::new(2, None),
    ComparisonOperator::Equal,
    None,
).unwrap_err();
assert_eq!(err.to_string(), "`x (value: 1) > 2` is false");

let err = ComparisonError::new(
    ComparisonValue::new(1, Some("x")),
    ComparisonOperator::Greater,
    ComparisonValue::new(2, Some("y")),
    ComparisonOperator::Equal,
    None,
).unwrap_err();
assert_eq!(err.to_string(), "`x (value: 1) > y (value: 2)` is false");

§Construction via macro

It is recommended to use the procedural macro compare_variables to construct this struct (available via the feature flag proc_macro which is enabled by default). With the macro, the previous example is simplified to:

use compare_variables::compare_variables;

let x = 1;
let y = 2;

let err = compare_variables!(x > 2).unwrap_err();
assert_eq!(err.to_string(), "`x (value: 1) > 2` is false");

let err = compare_variables!(x > y).unwrap_err();
assert_eq!(err.to_string(), "`x (value: 1) > y (value: 2)` is false");

For more examples, consult the macro documentation.

§Customize error messages

The error messages are build by concatenating the format strings of the given ComparisonValues and ComparisonOperators. These components can be accessed individually in order to build custom error messages:

use compare_variables::{ComparisonError, ComparisonValue, ComparisonOperator, ComparisonErrorTrait};

let err = ComparisonError::new(
    ComparisonValue::new(1, None),
    ComparisonOperator::Greater,
    ComparisonValue::new(2, None),
    ComparisonOperator::Equal,
    None,
).unwrap_err();

let my_error_msg = format!("Condition `{} {} {}` is not fulfilled", err.first_val(), err.comp_first_to_second(), err.second_val());
assert_eq!(my_error_msg, "Condition `1 > 2` is not fulfilled");

Implementations§

Source§

impl<T: PartialOrd> ComparisonError<T>

Source

pub fn new( first_val: ComparisonValue<T>, comp_first_to_second: ComparisonOperator, second_val: ComparisonValue<T>, comp_second_to_third: ComparisonOperator, third_val: Option<ComparisonValue<T>>, ) -> Result<(), Self>

Construct a new instance of ComparisonError if the comparison defined by the input arguments fails.

The first_val is compared to the second_val using the comp_first_to_second operator. If a third_val is given, it is compared to the second argument using the comp_second_to_third operator. If no third_val is given, comp_second_to_third is not used internally (and can therefore be chosen arbitrarily). If one of these comparisons evaluate to false, an instance of ComparisonError is returned as an Result::Err(ComparisonError). Otherwise, ComparisonError::new returns Result::Ok(())). This is done in order to allow seamless operation with the ? operator.

For examples, see the docstring of ComparisonError.

Source

pub fn first_val(&self) -> &ComparisonValue<T>

Returns a reference to the first value.

Source

pub fn second_val(&self) -> &ComparisonValue<T>

Returns a reference to the second value.

Source

pub fn third_val(&self) -> Option<&ComparisonValue<T>>

Returns a reference to the third value, if one was given.

Trait Implementations§

Source§

impl<T: Clone + PartialOrd> Clone for ComparisonError<T>

Source§

fn clone(&self) -> ComparisonError<T>

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl<T: PartialOrd + Debug + Sync + Send + 'static> ComparisonErrorTrait for ComparisonError<T>

Source§

fn fmt_first_val(&self, f: &mut Formatter<'_>) -> Result

Write the representation of the first comparison value into the given formatter. This function is especially useful if a ComparisonError is used as a trait object ComparisonErrorTrait in order to erase the underlying type.
Source§

fn fmt_second_val(&self, f: &mut Formatter<'_>) -> Result

Write the representation of the second comparison value into the given formatter. This function is especially useful if a ComparisonError is used as a trait object ComparisonErrorTrait in order to erase the underlying type.
Source§

fn fmt_third_val(&self, f: &mut Formatter<'_>) -> Result

Write the representation of the third comparison value into the given formatter. This function is especially useful if a ComparisonError is used as a trait object ComparisonErrorTrait in order to erase the underlying type. Read more
Source§

fn comp_first_to_second(&self) -> ComparisonOperator

Returns the comparison operator between the first and the second value.
Source§

fn comp_second_to_third(&self) -> ComparisonOperator

Returns the comparison operator between the second and the third value.
Source§

impl<T: PartialOrd + Debug> Debug for ComparisonError<T>

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl<T: PartialOrd + Debug> Display for ComparisonError<T>

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl<T: PartialOrd + Debug> Error for ComparisonError<T>

1.30.0 · Source§

fn source(&self) -> Option<&(dyn Error + 'static)>

Returns the lower-level source of this error, if any. Read more
1.0.0 · Source§

fn description(&self) -> &str

👎Deprecated since 1.42.0: use the Display impl or to_string()
1.0.0 · Source§

fn cause(&self) -> Option<&dyn Error>

👎Deprecated since 1.33.0: replaced by Error::source, which can support downcasting
Source§

fn provide<'a>(&'a self, request: &mut Request<'a>)

🔬This is a nightly-only experimental API. (error_generic_member_access)
Provides type-based access to context intended for error reports. Read more

Auto Trait Implementations§

§

impl<T> Freeze for ComparisonError<T>
where T: Freeze,

§

impl<T> RefUnwindSafe for ComparisonError<T>
where T: RefUnwindSafe,

§

impl<T> Send for ComparisonError<T>
where T: Send,

§

impl<T> Sync for ComparisonError<T>
where T: Sync,

§

impl<T> Unpin for ComparisonError<T>
where T: Unpin,

§

impl<T> UnwindSafe for ComparisonError<T>
where T: UnwindSafe,

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T> ToString for T
where T: Display + ?Sized,

Source§

fn to_string(&self) -> String

Converts the given value to a String. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.