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