| 1 |
/*! |
| 2 |
A module for constants and various base utilities. |
| 3 |
|
| 4 |
This module is a work-in-progress that may lead to helping us move off of |
| 5 |
ranged integers. I'm not quite sure where this will go. |
| 6 |
*/ |
| 7 |
|
| 8 |
use jcore::{ |
| 9 |
bounds::{self, const_check, Bounds, RawBoundsError}, |
| 10 |
constants as c, |
| 11 |
}; |
| 12 |
|
| 13 |
use crate::Error; |
| 14 |
|
| 15 |
/// Writes the definition of a single boundary type. |
| 16 |
/// |
| 17 |
/// When only the name and type are given, then this copies the `WHAT`, |
| 18 |
/// `MIN` and `MAX` definitions from `jcore`. This avoids copying the specific |
| 19 |
/// range values and maintains a single point of truth. |
| 20 |
macro_rules! define_one_boundary_type { |
| 21 |
( |
| 22 |
// The name of the boundary type. |
| 23 |
$name:ident, |
| 24 |
// The underlying primitive type. This is usually, but not always, |
| 25 |
// the smallest signed primitive integer type that can represent both |
| 26 |
// the minimum and maximum boundary values. |
| 27 |
$ty:ident, |
| 28 |
// A short human readable description that appears in error messages |
| 29 |
// when the boundaries of this type are violated. |
| 30 |
$what:expr, |
| 31 |
// The minimum value. |
| 32 |
$min:expr, |
| 33 |
// The maximum value. |
| 34 |
$max:expr $(,)? |
| 35 |
) => { |
| 36 |
pub(crate) struct $name(()); |
| 37 |
|
| 38 |
impl Bounds for $name { |
| 39 |
const WHAT: &'static str = $what; |
| 40 |
const MIN: Self::Primitive = $min; |
| 41 |
const MAX: Self::Primitive = $max; |
| 42 |
type Primitive = $ty; |
| 43 |
type Error = BoundsError; |
| 44 |
|
| 45 |
#[cold] |
| 46 |
#[inline(never)] |
| 47 |
fn error() -> BoundsError { |
| 48 |
Self::error() |
| 49 |
} |
| 50 |
} |
| 51 |
|
| 52 |
#[allow(dead_code)] |
| 53 |
impl $name { |
| 54 |
pub(crate) const MIN: $ty = <$name as Bounds>::MIN; |
| 55 |
pub(crate) const MAX: $ty = <$name as Bounds>::MAX; |
| 56 |
const LEN: i128 = Self::MAX as i128 - Self::MIN as i128 + 1; |
| 57 |
|
| 58 |
#[cold] |
| 59 |
pub(crate) const fn error() -> BoundsError { |
| 60 |
BoundsError::$name(RawBoundsError::new()) |
| 61 |
} |
| 62 |
|
| 63 |
#[cfg_attr(feature = "perf-inline", inline(always))] |
| 64 |
pub(crate) fn check( |
| 65 |
n: impl Into<i64>, |
| 66 |
) -> Result<$ty, BoundsError> { |
| 67 |
<$name as Bounds>::check(n) |
| 68 |
} |
| 69 |
|
| 70 |
#[cfg_attr(feature = "perf-inline", inline(always))] |
| 71 |
pub(crate) const fn checkc(n: i64) -> Result<$ty, BoundsError> { |
| 72 |
match const_check::$ty(n) { |
| 73 |
Ok(n) => Ok(n), |
| 74 |
Err(err) => Err(BoundsError::$name(err)), |
| 75 |
} |
| 76 |
} |
| 77 |
|
| 78 |
#[cfg_attr(feature = "perf-inline", inline(always))] |
| 79 |
pub(crate) fn checked_add( |
| 80 |
n1: $ty, |
| 81 |
n2: $ty, |
| 82 |
) -> Result<$ty, BoundsError> { |
| 83 |
<$name as Bounds>::checked_add(n1, n2) |
| 84 |
} |
| 85 |
|
| 86 |
#[cfg_attr(feature = "perf-inline", inline(always))] |
| 87 |
pub(crate) fn checked_mul( |
| 88 |
n1: $ty, |
| 89 |
n2: $ty, |
| 90 |
) -> Result<$ty, BoundsError> { |
| 91 |
<$name as Bounds>::checked_mul(n1, n2) |
| 92 |
} |
| 93 |
|
| 94 |
#[cfg(test)] |
| 95 |
pub(crate) fn arbitrary(g: &mut quickcheck::Gen) -> $ty { |
| 96 |
use quickcheck::Arbitrary; |
| 97 |
|
| 98 |
let mut n: $ty = <$ty>::arbitrary(g); |
| 99 |
n = n.wrapping_rem_euclid(Self::LEN as $ty); |
| 100 |
n += Self::MIN; |
| 101 |
n |
| 102 |
} |
| 103 |
} |
| 104 |
}; |
| 105 |
// A shortcut for defining a boundary type in `jiff` that is just a mirror |
| 106 |
// of a boundary type defined in `jiff-core`. We do this instead of using |
| 107 |
// the boundary type from `jiff-core` directly because we can't have a |
| 108 |
// `From` impl on a `jiff-core` error type for `jiff::Error`. (Because |
| 109 |
// that would make `jiff-core` a public dependency of `jiff`. Which means |
| 110 |
// any semver incompatible release of `jiff-core` would require a semver |
| 111 |
// incompatible release of `jiff`. Since `jiff-core` evolves more quickly |
| 112 |
// than `jiff`, this would be bad juju.) |
| 113 |
($name:ident, $ty:ident $(,)?) => { |
| 114 |
define_one_boundary_type!( |
| 115 |
$name, |
| 116 |
$ty, |
| 117 |
jcore::bounds::$name::WHAT, |
| 118 |
jcore::bounds::$name::MIN, |
| 119 |
jcore::bounds::$name::MAX, |
| 120 |
); |
| 121 |
}; |
| 122 |
} |
| 123 |
|
| 124 |
/// This macro writes out the boiler plate to define a boundary type. |
| 125 |
/// |
| 126 |
/// Specifically, it implements the `Bounds` trait and provides a few |
| 127 |
/// concrete methods. The concrete methods are mostly wrappers around |
| 128 |
/// the generic trait methods. They are provided so that callers don't |
| 129 |
/// have to import the `Bounds` trait to use them. |
| 130 |
macro_rules! define_bounds { |
| 131 |
($(( |
| 132 |
$name:ident, |
| 133 |
$ty:ident |
| 134 |
$($tt:tt)* |
| 135 |
)),* $(,)?) => { |
| 136 |
$( |
| 137 |
define_one_boundary_type!($name, $ty $($tt)*); |
| 138 |
)* |
| 139 |
|
| 140 |
/// An error that indicates a value is out of its intended range. |
| 141 |
#[derive(Clone, Debug)] |
| 142 |
#[cfg_attr(feature = "defmt", derive(defmt::Format))] |
| 143 |
pub(crate) enum BoundsError { |
| 144 |
$($name(RawBoundsError<$name>),)* |
| 145 |
} |
| 146 |
|
| 147 |
impl core::fmt::Display for BoundsError { |
| 148 |
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result { |
| 149 |
match *self { |
| 150 |
$(BoundsError::$name(ref err) => err.fmt(f),)* |
| 151 |
} |
| 152 |
} |
| 153 |
} |
| 154 |
} |
| 155 |
} |
| 156 |
|
| 157 |
// This is where we define all of Jiff's ranges. |
| 158 |
// |
| 159 |
// Well, that's not quite true. Many of them are actually defined in |
| 160 |
// `jiff-core`. For those, we still have an entry here that still produces |
| 161 |
// a boundary type, but it reuses the minimum and maximum values from |
| 162 |
// `jiff-core`. This is so `jiff` completely owns its own boundary types |
| 163 |
// (to avoid a public dep on `jiff-core`) while simultaneously preserving a |
| 164 |
// single point of truth for every range type. |
| 165 |
define_bounds! { |
| 166 |
(Century, i8, "century", 0, 99), |
| 167 |
(CivilDayNanosecond, i64), |
| 168 |
(CivilDaySecond, i32), |
| 169 |
(Day, i8), |
| 170 |
(DayOfYear, i16), |
| 171 |
(Hour, i8), |
| 172 |
(Hour12, i8, "hour (12 hour clock)", 1, 12), |
| 173 |
(ISOWeek, i8), |
| 174 |
(ISOYear, i16), |
| 175 |
// This matches Temporal's range. |
| 176 |
// See: https://github.com/tc39/proposal-temporal/issues/2458#issuecomment-1380742911 |
| 177 |
(Increment, i64, "rounding increment", 1, 1_000_000_000), |
| 178 |
(Increment32, i32, "rounding increment", 1, 1_000_000_000), |
| 179 |
// This is only used in parsing. A value of `60` gets clamped to `59`. |
| 180 |
(LeapSecond, i8, "second", 0, 60), |
| 181 |
(Microsecond, i16), |
| 182 |
(Millisecond, i16), |
| 183 |
(Minute, i8), |
| 184 |
(Month, i8), |
| 185 |
(Nanosecond, i16), |
| 186 |
(NthWeekday, i32), |
| 187 |
(OffsetHours, i8), |
| 188 |
(OffsetMinutes, i8), |
| 189 |
(OffsetSeconds, i8), |
| 190 |
(OffsetTotalSeconds, i32), |
| 191 |
(Second, i8), |
| 192 |
(SignedDurationSeconds, i64, "signed duration seconds", i64::MIN, i64::MAX), |
| 193 |
(SpanYears, i16, "years", -Self::MAX, (Year::LEN - 1) as i16), |
| 194 |
(SpanMonths, i32, "months", -Self::MAX, SpanYears::MAX as i32 * 12), |
| 195 |
(SpanWeeks, i32, "weeks", -Self::MAX, SpanDays::MAX / c::DAYS_PER_CIVIL_WEEK_32), |
| 196 |
(SpanDays, i32, "days", -Self::MAX, SpanHours::MAX / c::HOURS_PER_CIVIL_DAY_32), |
| 197 |
(SpanHours, i32, "hours", -Self::MAX, (SpanMinutes::MAX / c::MINS_PER_HOUR) as i32), |
| 198 |
(SpanMinutes, i64, "minutes", -Self::MAX, SpanSeconds::MAX / c::SECS_PER_MIN), |
| 199 |
( |
| 200 |
SpanSeconds, |
| 201 |
i64, |
| 202 |
"seconds", |
| 203 |
bounds::DeltaSeconds::MIN, |
| 204 |
bounds::DeltaSeconds::MAX, |
| 205 |
), |
| 206 |
( |
| 207 |
SpanMilliseconds, |
| 208 |
i64, |
| 209 |
"milliseconds", |
| 210 |
-Self::MAX, |
| 211 |
SpanSeconds::MAX * c::MILLIS_PER_SEC, |
| 212 |
), |
| 213 |
( |
| 214 |
SpanMicroseconds, |
| 215 |
i64, |
| 216 |
"microseconds", |
| 217 |
-Self::MAX, |
| 218 |
SpanMilliseconds::MAX * c::MICROS_PER_MILLI, |
| 219 |
), |
| 220 |
(SpanMultiple, i64, "span multiple", i64::MIN + 1, i64::MAX), |
| 221 |
// A range of the allowed number of nanoseconds. |
| 222 |
// |
| 223 |
// For this, we cannot cover the full span of supported time instants since |
| 224 |
// `UnixSeconds::MAX * NANOSECONDS_PER_SECOND` cannot fit into 64-bits. We |
| 225 |
// could use a `i128`, but it doesn't seem worth bloating up `Span`. |
| 226 |
// |
| 227 |
// Also note that our min is equal to -max, so that the total number of |
| 228 |
// values in this range is one less than the number of distinct `i64` |
| 229 |
// values. We do that so that the absolute value is always defined. |
| 230 |
(SpanNanoseconds, i64, "nanoseconds", i64::MIN + 1, i64::MAX), |
| 231 |
(SubsecNanosecond, i32), |
| 232 |
(SignedSubsecNanosecond, i32), |
| 233 |
(UnixEpochDays, i32), |
| 234 |
( |
| 235 |
UnixEpochMilliseconds, |
| 236 |
i64, |
| 237 |
"Unix timestamp milliseconds", |
| 238 |
UnixEpochSeconds::MIN * c::MILLIS_PER_SEC, |
| 239 |
UnixEpochSeconds::MAX * c::MILLIS_PER_SEC, |
| 240 |
), |
| 241 |
( |
| 242 |
UnixEpochMicroseconds, |
| 243 |
i64, |
| 244 |
"Unix timestamp microseconds", |
| 245 |
UnixEpochMilliseconds::MIN * c::MICROS_PER_MILLI, |
| 246 |
UnixEpochMilliseconds::MAX * c::MICROS_PER_MILLI, |
| 247 |
), |
| 248 |
(UnixEpochSeconds, i64), |
| 249 |
(WeekNum, i8, "week-number", 0, 53), |
| 250 |
(WeekdayMondayZero, i8), |
| 251 |
(WeekdayMondayOne, i8), |
| 252 |
(WeekdaySundayZero, i8), |
| 253 |
(WeekdaySundayOne, i8), |
| 254 |
// The range of years supported by Jiff. |
| 255 |
// |
| 256 |
// This is ultimately where some of the other ranges (like `UnixSeconds`) |
| 257 |
// were determined from. That is, the range of years is the primary point |
| 258 |
// at which the space of supported time instants is derived from. If one |
| 259 |
// wanted to expand this range, you'd need to change it here and then |
| 260 |
// compute the corresponding min/max values for `UnixSeconds`. (Among other |
| 261 |
// things... Increasing the supported Jiff range is far more complicated |
| 262 |
// than just changing some ranges here.) |
| 263 |
(Year, i16), |
| 264 |
(YearCE, i16), |
| 265 |
(YearBCE, i16), |
| 266 |
(YearTwoDigit, i16, "year (2 digits)", 0, 99), |
| 267 |
( |
| 268 |
ZonedDayNanoseconds, |
| 269 |
i64, |
| 270 |
"nanoseconds (in one zoned datetime day)", |
| 271 |
ZonedDaySeconds::MIN as i64 * c::NANOS_PER_SEC, |
| 272 |
ZonedDaySeconds::MAX as i64 * c::NANOS_PER_SEC, |
| 273 |
), |
| 274 |
// The number of seconds permitted in a single day. |
| 275 |
// |
| 276 |
// This is mostly just a "sensible" cap on what is possible. We allow one |
| 277 |
// day to span up to 7 civil days. |
| 278 |
// |
| 279 |
// It must also be at least 1 second long. |
| 280 |
( |
| 281 |
ZonedDaySeconds, |
| 282 |
i32, |
| 283 |
"seconds (in one zoned datetime day)", |
| 284 |
1, |
| 285 |
7 * c::SECS_PER_CIVIL_DAY_32, |
| 286 |
), |
| 287 |
} |
| 288 |
|
| 289 |
impl From<BoundsError> for Error { |
| 290 |
fn from(err: BoundsError) -> Error { |
| 291 |
Error::bounds(err) |
| 292 |
} |
| 293 |
} |
| 294 |
|
| 295 |
impl crate::error::IntoError for BoundsError { |
| 296 |
fn into_error(self) -> Error { |
| 297 |
self.into() |
| 298 |
} |
| 299 |
} |
| 300 |
|
| 301 |
/// Like `BoundsError`, but maintained manually. |
| 302 |
/// |
| 303 |
/// This is useful for range errors outside of the framework above. |
| 304 |
#[derive(Clone, Debug)] |
| 305 |
#[cfg_attr(feature = "defmt", derive(defmt::Format))] |
| 306 |
pub(crate) enum SpecialBoundsError { |
| 307 |
SignedDurationFloatOutOfRangeF32, |
| 308 |
SignedDurationFloatOutOfRangeF64, |
| 309 |
SignedToUnsignedDuration, |
| 310 |
} |
| 311 |
|
| 312 |
impl core::fmt::Display for SpecialBoundsError { |
| 313 |
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result { |
| 314 |
use self::SpecialBoundsError::*; |
| 315 |
|
| 316 |
match *self { |
| 317 |
SignedToUnsignedDuration => f.write_str( |
| 318 |
"negative signed durations cannot be converted \ |
| 319 |
to an unsigned duration", |
| 320 |
), |
| 321 |
SignedDurationFloatOutOfRangeF32 => { |
| 322 |
write!( |
| 323 |
f, |
| 324 |
"parameter 'floating point seconds' is not in \ |
| 325 |
the required range of {min}..={max}", |
| 326 |
min = i64::MIN as f32, |
| 327 |
max = i64::MAX as f32, |
| 328 |
) |
| 329 |
} |
| 330 |
SignedDurationFloatOutOfRangeF64 => { |
| 331 |
write!( |
| 332 |
f, |
| 333 |
"parameter 'floating point seconds' is not in \ |
| 334 |
the required range of {min}..={max}", |
| 335 |
min = i64::MIN as f64, |
| 336 |
max = i64::MAX as f64, |
| 337 |
) |
| 338 |
} |
| 339 |
} |
| 340 |
} |
| 341 |
} |
| 342 |
|
| 343 |
impl From<SpecialBoundsError> for Error { |
| 344 |
fn from(err: SpecialBoundsError) -> Error { |
| 345 |
Error::special_bounds(err) |
| 346 |
} |
| 347 |
} |
| 348 |
|
| 349 |
impl crate::error::IntoError for SpecialBoundsError { |
| 350 |
fn into_error(self) -> Error { |
| 351 |
self.into() |
| 352 |
} |
| 353 |
} |
| 354 |
|
| 355 |
#[cfg(test)] |
| 356 |
mod tests { |
| 357 |
use alloc::string::ToString; |
| 358 |
|
| 359 |
use super::*; |
| 360 |
|
| 361 |
#[test] |
| 362 |
fn size_of_bounds_error() { |
| 363 |
// It's okay if this grows, but I wrote this test initially |
| 364 |
// to confirm that a `BoundsError` is very small. (Since it's |
| 365 |
// just a bunch of variants of ZSTs.) |
| 366 |
assert_eq!(1, core::mem::size_of::<BoundsError>()); |
| 367 |
} |
| 368 |
|
| 369 |
#[test] |
| 370 |
fn basic_error_functionality() { |
| 371 |
let err = Year::check(10_000).unwrap_err(); |
| 372 |
assert_eq!( |
| 373 |
err.to_string(), |
| 374 |
"parameter 'year' is not in the required range of -9999..=9999", |
| 375 |
); |
| 376 |
} |
| 377 |
} |