use crate::types::MonthCode;
use displaydoc::Display;
#[derive(Debug, Copy, Clone, PartialEq, Display)]
#[non_exhaustive]
pub enum DateError {
#[displaydoc("The {field} = {value} argument is out of range {min}..={max}")]
Range {
field: &'static str,
value: i32,
min: i32,
max: i32,
},
#[displaydoc("Unknown era")]
UnknownEra,
#[displaydoc("Unknown month code {0:?}")]
UnknownMonthCode(MonthCode),
}
impl core::error::Error for DateError {}
#[derive(Debug, Copy, Clone, PartialEq, Display)]
#[displaydoc("The {field} = {value} argument is out of range {min}..={max}")]
#[allow(clippy::exhaustive_structs)]
pub struct RangeError {
pub field: &'static str,
pub value: i32,
pub min: i32,
pub max: i32,
}
impl core::error::Error for RangeError {}
impl From<RangeError> for DateError {
fn from(value: RangeError) -> Self {
let RangeError {
field,
value,
min,
max,
} = value;
DateError::Range {
field,
value,
min,
max,
}
}
}
pub(crate) fn year_check(
year: i32,
bounds: impl core::ops::RangeBounds<i32>,
) -> Result<i32, RangeError> {
use core::ops::Bound::*;
if !bounds.contains(&year) {
return Err(RangeError {
field: "year",
value: year,
min: match bounds.start_bound() {
Included(&m) => m,
Excluded(&m) => m + 1,
Unbounded => i32::MIN,
},
max: match bounds.end_bound() {
Included(&m) => m,
Excluded(&m) => m - 1,
Unbounded => i32::MAX,
},
});
}
Ok(year)
}