| 1 | // auto-generated by: jiff-cli generate shared |
| 2 | |
| 3 | /*! |
| 4 | This module defines the internal core time data types. |
| 5 | |
| 6 | This includes physical time (i.e., a timestamp) and civil time. |
| 7 | |
| 8 | These types exist to provide a home for the core algorithms in a datetime |
| 9 | crate. For example, converting from a timestamp to a Gregorian calendar date |
| 10 | and clock time. |
| 11 | |
| 12 | These routines are specifically implemented on simple primitive integer types |
| 13 | and implicitly assume that the inputs are valid (i.e., within Jiff's minimum |
| 14 | and maximum ranges). |
| 15 | |
| 16 | These exist to provide `const` capabilities, and also to provide a small |
| 17 | reusable core of important algorithms that can be shared between `jiff` and |
| 18 | `jiff-static`. |
| 19 | |
| 20 | # Naming |
| 21 | |
| 22 | The types in this module are prefixed with letter `I` to make it clear that |
| 23 | they are internal types. Specifically, to distinguish them from Jiff's public |
| 24 | types. For example, `Date` versus `IDate`. |
| 25 | */ |
| 26 | |
| 27 | use super::error::{err, Error}; |
| 28 | |
| 29 | #[derive(Clone, Copy, Debug, Eq, PartialEq, PartialOrd, Ord)] |
| 30 | pub(crate) struct ITimestamp { |
| 31 | pub(crate) second: i64, |
| 32 | pub(crate) nanosecond: i32, |
| 33 | } |
| 34 | |
| 35 | impl ITimestamp { |
| 36 | const MIN: ITimestamp = |
| 37 | ITimestamp { second: -377705023201, nanosecond: 0 }; |
| 38 | const MAX: ITimestamp = |
| 39 | ITimestamp { second: 253402207200, nanosecond: 999_999_999 }; |
| 40 | |
| 41 | /// Creates an `ITimestamp` from a Unix timestamp in seconds. |
| 42 | #[inline] |
| 43 | pub(crate) const fn from_second(second: i64) -> ITimestamp { |
| 44 | ITimestamp { second, nanosecond: 0 } |
| 45 | } |
| 46 | |
| 47 | /// Converts a Unix timestamp with an offset to a Gregorian datetime. |
| 48 | /// |
| 49 | /// The offset should correspond to the number of seconds required to |
| 50 | /// add to this timestamp to get the local time. |
| 51 | #[cfg_attr(feature = "perf-inline", inline(always))] |
| 52 | pub(crate) const fn to_datetime(&self, offset: IOffset) -> IDateTime { |
| 53 | let ITimestamp { mut second, mut nanosecond } = *self; |
| 54 | second += offset.second as i64; |
| 55 | let mut epoch_day = second.div_euclid(86_400) as i32; |
| 56 | second = second.rem_euclid(86_400); |
| 57 | if nanosecond < 0 { |
| 58 | if second > 0 { |
| 59 | second -= 1; |
| 60 | nanosecond += 1_000_000_000; |
| 61 | } else { |
| 62 | epoch_day -= 1; |
| 63 | second += 86_399; |
| 64 | nanosecond += 1_000_000_000; |
| 65 | } |
| 66 | } |
| 67 | |
| 68 | let date = IEpochDay { epoch_day }.to_date(); |
| 69 | let mut time = ITimeSecond { second: second as i32 }.to_time(); |
| 70 | time.subsec_nanosecond = nanosecond; |
| 71 | IDateTime { date, time } |
| 72 | } |
| 73 | } |
| 74 | |
| 75 | #[derive(Clone, Copy, Debug, Eq, PartialEq, PartialOrd, Ord)] |
| 76 | pub(crate) struct IOffset { |
| 77 | pub(crate) second: i32, |
| 78 | } |
| 79 | |
| 80 | impl IOffset { |
| 81 | pub(crate) const UTC: IOffset = IOffset { second: 0 }; |
| 82 | } |
| 83 | |
| 84 | #[derive(Clone, Copy, Debug, Eq, PartialEq, PartialOrd, Ord)] |
| 85 | pub(crate) struct IDateTime { |
| 86 | pub(crate) date: IDate, |
| 87 | pub(crate) time: ITime, |
| 88 | } |
| 89 | |
| 90 | impl IDateTime { |
| 91 | const MIN: IDateTime = IDateTime { date: IDate::MIN, time: ITime::MIN }; |
| 92 | const MAX: IDateTime = IDateTime { date: IDate::MAX, time: ITime::MAX }; |
| 93 | |
| 94 | /// Converts a Gregorian datetime and its offset to a Unix timestamp. |
| 95 | /// |
| 96 | /// The offset should correspond to the number of seconds required to |
| 97 | /// subtract from this datetime in order to get to UTC. |
| 98 | #[cfg_attr(feature = "perf-inline", inline(always))] |
| 99 | pub(crate) fn to_timestamp(&self, offset: IOffset) -> ITimestamp { |
| 100 | let epoch_day = self.date.to_epoch_day().epoch_day; |
| 101 | let mut second = (epoch_day as i64) * 86_400 |
| 102 | + (self.time.to_second().second as i64); |
| 103 | let mut nanosecond = self.time.subsec_nanosecond; |
| 104 | second -= offset.second as i64; |
| 105 | if epoch_day < 0 && nanosecond != 0 { |
| 106 | second += 1; |
| 107 | nanosecond -= 1_000_000_000; |
| 108 | } |
| 109 | ITimestamp { second, nanosecond } |
| 110 | } |
| 111 | |
| 112 | /// Converts a Gregorian datetime and its offset to a Unix timestamp. |
| 113 | /// |
| 114 | /// If the timestamp would overflow Jiff's timestamp range, then this |
| 115 | /// returns `None`. |
| 116 | /// |
| 117 | /// The offset should correspond to the number of seconds required to |
| 118 | /// subtract from this datetime in order to get to UTC. |
| 119 | #[cfg_attr(feature = "perf-inline", inline(always))] |
| 120 | pub(crate) fn to_timestamp_checked( |
| 121 | &self, |
| 122 | offset: IOffset, |
| 123 | ) -> Option<ITimestamp> { |
| 124 | let ts = self.to_timestamp(offset); |
| 125 | if !(ITimestamp::MIN <= ts && ts <= ITimestamp::MAX) { |
| 126 | return None; |
| 127 | } |
| 128 | Some(ts) |
| 129 | } |
| 130 | |
| 131 | #[cfg_attr(feature = "perf-inline", inline(always))] |
| 132 | pub(crate) fn saturating_add_seconds(&self, seconds: i32) -> IDateTime { |
| 133 | self.checked_add_seconds(seconds).unwrap_or_else(|_| { |
| 134 | if seconds < 0 { |
| 135 | IDateTime::MIN |
| 136 | } else { |
| 137 | IDateTime::MAX |
| 138 | } |
| 139 | }) |
| 140 | } |
| 141 | |
| 142 | #[cfg_attr(feature = "perf-inline", inline(always))] |
| 143 | pub(crate) fn checked_add_seconds( |
| 144 | &self, |
| 145 | seconds: i32, |
| 146 | ) -> Result<IDateTime, Error> { |
| 147 | let day_second = |
| 148 | self.time.to_second().second.checked_add(seconds).ok_or_else( |
| 149 | || err!("adding `{seconds}s` to datetime overflowed"), |
| 150 | )?; |
| 151 | let days = day_second.div_euclid(86400); |
| 152 | let second = day_second.rem_euclid(86400); |
| 153 | let date = self.date.checked_add_days(days)?; |
| 154 | let time = ITimeSecond { second }.to_time(); |
| 155 | Ok(IDateTime { date, time }) |
| 156 | } |
| 157 | } |
| 158 | |
| 159 | #[derive(Clone, Copy, Debug, Eq, PartialEq, PartialOrd, Ord)] |
| 160 | pub(crate) struct IEpochDay { |
| 161 | pub(crate) epoch_day: i32, |
| 162 | } |
| 163 | |
| 164 | impl IEpochDay { |
| 165 | const MIN: IEpochDay = IEpochDay { epoch_day: -4371587 }; |
| 166 | const MAX: IEpochDay = IEpochDay { epoch_day: 2932896 }; |
| 167 | |
| 168 | /// Converts days since the Unix epoch to a Gregorian date. |
| 169 | /// |
| 170 | /// This is Neri-Schneider. There's no branching or divisions. |
| 171 | /// |
| 172 | /// Ref: <https://github.com/cassioneri/eaf/blob/684d3cc32d14eee371d0abe4f683d6d6a49ed5c1/algorithms/neri_schneider.hpp#L40C3-L40C34> |
| 173 | #[cfg_attr(feature = "perf-inline", inline(always))] |
| 174 | #[allow(non_upper_case_globals, non_snake_case)] // to mimic source |
| 175 | pub(crate) const fn to_date(&self) -> IDate { |
| 176 | const s: u32 = 82; |
| 177 | const K: u32 = 719468 + 146097 * s; |
| 178 | const L: u32 = 400 * s; |
| 179 | |
| 180 | let N_U = self.epoch_day as u32; |
| 181 | let N = N_U.wrapping_add(K); |
| 182 | |
| 183 | let N_1 = 4 * N + 3; |
| 184 | let C = N_1 / 146097; |
| 185 | let N_C = (N_1 % 146097) / 4; |
| 186 | |
| 187 | let N_2 = 4 * N_C + 3; |
| 188 | let P_2 = 2939745 * (N_2 as u64); |
| 189 | let Z = (P_2 / 4294967296) as u32; |
| 190 | let N_Y = (P_2 % 4294967296) as u32 / 2939745 / 4; |
| 191 | let Y = 100 * C + Z; |
| 192 | |
| 193 | let N_3 = 2141 * N_Y + 197913; |
| 194 | let M = N_3 / 65536; |
| 195 | let D = (N_3 % 65536) / 2141; |
| 196 | |
| 197 | let J = N_Y >= 306; |
| 198 | let year = Y.wrapping_sub(L).wrapping_add(J as u32) as i16; |
| 199 | let month = (if J { M - 12 } else { M }) as i8; |
| 200 | let day = (D + 1) as i8; |
| 201 | IDate { year, month, day } |
| 202 | } |
| 203 | |
| 204 | /// Returns the day of the week for this epoch day. |
| 205 | #[cfg_attr(feature = "perf-inline", inline(always))] |
| 206 | pub(crate) const fn weekday(&self) -> IWeekday { |
| 207 | // Based on Hinnant's approach here, although we use ISO weekday |
| 208 | // numbering by default. Basically, this works by using the knowledge |
| 209 | // that 1970-01-01 was a Thursday. |
| 210 | // |
| 211 | // Ref: http://howardhinnant.github.io/date_algorithms.html |
| 212 | IWeekday::from_monday_zero_offset( |
| 213 | (self.epoch_day + 3).rem_euclid(7) as i8 |
| 214 | ) |
| 215 | } |
| 216 | |
| 217 | /// Add the given number of days to this epoch day. |
| 218 | /// |
| 219 | /// If this would overflow an `i32` or result in an out-of-bounds epoch |
| 220 | /// day, then this returns an error. |
| 221 | #[inline] |
| 222 | pub(crate) fn checked_add(&self, amount: i32) -> Result<IEpochDay, Error> { |
| 223 | let epoch_day = self.epoch_day; |
| 224 | let sum = epoch_day.checked_add(amount).ok_or_else(|| { |
| 225 | err!("adding `{amount}` to epoch day `{epoch_day}` overflowed i32") |
| 226 | })?; |
| 227 | let ret = IEpochDay { epoch_day: sum }; |
| 228 | if !(IEpochDay::MIN <= ret && ret <= IEpochDay::MAX) { |
| 229 | return Err(err!( |
| 230 | "adding `{amount}` to epoch day `{epoch_day}` \ |
| 231 | resulted in `{sum}`, which is not in the required \ |
| 232 | epoch day range of `{min}..={max}`", |
| 233 | min = IEpochDay::MIN.epoch_day, |
| 234 | max = IEpochDay::MAX.epoch_day, |
| 235 | )); |
| 236 | } |
| 237 | Ok(ret) |
| 238 | } |
| 239 | } |
| 240 | |
| 241 | #[derive(Clone, Copy, Debug, Eq, PartialEq, PartialOrd, Ord)] |
| 242 | pub(crate) struct IDate { |
| 243 | pub(crate) year: i16, |
| 244 | pub(crate) month: i8, |
| 245 | pub(crate) day: i8, |
| 246 | } |
| 247 | |
| 248 | impl IDate { |
| 249 | const MIN: IDate = IDate { year: -9999, month: 1, day: 1 }; |
| 250 | const MAX: IDate = IDate { year: 9999, month: 12, day: 31 }; |
| 251 | |
| 252 | /// Fallibly builds a new date. |
| 253 | /// |
| 254 | /// This checks that the given day is valid for the given year/month. |
| 255 | /// |
| 256 | /// No other conditions are checked. This assumes `year` and `month` are |
| 257 | /// valid, and that `day >= 1`. |
| 258 | #[inline] |
| 259 | pub(crate) fn try_new( |
| 260 | year: i16, |
| 261 | month: i8, |
| 262 | day: i8, |
| 263 | ) -> Result<IDate, Error> { |
| 264 | if day > 28 { |
| 265 | let max_day = days_in_month(year, month); |
| 266 | if day > max_day { |
| 267 | return Err(err!( |
| 268 | "day={day} is out of range for year={year} \ |
| 269 | and month={month}, must be in range 1..={max_day}", |
| 270 | )); |
| 271 | } |
| 272 | } |
| 273 | Ok(IDate { year, month, day }) |
| 274 | } |
| 275 | |
| 276 | /// Returns the date corresponding to the day of the given year. The day |
| 277 | /// of the year should be a value in `1..=366`, with `366` only being valid |
| 278 | /// if `year` is a leap year. |
| 279 | /// |
| 280 | /// This assumes that `year` is valid, but returns an error if `day` is |
| 281 | /// not in the range `1..=366`. |
| 282 | #[inline] |
| 283 | pub(crate) fn from_day_of_year( |
| 284 | year: i16, |
| 285 | day: i16, |
| 286 | ) -> Result<IDate, Error> { |
| 287 | if !(1 <= day && day <= 366) { |
| 288 | return Err(err!( |
| 289 | "day-of-year={day} is out of range for year={year}, \ |
| 290 | must be in range 1..={max_day}", |
| 291 | max_day = days_in_year(year), |
| 292 | )); |
| 293 | } |
| 294 | let start = IDate { year, month: 1, day: 1 }.to_epoch_day(); |
| 295 | let end = start |
| 296 | .checked_add(i32::from(day) - 1) |
| 297 | .map_err(|_| { |
| 298 | err!( |
| 299 | "failed to find date for \ |
| 300 | year={year} and day-of-year={day}: \ |
| 301 | adding `{day}` to `{start}` overflows \ |
| 302 | Jiff's range", |
| 303 | start = start.epoch_day, |
| 304 | ) |
| 305 | })? |
| 306 | .to_date(); |
| 307 | // If we overflowed into the next year, then `day` is too big. |
| 308 | if year != end.year { |
| 309 | // Can only happen given day=366 and this is a leap year. |
| 310 | debug_assert_eq!(day, 366); |
| 311 | debug_assert!(!is_leap_year(year)); |
| 312 | return Err(err!( |
| 313 | "day-of-year={day} is out of range for year={year}, \ |
| 314 | must be in range 1..={max_day}", |
| 315 | max_day = days_in_year(year), |
| 316 | )); |
| 317 | } |
| 318 | Ok(end) |
| 319 | } |
| 320 | |
| 321 | /// Returns the date corresponding to the day of the given year. The day |
| 322 | /// of the year should be a value in `1..=365`, with February 29 being |
| 323 | /// completely ignored. That is, it is guaranteed that February 29 will |
| 324 | /// never be returned by this function. It is impossible. |
| 325 | /// |
| 326 | /// This assumes that `year` is valid, but returns an error if `day` is |
| 327 | /// not in the range `1..=365`. |
| 328 | #[inline] |
| 329 | pub(crate) fn from_day_of_year_no_leap( |
| 330 | year: i16, |
| 331 | mut day: i16, |
| 332 | ) -> Result<IDate, Error> { |
| 333 | if !(1 <= day && day <= 365) { |
| 334 | return Err(err!( |
| 335 | "day-of-year={day} is out of range for year={year}, \ |
| 336 | must be in range 1..=365", |
| 337 | )); |
| 338 | } |
| 339 | if day >= 60 && is_leap_year(year) { |
| 340 | day += 1; |
| 341 | } |
| 342 | // The boundary check above guarantees this always succeeds. |
| 343 | Ok(IDate::from_day_of_year(year, day).unwrap()) |
| 344 | } |
| 345 | |
| 346 | /// Converts a Gregorian date to days since the Unix epoch. |
| 347 | /// |
| 348 | /// This is Neri-Schneider. There's no branching or divisions. |
| 349 | /// |
| 350 | /// Ref: https://github.com/cassioneri/eaf/blob/684d3cc32d14eee371d0abe4f683d6d6a49ed5c1/algorithms/neri_schneider.hpp#L83 |
| 351 | #[cfg_attr(feature = "perf-inline", inline(always))] |
| 352 | #[allow(non_upper_case_globals, non_snake_case)] // to mimic source |
| 353 | pub(crate) const fn to_epoch_day(&self) -> IEpochDay { |
| 354 | const s: u32 = 82; |
| 355 | const K: u32 = 719468 + 146097 * s; |
| 356 | const L: u32 = 400 * s; |
| 357 | |
| 358 | let year = self.year as u32; |
| 359 | let month = self.month as u32; |
| 360 | let day = self.day as u32; |
| 361 | |
| 362 | let J = month <= 2; |
| 363 | let Y = year.wrapping_add(L).wrapping_sub(J as u32); |
| 364 | let M = if J { month + 12 } else { month }; |
| 365 | let D = day - 1; |
| 366 | let C = Y / 100; |
| 367 | |
| 368 | let y_star = 1461 * Y / 4 - C + C / 4; |
| 369 | let m_star = (979 * M - 2919) / 32; |
| 370 | let N = y_star + m_star + D; |
| 371 | |
| 372 | let N_U = N.wrapping_sub(K); |
| 373 | let epoch_day = N_U as i32; |
| 374 | IEpochDay { epoch_day } |
| 375 | } |
| 376 | |
| 377 | /// Returns the day of the week for this date. |
| 378 | #[inline] |
| 379 | pub(crate) const fn weekday(&self) -> IWeekday { |
| 380 | self.to_epoch_day().weekday() |
| 381 | } |
| 382 | |
| 383 | /// Returns the `nth` weekday of the month represented by this date. |
| 384 | /// |
| 385 | /// `nth` must be non-zero and otherwise in the range `-5..=5`. If it |
| 386 | /// isn't, an error is returned. |
| 387 | /// |
| 388 | /// This also returns an error if `abs(nth)==5` and there is no "5th" |
| 389 | /// weekday of this month. |
| 390 | #[inline] |
| 391 | pub(crate) fn nth_weekday_of_month( |
| 392 | &self, |
| 393 | nth: i8, |
| 394 | weekday: IWeekday, |
| 395 | ) -> Result<IDate, Error> { |
| 396 | if nth == 0 || !(-5 <= nth && nth <= 5) { |
| 397 | return Err(err!( |
| 398 | "got nth weekday of `{nth}`, but \ |
| 399 | must be non-zero and in range `-5..=5`", |
| 400 | )); |
| 401 | } |
| 402 | if nth > 0 { |
| 403 | let first_weekday = self.first_of_month().weekday(); |
| 404 | let diff = weekday.since(first_weekday); |
| 405 | let day = diff + 1 + (nth - 1) * 7; |
| 406 | IDate::try_new(self.year, self.month, day) |
| 407 | } else { |
| 408 | let last = self.last_of_month(); |
| 409 | let last_weekday = last.weekday(); |
| 410 | let diff = last_weekday.since(weekday); |
| 411 | let day = last.day - diff - (nth.abs() - 1) * 7; |
| 412 | // Our math can go below 1 when nth is -5 and there is no "5th from |
| 413 | // last" weekday in this month. Since this is outside the bounds |
| 414 | // of `Day`, we can't let this boundary condition escape. So we |
| 415 | // check it here. |
| 416 | if day < 1 { |
| 417 | return Err(err!( |
| 418 | "day={day} is out of range for year={year} \ |
| 419 | and month={month}, must be in range 1..={max_day}", |
| 420 | year = self.year, |
| 421 | month = self.month, |
| 422 | max_day = days_in_month(self.year, self.month), |
| 423 | )); |
| 424 | } |
| 425 | IDate::try_new(self.year, self.month, day) |
| 426 | } |
| 427 | } |
| 428 | |
| 429 | /// Returns the day before this date. |
| 430 | #[inline] |
| 431 | pub(crate) fn yesterday(self) -> Result<IDate, Error> { |
| 432 | if self.day == 1 { |
| 433 | if self.month == 1 { |
| 434 | let year = self.year - 1; |
| 435 | if year <= -10000 { |
| 436 | return Err(err!( |
| 437 | "returning yesterday for -9999-01-01 is not \ |
| 438 | possible because it is less than Jiff's supported |
| 439 | minimum date", |
| 440 | )); |
| 441 | } |
| 442 | return Ok(IDate { year, month: 12, day: 31 }); |
| 443 | } |
| 444 | let month = self.month - 1; |
| 445 | let day = days_in_month(self.year, month); |
| 446 | return Ok(IDate { month, day, ..self }); |
| 447 | } |
| 448 | Ok(IDate { day: self.day - 1, ..self }) |
| 449 | } |
| 450 | |
| 451 | /// Returns the day after this date. |
| 452 | #[inline] |
| 453 | pub(crate) fn tomorrow(self) -> Result<IDate, Error> { |
| 454 | if self.day >= 28 && self.day == days_in_month(self.year, self.month) { |
| 455 | if self.month == 12 { |
| 456 | let year = self.year + 1; |
| 457 | if year >= 10000 { |
| 458 | return Err(err!( |
| 459 | "returning tomorrow for 9999-12-31 is not \ |
| 460 | possible because it is greater than Jiff's supported |
| 461 | maximum date", |
| 462 | )); |
| 463 | } |
| 464 | return Ok(IDate { year, month: 1, day: 1 }); |
| 465 | } |
| 466 | let month = self.month + 1; |
| 467 | return Ok(IDate { month, day: 1, ..self }); |
| 468 | } |
| 469 | Ok(IDate { day: self.day + 1, ..self }) |
| 470 | } |
| 471 | |
| 472 | /// Returns the year one year before this date. |
| 473 | #[inline] |
| 474 | pub(crate) fn prev_year(self) -> Result<i16, Error> { |
| 475 | let year = self.year - 1; |
| 476 | if year <= -10_000 { |
| 477 | return Err(err!( |
| 478 | "returning previous year for {year:04}-{month:02}-{day:02} is \ |
| 479 | not possible because it is less than Jiff's supported \ |
| 480 | minimum date", |
| 481 | year = self.year, |
| 482 | month = self.month, |
| 483 | day = self.day, |
| 484 | )); |
| 485 | } |
| 486 | Ok(year) |
| 487 | } |
| 488 | |
| 489 | /// Returns the year one year from this date. |
| 490 | #[inline] |
| 491 | pub(crate) fn next_year(self) -> Result<i16, Error> { |
| 492 | let year = self.year + 1; |
| 493 | if year >= 10_000 { |
| 494 | return Err(err!( |
| 495 | "returning next year for {year:04}-{month:02}-{day:02} is \ |
| 496 | not possible because it is greater than Jiff's supported \ |
| 497 | maximum date", |
| 498 | year = self.year, |
| 499 | month = self.month, |
| 500 | day = self.day, |
| 501 | )); |
| 502 | } |
| 503 | Ok(year) |
| 504 | } |
| 505 | |
| 506 | /// Add the number of days to this date. |
| 507 | #[inline] |
| 508 | pub(crate) fn checked_add_days( |
| 509 | &self, |
| 510 | amount: i32, |
| 511 | ) -> Result<IDate, Error> { |
| 512 | match amount { |
| 513 | 0 => Ok(*self), |
| 514 | -1 => self.yesterday(), |
| 515 | 1 => self.tomorrow(), |
| 516 | n => self.to_epoch_day().checked_add(n).map(|d| d.to_date()), |
| 517 | } |
| 518 | } |
| 519 | |
| 520 | #[inline] |
| 521 | fn first_of_month(&self) -> IDate { |
| 522 | IDate { day: 1, ..*self } |
| 523 | } |
| 524 | |
| 525 | #[inline] |
| 526 | fn last_of_month(&self) -> IDate { |
| 527 | IDate { day: days_in_month(self.year, self.month), ..*self } |
| 528 | } |
| 529 | |
| 530 | #[cfg(test)] |
| 531 | pub(crate) fn at( |
| 532 | &self, |
| 533 | hour: i8, |
| 534 | minute: i8, |
| 535 | second: i8, |
| 536 | subsec_nanosecond: i32, |
| 537 | ) -> IDateTime { |
| 538 | let time = ITime { hour, minute, second, subsec_nanosecond }; |
| 539 | IDateTime { date: *self, time } |
| 540 | } |
| 541 | } |
| 542 | |
| 543 | /// Represents a clock time. |
| 544 | /// |
| 545 | /// This uses units of hours, minutes, seconds and fractional seconds (to |
| 546 | /// nanosecond precision). |
| 547 | #[derive(Clone, Copy, Debug, Eq, PartialEq, PartialOrd, Ord)] |
| 548 | pub(crate) struct ITime { |
| 549 | pub(crate) hour: i8, |
| 550 | pub(crate) minute: i8, |
| 551 | pub(crate) second: i8, |
| 552 | pub(crate) subsec_nanosecond: i32, |
| 553 | } |
| 554 | |
| 555 | impl ITime { |
| 556 | pub(crate) const ZERO: ITime = |
| 557 | ITime { hour: 0, minute: 0, second: 0, subsec_nanosecond: 0 }; |
| 558 | pub(crate) const MIN: ITime = |
| 559 | ITime { hour: 0, minute: 0, second: 0, subsec_nanosecond: 0 }; |
| 560 | pub(crate) const MAX: ITime = ITime { |
| 561 | hour: 23, |
| 562 | minute: 59, |
| 563 | second: 59, |
| 564 | subsec_nanosecond: 999_999_999, |
| 565 | }; |
| 566 | |
| 567 | #[cfg_attr(feature = "perf-inline", inline(always))] |
| 568 | pub(crate) const fn to_second(&self) -> ITimeSecond { |
| 569 | let mut second: i32 = 0; |
| 570 | second += (self.hour as i32) * 3600; |
| 571 | second += (self.minute as i32) * 60; |
| 572 | second += self.second as i32; |
| 573 | ITimeSecond { second } |
| 574 | } |
| 575 | |
| 576 | #[cfg_attr(feature = "perf-inline", inline(always))] |
| 577 | pub(crate) const fn to_nanosecond(&self) -> ITimeNanosecond { |
| 578 | let mut nanosecond: i64 = 0; |
| 579 | nanosecond += (self.hour as i64) * 3_600_000_000_000; |
| 580 | nanosecond += (self.minute as i64) * 60_000_000_000; |
| 581 | nanosecond += (self.second as i64) * 1_000_000_000; |
| 582 | nanosecond += self.subsec_nanosecond as i64; |
| 583 | ITimeNanosecond { nanosecond } |
| 584 | } |
| 585 | } |
| 586 | |
| 587 | /// Represents a single point in the day, to second precision. |
| 588 | #[derive(Clone, Copy, Debug, Eq, PartialEq, PartialOrd, Ord)] |
| 589 | pub(crate) struct ITimeSecond { |
| 590 | pub(crate) second: i32, |
| 591 | } |
| 592 | |
| 593 | impl ITimeSecond { |
| 594 | #[cfg_attr(feature = "perf-inline", inline(always))] |
| 595 | pub(crate) const fn to_time(&self) -> ITime { |
| 596 | let mut second = self.second; |
| 597 | let mut time = ITime::ZERO; |
| 598 | if second != 0 { |
| 599 | time.hour = (second / 3600) as i8; |
| 600 | second %= 3600; |
| 601 | if second != 0 { |
| 602 | time.minute = (second / 60) as i8; |
| 603 | time.second = (second % 60) as i8; |
| 604 | } |
| 605 | } |
| 606 | time |
| 607 | } |
| 608 | } |
| 609 | |
| 610 | /// Represents a single point in the day, to nanosecond precision. |
| 611 | #[derive(Clone, Copy, Debug, Eq, PartialEq, PartialOrd, Ord)] |
| 612 | pub(crate) struct ITimeNanosecond { |
| 613 | pub(crate) nanosecond: i64, |
| 614 | } |
| 615 | |
| 616 | impl ITimeNanosecond { |
| 617 | #[cfg_attr(feature = "perf-inline", inline(always))] |
| 618 | pub(crate) const fn to_time(&self) -> ITime { |
| 619 | let mut nanosecond = self.nanosecond; |
| 620 | let mut time = ITime::ZERO; |
| 621 | if nanosecond != 0 { |
| 622 | time.hour = (nanosecond / 3_600_000_000_000) as i8; |
| 623 | nanosecond %= 3_600_000_000_000; |
| 624 | if nanosecond != 0 { |
| 625 | time.minute = (nanosecond / 60_000_000_000) as i8; |
| 626 | nanosecond %= 60_000_000_000; |
| 627 | if nanosecond != 0 { |
| 628 | time.second = (nanosecond / 1_000_000_000) as i8; |
| 629 | time.subsec_nanosecond = |
| 630 | (nanosecond % 1_000_000_000) as i32; |
| 631 | } |
| 632 | } |
| 633 | } |
| 634 | time |
| 635 | } |
| 636 | } |
| 637 | |
| 638 | /// Represents a weekday. |
| 639 | #[derive(Clone, Copy, Debug, Eq, PartialEq, PartialOrd, Ord)] |
| 640 | pub(crate) struct IWeekday { |
| 641 | /// Range is `1..=6` with `1=Monday`. |
| 642 | offset: i8, |
| 643 | } |
| 644 | |
| 645 | impl IWeekday { |
| 646 | /// Creates a weekday assuming the week starts on Monday and Monday is at |
| 647 | /// offset `0`. |
| 648 | #[inline] |
| 649 | pub(crate) const fn from_monday_zero_offset(offset: i8) -> IWeekday { |
| 650 | assert!(0 <= offset && offset <= 6); |
| 651 | IWeekday::from_monday_one_offset(offset + 1) |
| 652 | } |
| 653 | |
| 654 | /// Creates a weekday assuming the week starts on Monday and Monday is at |
| 655 | /// offset `1`. |
| 656 | #[inline] |
| 657 | pub(crate) const fn from_monday_one_offset(offset: i8) -> IWeekday { |
| 658 | assert!(1 <= offset && offset <= 7); |
| 659 | IWeekday { offset } |
| 660 | } |
| 661 | |
| 662 | /// Creates a weekday assuming the week starts on Sunday and Sunday is at |
| 663 | /// offset `0`. |
| 664 | #[inline] |
| 665 | pub(crate) const fn from_sunday_zero_offset(offset: i8) -> IWeekday { |
| 666 | assert!(0 <= offset && offset <= 6); |
| 667 | IWeekday::from_monday_zero_offset((offset - 1).rem_euclid(7)) |
| 668 | } |
| 669 | |
| 670 | /// Creates a weekday assuming the week starts on Sunday and Sunday is at |
| 671 | /// offset `1`. |
| 672 | #[cfg(test)] // currently dead code |
| 673 | #[inline] |
| 674 | pub(crate) const fn from_sunday_one_offset(offset: i8) -> IWeekday { |
| 675 | assert!(1 <= offset && offset <= 7); |
| 676 | IWeekday::from_sunday_zero_offset(offset - 1) |
| 677 | } |
| 678 | |
| 679 | /// Returns this weekday as an offset in the range `0..=6` where |
| 680 | /// `0=Monday`. |
| 681 | #[inline] |
| 682 | pub(crate) const fn to_monday_zero_offset(self) -> i8 { |
| 683 | self.to_monday_one_offset() - 1 |
| 684 | } |
| 685 | |
| 686 | /// Returns this weekday as an offset in the range `1..=7` where |
| 687 | /// `1=Monday`. |
| 688 | #[inline] |
| 689 | pub(crate) const fn to_monday_one_offset(self) -> i8 { |
| 690 | self.offset |
| 691 | } |
| 692 | |
| 693 | /// Returns this weekday as an offset in the range `0..=6` where |
| 694 | /// `0=Sunday`. |
| 695 | #[cfg(test)] // currently dead code |
| 696 | #[inline] |
| 697 | pub(crate) const fn to_sunday_zero_offset(self) -> i8 { |
| 698 | (self.to_monday_zero_offset() + 1) % 7 |
| 699 | } |
| 700 | |
| 701 | /// Returns this weekday as an offset in the range `1..=7` where |
| 702 | /// `1=Sunday`. |
| 703 | #[cfg(test)] // currently dead code |
| 704 | #[inline] |
| 705 | pub(crate) const fn to_sunday_one_offset(self) -> i8 { |
| 706 | self.to_sunday_zero_offset() + 1 |
| 707 | } |
| 708 | |
| 709 | #[inline] |
| 710 | pub(crate) const fn since(self, other: IWeekday) -> i8 { |
| 711 | (self.to_monday_zero_offset() - other.to_monday_zero_offset()) |
| 712 | .rem_euclid(7) |
| 713 | } |
| 714 | } |
| 715 | |
| 716 | #[derive(Clone, Copy, Debug, Eq, PartialEq)] |
| 717 | pub(crate) enum IAmbiguousOffset { |
| 718 | Unambiguous { offset: IOffset }, |
| 719 | Gap { before: IOffset, after: IOffset }, |
| 720 | Fold { before: IOffset, after: IOffset }, |
| 721 | } |
| 722 | |
| 723 | /// Returns true if and only if the given year is a leap year. |
| 724 | /// |
| 725 | /// A leap year is a year with 366 days. Typical years have 365 days. |
| 726 | #[inline] |
| 727 | pub(crate) const fn is_leap_year(year: i16) -> bool { |
| 728 | // From: https://github.com/BurntSushi/jiff/pull/23 |
| 729 | let d = if year % 25 != 0 { 4 } else { 16 }; |
| 730 | (year % d) == 0 |
| 731 | } |
| 732 | |
| 733 | /// Return the number of days in the given year. |
| 734 | #[inline] |
| 735 | pub(crate) const fn days_in_year(year: i16) -> i16 { |
| 736 | if is_leap_year(year) { |
| 737 | 366 |
| 738 | } else { |
| 739 | 365 |
| 740 | } |
| 741 | } |
| 742 | |
| 743 | /// Return the number of days in the given month. |
| 744 | #[inline] |
| 745 | pub(crate) const fn days_in_month(year: i16, month: i8) -> i8 { |
| 746 | // From: https://github.com/BurntSushi/jiff/pull/23 |
| 747 | if month == 2 { |
| 748 | if is_leap_year(year) { |
| 749 | 29 |
| 750 | } else { |
| 751 | 28 |
| 752 | } |
| 753 | } else { |
| 754 | 30 | (month ^ month >> 3) |
| 755 | } |
| 756 | } |
| 757 | |
| 758 | #[cfg(test)] |
| 759 | mod tests { |
| 760 | use super::*; |
| 761 | |
| 762 | #[test] |
| 763 | fn roundtrip_epochday_date() { |
| 764 | for year in -9999..=9999 { |
| 765 | for month in 1..=12 { |
| 766 | for day in 1..=days_in_month(year, month) { |
| 767 | let date = IDate { year, month, day }; |
| 768 | let epoch_day = date.to_epoch_day(); |
| 769 | let date_roundtrip = epoch_day.to_date(); |
| 770 | assert_eq!(date, date_roundtrip); |
| 771 | } |
| 772 | } |
| 773 | } |
| 774 | } |
| 775 | |
| 776 | #[test] |
| 777 | fn roundtrip_second_time() { |
| 778 | for second in 0..=86_399 { |
| 779 | let second = ITimeSecond { second }; |
| 780 | let time = second.to_time(); |
| 781 | let second_roundtrip = time.to_second(); |
| 782 | assert_eq!(second, second_roundtrip); |
| 783 | } |
| 784 | } |
| 785 | |
| 786 | #[test] |
| 787 | fn roundtrip_nanosecond_time() { |
| 788 | for second in 0..=86_399 { |
| 789 | for nanosecond in |
| 790 | [0, 250_000_000, 500_000_000, 750_000_000, 900_000_000] |
| 791 | { |
| 792 | let nanosecond = ITimeNanosecond { |
| 793 | nanosecond: (second * 1_000_000_000 + nanosecond), |
| 794 | }; |
| 795 | let time = nanosecond.to_time(); |
| 796 | let nanosecond_roundtrip = time.to_nanosecond(); |
| 797 | assert_eq!(nanosecond, nanosecond_roundtrip); |
| 798 | } |
| 799 | } |
| 800 | } |
| 801 | |
| 802 | #[test] |
| 803 | fn nth_weekday() { |
| 804 | let d1 = IDate { year: 2017, month: 3, day: 1 }; |
| 805 | let wday = IWeekday::from_sunday_zero_offset(5); |
| 806 | let d2 = d1.nth_weekday_of_month(2, wday).unwrap(); |
| 807 | assert_eq!(d2, IDate { year: 2017, month: 3, day: 10 }); |
| 808 | |
| 809 | let d1 = IDate { year: 2024, month: 3, day: 1 }; |
| 810 | let wday = IWeekday::from_sunday_zero_offset(4); |
| 811 | let d2 = d1.nth_weekday_of_month(-1, wday).unwrap(); |
| 812 | assert_eq!(d2, IDate { year: 2024, month: 3, day: 28 }); |
| 813 | |
| 814 | let d1 = IDate { year: 2024, month: 3, day: 25 }; |
| 815 | let wday = IWeekday::from_sunday_zero_offset(1); |
| 816 | assert!(d1.nth_weekday_of_month(5, wday).is_err()); |
| 817 | assert!(d1.nth_weekday_of_month(-5, wday).is_err()); |
| 818 | |
| 819 | let d1 = IDate { year: 1998, month: 1, day: 1 }; |
| 820 | let wday = IWeekday::from_sunday_zero_offset(6); |
| 821 | let d2 = d1.nth_weekday_of_month(5, wday).unwrap(); |
| 822 | assert_eq!(d2, IDate { year: 1998, month: 1, day: 31 }); |
| 823 | } |
| 824 | |
| 825 | #[test] |
| 826 | fn weekday() { |
| 827 | let wday = IWeekday::from_sunday_zero_offset(0); |
| 828 | assert_eq!(wday.to_monday_one_offset(), 7); |
| 829 | |
| 830 | let wday = IWeekday::from_monday_one_offset(7); |
| 831 | assert_eq!(wday.to_sunday_zero_offset(), 0); |
| 832 | |
| 833 | let wday = IWeekday::from_sunday_one_offset(1); |
| 834 | assert_eq!(wday.to_monday_zero_offset(), 6); |
| 835 | |
| 836 | let wday = IWeekday::from_monday_zero_offset(6); |
| 837 | assert_eq!(wday.to_sunday_one_offset(), 1); |
| 838 | } |
| 839 | |
| 840 | #[test] |
| 841 | fn weekday_since() { |
| 842 | let wday1 = IWeekday::from_sunday_zero_offset(0); |
| 843 | let wday2 = IWeekday::from_sunday_zero_offset(6); |
| 844 | assert_eq!(wday2.since(wday1), 6); |
| 845 | assert_eq!(wday1.since(wday2), 1); |
| 846 | } |
| 847 | |
| 848 | #[test] |
| 849 | fn leap_year() { |
| 850 | assert!(!is_leap_year(1900)); |
| 851 | assert!(is_leap_year(2000)); |
| 852 | assert!(!is_leap_year(2001)); |
| 853 | assert!(!is_leap_year(2002)); |
| 854 | assert!(!is_leap_year(2003)); |
| 855 | assert!(is_leap_year(2004)); |
| 856 | } |
| 857 | |
| 858 | #[test] |
| 859 | fn number_of_days_in_month() { |
| 860 | assert_eq!(days_in_month(2024, 1), 31); |
| 861 | assert_eq!(days_in_month(2024, 2), 29); |
| 862 | assert_eq!(days_in_month(2024, 3), 31); |
| 863 | assert_eq!(days_in_month(2024, 4), 30); |
| 864 | assert_eq!(days_in_month(2024, 5), 31); |
| 865 | assert_eq!(days_in_month(2024, 6), 30); |
| 866 | assert_eq!(days_in_month(2024, 7), 31); |
| 867 | assert_eq!(days_in_month(2024, 8), 31); |
| 868 | assert_eq!(days_in_month(2024, 9), 30); |
| 869 | assert_eq!(days_in_month(2024, 10), 31); |
| 870 | assert_eq!(days_in_month(2024, 11), 30); |
| 871 | assert_eq!(days_in_month(2024, 12), 31); |
| 872 | |
| 873 | assert_eq!(days_in_month(2025, 1), 31); |
| 874 | assert_eq!(days_in_month(2025, 2), 28); |
| 875 | assert_eq!(days_in_month(2025, 3), 31); |
| 876 | assert_eq!(days_in_month(2025, 4), 30); |
| 877 | assert_eq!(days_in_month(2025, 5), 31); |
| 878 | assert_eq!(days_in_month(2025, 6), 30); |
| 879 | assert_eq!(days_in_month(2025, 7), 31); |
| 880 | assert_eq!(days_in_month(2025, 8), 31); |
| 881 | assert_eq!(days_in_month(2025, 9), 30); |
| 882 | assert_eq!(days_in_month(2025, 10), 31); |
| 883 | assert_eq!(days_in_month(2025, 11), 30); |
| 884 | assert_eq!(days_in_month(2025, 12), 31); |
| 885 | |
| 886 | assert_eq!(days_in_month(1900, 2), 28); |
| 887 | assert_eq!(days_in_month(2000, 2), 29); |
| 888 | } |
| 889 | |
| 890 | #[test] |
| 891 | fn yesterday() { |
| 892 | let d1 = IDate { year: 2025, month: 4, day: 7 }; |
| 893 | let d2 = d1.yesterday().unwrap(); |
| 894 | assert_eq!(d2, IDate { year: 2025, month: 4, day: 6 }); |
| 895 | |
| 896 | let d1 = IDate { year: 2025, month: 4, day: 1 }; |
| 897 | let d2 = d1.yesterday().unwrap(); |
| 898 | assert_eq!(d2, IDate { year: 2025, month: 3, day: 31 }); |
| 899 | |
| 900 | let d1 = IDate { year: 2025, month: 1, day: 1 }; |
| 901 | let d2 = d1.yesterday().unwrap(); |
| 902 | assert_eq!(d2, IDate { year: 2024, month: 12, day: 31 }); |
| 903 | |
| 904 | let d1 = IDate { year: -9999, month: 1, day: 1 }; |
| 905 | assert_eq!(d1.yesterday().ok(), None); |
| 906 | } |
| 907 | |
| 908 | #[test] |
| 909 | fn tomorrow() { |
| 910 | let d1 = IDate { year: 2025, month: 4, day: 7 }; |
| 911 | let d2 = d1.tomorrow().unwrap(); |
| 912 | assert_eq!(d2, IDate { year: 2025, month: 4, day: 8 }); |
| 913 | |
| 914 | let d1 = IDate { year: 2025, month: 3, day: 31 }; |
| 915 | let d2 = d1.tomorrow().unwrap(); |
| 916 | assert_eq!(d2, IDate { year: 2025, month: 4, day: 1 }); |
| 917 | |
| 918 | let d1 = IDate { year: 2025, month: 12, day: 31 }; |
| 919 | let d2 = d1.tomorrow().unwrap(); |
| 920 | assert_eq!(d2, IDate { year: 2026, month: 1, day: 1 }); |
| 921 | |
| 922 | let d1 = IDate { year: 9999, month: 12, day: 31 }; |
| 923 | assert_eq!(d1.tomorrow().ok(), None); |
| 924 | } |
| 925 | } |