Skip to main content

niche_value/
error.rs

1//! Error types returned by the checked conversions.
2//!
3//! The integer error types mirror [`nonmax`](https://docs.rs/nonmax)'s
4//! `TryFromIntError` / `ParseIntError` (which themselves mirror the
5//! `core::num` types) so that code written against `nonmax` keeps compiling.
6//! The float error types mirror `core::num::ParseFloatError` naming.
7
8/// Error returned when a checked integral conversion fails (mirrors
9/// [`core::num::TryFromIntError`]).
10#[derive(Debug, Clone, Copy, PartialEq, Eq)]
11pub struct TryFromIntError(pub(crate) ());
12
13impl core::fmt::Display for TryFromIntError {
14    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
15        "out of range integral type conversion attempted".fmt(f)
16    }
17}
18
19impl From<core::num::TryFromIntError> for TryFromIntError {
20    fn from(_: core::num::TryFromIntError) -> Self {
21        Self(())
22    }
23}
24
25impl From<core::convert::Infallible> for TryFromIntError {
26    fn from(never: core::convert::Infallible) -> Self {
27        match never {}
28    }
29}
30
31#[cfg(feature = "std")]
32impl std::error::Error for TryFromIntError {}
33
34/// Error returned when an integer string cannot be parsed into a niche integer
35/// (mirrors [`core::num::ParseIntError`]).
36#[derive(Debug, Clone, PartialEq, Eq)]
37pub struct ParseIntError(pub(crate) ());
38
39impl core::fmt::Display for ParseIntError {
40    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
41        "unable to parse integer".fmt(f)
42    }
43}
44
45impl From<core::num::ParseIntError> for ParseIntError {
46    fn from(_: core::num::ParseIntError) -> Self {
47        Self(())
48    }
49}
50
51#[cfg(feature = "std")]
52impl std::error::Error for ParseIntError {}
53
54/// Error returned when a checked `f32`/`f64` conversion fails (the value was the
55/// forbidden bit pattern, or `NaN`/`±inf` for the class-based types).
56#[derive(Debug, Clone, Copy, PartialEq, Eq)]
57pub struct TryFromFloatError(pub(crate) ());
58
59impl core::fmt::Display for TryFromFloatError {
60    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
61        "float value is forbidden by this niche type".fmt(f)
62    }
63}
64
65#[cfg(feature = "std")]
66impl std::error::Error for TryFromFloatError {}
67
68/// Error returned when a float string cannot be parsed into a niche float
69/// (mirrors [`core::num::ParseFloatError`] naming).
70#[derive(Debug, Clone, PartialEq, Eq)]
71pub struct ParseFloatError(pub(crate) ());
72
73impl core::fmt::Display for ParseFloatError {
74    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
75        "unable to parse float".fmt(f)
76    }
77}
78
79impl From<core::num::ParseFloatError> for ParseFloatError {
80    fn from(_: core::num::ParseFloatError) -> Self {
81        Self(())
82    }
83}
84
85#[cfg(feature = "std")]
86impl std::error::Error for ParseFloatError {}