| 1 |
use crate::{constants::MAX_PRECISION_U32, Decimal}; |
| 2 |
use alloc::string::String; |
| 3 |
use core::fmt; |
| 4 |
|
| 5 |
/// Error type for the library. |
| 6 |
#[derive(Clone, Debug, PartialEq)] |
| 7 |
pub enum Error { |
| 8 |
/// A generic error from Rust Decimal with the `String` containing more information as to what |
| 9 |
/// went wrong. |
| 10 |
/// |
| 11 |
/// This is a legacy/deprecated error type retained for backwards compatibility. |
| 12 |
ErrorString(String), |
| 13 |
/// The value provided exceeds `Decimal::MAX`. |
| 14 |
ExceedsMaximumPossibleValue, |
| 15 |
/// The value provided is less than `Decimal::MIN`. |
| 16 |
LessThanMinimumPossibleValue, |
| 17 |
/// An underflow is when there are more fractional digits than can be represented within `Decimal`. |
| 18 |
Underflow, |
| 19 |
/// The scale provided exceeds the maximum scale that `Decimal` can represent. |
| 20 |
ScaleExceedsMaximumPrecision(u32), |
| 21 |
/// Represents a failure to convert to/from `Decimal` to the specified type. This is typically |
| 22 |
/// due to type constraints (e.g. `Decimal::MAX` cannot be converted into `i32`). |
| 23 |
ConversionTo(String), |
| 24 |
} |
| 25 |
|
| 26 |
impl<S> From<S> for Error |
| 27 |
where |
| 28 |
S: Into<String>, |
| 29 |
{ |
| 30 |
#[inline] |
| 31 |
fn from(from: S) -> Self { |
| 32 |
Self::ErrorString(from.into()) |
| 33 |
} |
| 34 |
} |
| 35 |
|
| 36 |
#[cold] |
| 37 |
pub(crate) fn tail_error(from: &'static str) -> Result<Decimal, Error> { |
| 38 |
Err(from.into()) |
| 39 |
} |
| 40 |
|
| 41 |
#[cfg(feature = "std")] |
| 42 |
impl std::error::Error for Error {} |
| 43 |
|
| 44 |
impl fmt::Display for Error { |
| 45 |
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 46 |
match *self { |
| 47 |
Self::ErrorString(ref err) => f.pad(err), |
| 48 |
Self::ExceedsMaximumPossibleValue => { |
| 49 |
write!(f, "Number exceeds maximum value that can be represented.") |
| 50 |
} |
| 51 |
Self::LessThanMinimumPossibleValue => { |
| 52 |
write!(f, "Number less than minimum value that can be represented.") |
| 53 |
} |
| 54 |
Self::Underflow => { |
| 55 |
write!(f, "Number has a high precision that can not be represented.") |
| 56 |
} |
| 57 |
Self::ScaleExceedsMaximumPrecision(ref scale) => { |
| 58 |
write!( |
| 59 |
f, |
| 60 |
"Scale exceeds the maximum precision allowed: {} > {}", |
| 61 |
scale, MAX_PRECISION_U32 |
| 62 |
) |
| 63 |
} |
| 64 |
Self::ConversionTo(ref type_name) => { |
| 65 |
write!(f, "Error while converting to {}", type_name) |
| 66 |
} |
| 67 |
} |
| 68 |
} |
| 69 |
} |