Debian Codegraph @

third_party/rust/calendrical_calculations/src/hebrew_keviyah.rs

raw
1 // This file is part of ICU4X.
2 //
3 // The contents of this file implement algorithms from Calendrical Calculations
4 // by Reingold & Dershowitz, Cambridge University Press, 4th edition (2018),
5 // which have been released as Lisp code at <https://github.com/EdReingold/calendar-code2/>
6 // under the Apache-2.0 license. Accordingly, this file is released under
7 // the Apache License, Version 2.0 which can be found at the calendrical_calculations
8 // package root or at http://www.apache.org/licenses/LICENSE-2.0.
9
10 // The algorithms in this file are rather well-published in multiple places,
11 // though the resource that was primarily used was
12 // J Jean Adler's _A Short History of the Jewish Fixed Calendar_, found
13 // at <https://hakirah.org/vol20Ajdler.pdf>, with more detailed appendices
14 // at <https://www.hakirah.org/vol20AjdlerAppendices.pdf>.
15 // Most of the math can be found on Wikipedia as well,
16 // at <https://en.wikipedia.org/wiki/Hebrew_calendar#The_four_gates>
17
18 //! Alternate, more efficient structures for working with the Hebrew Calendar
19 //! using the keviyah and Four Gates system
20 //!
21 //! The main entry point for this code is [`YearInfo::compute_for()`] and [`YearInfo::year_containing_rd()`],
22 //! which will efficiently calculate certain information about a Hebrew year, given the Hebrew year
23 //! or a date that falls within it, and produce it as a [`YearInfo`].
24 //!
25 //! From there, you can compute additional information via [`YearInfo::new_year()`] and by accessing
26 //! the methods on [`YearInfo::keviyah`].
27 //!
28 //!
29 //! # How this code works:
30 //!
31 //! ## How the Hebrew Calendar works
32 //!
33 //! The Hebrew calendar is a lunisolar calendar following a Metonic cycle: every 19 years, the pattern of
34 //! leap years repeats. However, the precise month lengths vary from cycle to cycle: There are a handful of
35 //! corrections performed to ensure that:
36 //!
37 //! - The lunar conjunction happens on or before the first day of the month
38 //! - Yom Kippur is not before or after the Sabbath
39 //! - Hoshana Rabbah is not on the Sabbath
40 //!
41 //! These corrections can be done using systematic calculations, which this code attempts to efficiently perform.
42 //!
43 //! ## Molad
44 //!
45 //! A molad is the time of a conjunction, the moment when the new moon occurs. The "Molad Tishrei" is
46 //! the conjunction corresponding to the month Tishrei, the first month, so it is the molad that starts the new year.
47 //! In this file we'll typically use "molad" to refer to the molad Tishrei of a year.
48 //!
49 //! The Hebrew calendar does not always start on the day of the molad Tishrei: it may be postponed one or two days.
50 //! However, the time in the week that the molad occurs is sufficient to know when it gets postponed to.
51 //!
52 //! ## Keviyah
53 //!
54 //! See also: the [`Keviyah`] type.
55 //!
56 //! This is the core concept being used here. Everything you need to know about the characteristics
57 //! of a hebrew year can be boiled down to a notion called the "keviyah" of a year. This
58 //! encapsulates three bits of information:
59 //!
60 //! - What day of the week the year starts on
61 //! - What the month lengths are
62 //! - What day of the week Passover starts on.
63 //!
64 //! While this seems like many possible combinations, only fourteen of them are possible.
65 //!
66 //! Knowing the Keviyah of the year you can understand exactly what the lengths of each month are.
67 //! Furthermore, if you know the week the year falls in, you can additionally understand what
68 //! the precise day of the new year is.
69 //!
70 //! [`YearInfo`] encapsulates these two pieces of information: the [`Keviyah`] and the number of weeks
71 //! since the epoch of the Hebrew calendar.
72 //!
73 //! ## The Four Gates table
74 //!
75 //! This is an efficient lookup based way of calculating the [`Keviyah`] for a year. In the Metonic cycle,
76 //! there are four broad types of year: leap years, years preceding leap years, years succeeding leap years,
77 //! and years sandwiched between leap years. For each of these year types, there is a partitioning
78 //! of the week into seven segments, and the [`Keviyah`] of that year depends on which segment the molad falls
79 //! in.
80 //!
81 //! So to calculate the [`Keviyah`] of a year, we can calculate its molad, pick the right partitioning based on the
82 //! year type, and see where the molad falls in that table.
83
84 use crate::helpers::i64_to_i32;
85 use crate::rata_die::RataDie;
86 use core::cmp::Ordering;
87
88 // A note on time notation
89 //
90 // Hebrew timekeeping has some differences from standard timekeeping. A Hebrew day is split into 24
91 // hours, each split into 1080 ḥalakim ("parts", abbreviated "ḥal" or "p"). Furthermore, the Hebrew
92 // day for calendrical purposes canonically starts at 6PM the previous evening, e.g. Hebrew Monday
93 // starts on Sunday 6PM. (For non-calendrical observational purposes this varies and is based on
94 // the sunset, but that is not too relevant for the algorithms here.)
95 //
96 // In this file an unqualified day of the week will refer to a standard weekday, and Hebrew weekdays
97 // will be referred to as "Hebrew Sunday" etc. Sometimes the term "regular" or "standard" will be used
98 // to refer to a standard weekday when we particularly wish to avoid ambiguity.
99 //
100 // Hebrew weeks start on Sunday. A common notation for times of the week looks like 2-5-204, which
101 // means "second Hebrew Day of the week, 5h 204 ḥal", which is 5h 204 ḥal after the start of Hebrew
102 // Monday (which is 23h:204ḥal on standard Sunday).
103 //
104 // Some resources will use ḥalakim notation when talking about time during a standard day. This
105 // document will use standard `:` notation for this, as used above with 23h:204ḥal being equal to
106 // 5h 204ḥal. In other words, if a time is notated using dashes or spaces, it is relative to the
107 // hebrew start of day, whereas if it is notated using a colon, it is relative to midnight.
108 //
109 // Finally, Adjler, the resource we are using, uses both inclusive and exclusive time notation. It
110 // is typical across resources using the 2-5-204 notation for the 2 to be "second day" as opposed
111 // to "two full days have passed" (i.e., on the first day). However *in the context of
112 // calculations* Adjler will use 1-5-204 to refer to stuff happening on Hebrew Monday, and clarify
113 // it as (2)-5-204. This is because zero-indexing works better in calculations.
114 //
115 // Comparing these algorithms with the source in Adjler should be careful about this. All other
116 // resources seem to universally 1-index in the dashes notation. This file will only use
117 // zero-indexed notation when explicitly disambiguated, usually when talking about intervals.
118
119 /// Calculate the number of months preceding the molad Tishrei for a given hebrew year (Tishrei is the first month)
120 #[inline]
121 fn months_preceding_molad(h_year: i32) -> i64 {
122 // Ft = INT((235N + 1 / 19))
123 // Where N = h_year - 1 (number of elapsed years since epoch)
124 // This math essentially comes from the Metonic cycle of 19 years containing
125 // 235 months: 12 months per year, plus an extra month for each of the 7 leap years.
126
127 (235 * (i64::from(h_year) - 1) + 1).div_euclid(19)
128 }
129
130 /// Conveniently create a constant for a ḥalakim (by default in 1-indexed notation). Produces a constant
131 /// that tracks the number of ḥalakim since the beginning of the week
132 macro_rules! ḥal {
133 ($d:literal-$h:literal-$p:literal) => {{
134 const CONSTANT: i32 = (($d - 1) * 24 + $h) * 1080 + $p;
135 CONSTANT
136 }};
137 (0-indexed $d:literal-$h:literal-$p:literal) => {{
138 const CONSTANT: i32 = ($d * 24 + $h) * 1080 + $p;
139 CONSTANT
140 }};
141 }
142
143 /// The molad Beherad is the first molad, i.e. the molad of the epoch year.
144 /// It occurred on Oct 6, 3761 BC, 23h:204ḥal (Jerusalem Time, Julian Calendar)
145 ///
146 /// Which is the second Hebrew day of the week (Hebrew Monday), 5h 204ḥal, 2-5-204.
147 /// ("Beharad" בהרד is just a way of writing 2-5-204, ב-ה-רד using Hebrew numerals)
148 ///
149 /// This is 31524ḥal after the start of the week (Saturday 6PM)
150 ///
151 /// From Adjler Appendix A
152 const MOLAD_BEHERAD_OFFSET: i32 = ḥal!(2 - 5 - 204);
153
154 /// The amount of time a Hebrew lunation takes (in ḥalakim). This is not exactly the amount of time
155 /// taken by one revolution of the moon (the real world seldom has events that are perfect integer
156 /// multiples of 1080ths of an hour), but it is what the Hebrew calendar uses. This does mean that
157 /// there will be drift over time with the actual state of the celestial sphere, however that is
158 /// irrelevant since the actual state of the celestial sphere is not what is used for the Hebrew
159 /// calendar.
160 ///
161 /// This is 29-12-793 in zero-indexed notation. It is equal to 765433ḥal.
162 /// From Adjler Appendix A
163 const HEBREW_LUNATION_TIME: i32 = ḥal!(0-indexed 29-12-793);
164
165 /// From Reingold (ch 8.2, in implementation for fixed-from-hebrew)
166 const HEBREW_APPROX_YEAR_LENGTH: f64 = 35975351.0 / 98496.0;
167
168 /// The number of ḥalakim in a week
169 ///
170 /// (This is 181440)
171 const ḤALAKIM_IN_WEEK: i64 = 1080 * 24 * 7;
172
173 /// The Hebrew calendar epoch. It did not need to be postponed, so it occurs on Hebrew Monday, Oct 7, 3761 BCE (Julian),
174 /// the same as the Molad Beherad.
175 ///
176 /// (note that the molad Beherad occurs on standard Sunday, but because it happens after 6PM it is still Hebrew Monday)
177 const HEBREW_CALENDAR_EPOCH: RataDie = crate::julian::fixed_from_julian_book_version(-3761, 10, 7);
178
179 /// The minumum hebrew year supported by this code (this is the minimum value for i32)
180 pub const HEBREW_MIN_YEAR: i32 = i32::MIN;
181 /// The minumum R.D. supported by this code (this code will clamp outside of it)
182 // (this constant is verified by tests)
183 pub const HEBREW_MIN_RD: RataDie = RataDie::new(-784362951979);
184 /// The maximum hebrew year supported by this code (this is the maximum alue for i32)
185 // (this constant is verified by tests)
186 pub const HEBREW_MAX_YEAR: i32 = i32::MAX;
187 /// The maximum R.D. supported by this code (this is the last day in [`HEBREW_MAX_YEAR`])
188 // (this constant is verified by tests)
189 pub const HEBREW_MAX_RD: RataDie = RataDie::new(784360204356);
190
191 /// Given a Hebrew Year, returns its molad specified as:
192 ///
193 /// - The number of weeks since the week of Beharad (Oct 6, 3761 BCE Julian)
194 /// - The number of ḥalakim since the start of the week (Hebrew Sunday, starting on Saturday at 18:00)
195 #[inline]
196 fn molad_details(h_year: i32) -> (i64, i32) {
197 let months_preceding = months_preceding_molad(h_year);
198
199 // The molad tishri expressed in parts since the beginning of the week containing Molad of Beharad
200 // Formula from Adjler Appendix A
201 let molad = MOLAD_BEHERAD_OFFSET as i64 + months_preceding * HEBREW_LUNATION_TIME as i64;
202
203 // Split into quotient and remainder
204 let weeks_since_beharad = molad.div_euclid(ḤALAKIM_IN_WEEK);
205 let in_week = molad.rem_euclid(ḤALAKIM_IN_WEEK);
206
207 let in_week = i32::try_from(in_week);
208 debug_assert!(in_week.is_ok(), "ḤALAKIM_IN_WEEK should fit in an i32");
209
210 (weeks_since_beharad, in_week.unwrap_or(0))
211 }
212
213 /// Everything about a given year. Can be conveniently packed down into an i64 if needed.
214 #[derive(Copy, Clone, Eq, PartialEq, Debug)]
215 #[allow(clippy::exhaustive_structs)] // This may change but we're fine breaking this crate
216 pub struct YearInfo {
217 /// The Keviyah of the year
218 pub keviyah: Keviyah,
219 /// How many full weeks have passed since the week of Beharad
220 pub weeks_since_beharad: i64,
221 }
222
223 impl YearInfo {
224 /// Compute the YearInfo for a given year
225 #[inline]
226 pub fn compute_for(h_year: i32) -> Self {
227 let (mut weeks_since_beharad, ḥalakim) = molad_details(h_year);
228
229 let cycle_type = MetonicCycleType::for_h_year(h_year);
230
231 let keviyah = keviyah_for(cycle_type, ḥalakim);
232
233 // The last six hours of Hebrew Saturday (i.e. after noon on Regular Saturday)
234 // get unconditionally postponed to Monday according to the Four Gates table. This
235 // puts us in a new week!
236 if ḥalakim > ḥal!(7 - 18 - 0) {
237 weeks_since_beharad += 1;
238 }
239
240 Self {
241 keviyah,
242 weeks_since_beharad,
243 }
244 }
245
246 /// Returns the YearInfo and h_year for the year containing `date`
247 ///
248 /// This will clamp the R.D. such that the hebrew year is within range for i32
249 #[inline]
250 pub fn year_containing_rd(date: RataDie) -> (Self, i32) {
251 #[allow(unused_imports)]
252 use core_maths::*;
253
254 let date = date.clamp(HEBREW_MIN_RD, HEBREW_MAX_RD);
255
256 let days_since_epoch = (date - HEBREW_CALENDAR_EPOCH) as f64;
257 let maybe_approx =
258 i64_to_i32(1 + days_since_epoch.div_euclid(HEBREW_APPROX_YEAR_LENGTH) as i64);
259 let approx = maybe_approx.unwrap_or_else(|e| e.saturate());
260
261 let yi = Self::compute_for(approx);
262
263 // compute if yi ⩼ rd
264 let cmp = yi.compare(date);
265
266 let (yi, h_year) = match cmp {
267 // The approx year is a year greater. Go one year down
268 Ordering::Greater => {
269 let prev = approx.saturating_sub(1);
270 (Self::compute_for(prev), prev)
271 }
272 // Bullseye
273 Ordering::Equal => (yi, approx),
274 // The approx year is a year lower. Go one year up.
275 Ordering::Less => {
276 let next = approx.saturating_add(1);
277 (Self::compute_for(next), next)
278 }
279 };
280
281 debug_assert!(yi.compare(date).is_eq(),
282 "Date {date:?} calculated approximately to Hebrew Year {approx} (comparison: {cmp:?}), \
283 should be contained in adjacent year {h_year} but that year is still {:?} it", yi.compare(date));
284
285 (yi, h_year)
286 }
287
288 /// Compare this year against a date. Returns Ordering::Greater
289 /// when this year is after the given date
290 ///
291 /// i.e. this is computing self ⩼ rd
292 fn compare(self, rd: RataDie) -> Ordering {
293 let ny = self.new_year();
294 let len = self.keviyah.year_length();
295
296 if rd < ny {
297 Ordering::Greater
298 } else if rd >= ny + len.into() {
299 Ordering::Less
300 } else {
301 Ordering::Equal
302 }
303 }
304
305 /// Compute the date of New Year's Day
306 #[inline]
307 pub fn new_year(self) -> RataDie {
308 // Beharad started on Monday
309 const BEHARAD_START_OF_YEAR: StartOfYear = StartOfYear::Monday;
310 let days_since_beharad = (self.weeks_since_beharad * 7)
311 + self.keviyah.start_of_year() as i64
312 - BEHARAD_START_OF_YEAR as i64;
313 HEBREW_CALENDAR_EPOCH + days_since_beharad
314 }
315 }
316
317 /// The Keviyah (קביעה) of a year. A year may be one of fourteen types, categorized by the day of
318 /// week of the new year (the first number, 1 = Sunday), the type of year (Deficient, Regular,
319 /// Complete), and the day of week of the first day of Passover. The last segment disambiguates
320 /// between cases that have the same first two but differ on whether they are leap years (since
321 /// Passover happens in Nisan, after the leap month Adar).
322 ///
323 /// The discriminant values of these entries are according to
324 /// the positions these keviyot appear in the Four Gates table,
325 /// with the leap year ones being offset by 7. We don't directly rely on this
326 /// property but it is useful for potential bitpacking, and we use it as a way
327 /// to double-check that the four gates code is set up correctly. We do directly
328 /// rely on the leap-keviyot being after the regular ones (and starting with בחה) in is_leap.
329 ///
330 /// For people unsure if their editor supports bidirectional text,
331 /// the first Keviyah (2D3) is Bet (ב), Ḥet (ח), Gimel (ג).
332 ///
333 /// (The Hebrew values are used in code for two reasons: firstly, Rust identifiers
334 /// can't start with a number, and secondly, sources differ on the Latin alphanumeric notation
335 /// but use identical Hebrew notation)
336 #[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Debug)]
337 #[allow(clippy::exhaustive_enums)] // There are only 14 keviyot (and always have been)
338 pub enum Keviyah {
339 // Regular years
340 /// 2D3
341 בחג = 0,
342 /// 2C5
343 בשה = 1,
344 /// 3R5
345 גכה = 2,
346 /// 5R7
347 הכז = 3,
348 /// 5C1
349 השא = 4,
350 /// 7D1
351 זחא = 5,
352 /// 7C3
353 זשג = 6,
354
355 // Leap years
356 /// 2D5
357 בחה = 7,
358 /// 2C7
359 בשז = 8,
360 /// 3R7
361 גכז = 9,
362 /// 5D1
363 החא = 10,
364 /// 5C3
365 השג = 11,
366 /// 7D3
367 זחג = 12,
368 /// 7C5
369 זשה = 13,
370 }
371
372 /// The type of year it is
373 #[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Debug)]
374 #[allow(clippy::exhaustive_enums)] // This is intrinsic to the calendar
375 pub enum YearType {
376 /// חסרה: both Ḥeshvan and Kislev have 29 days
377 Deficient = -1,
378 /// כסדרה: Ḥeshvan has 29, Kislev has 30
379 Regular = 0,
380 /// שלמה: both Ḥeshvan and Kislev have 30 days
381 Complete = 1,
382 }
383
384 impl YearType {
385 /// The length correction from a regular year (354/385)
386 fn length_correction(self) -> i8 {
387 self as i8
388 }
389
390 /// The length of Ḥeshvan
391 fn ḥeshvan_length(self) -> u8 {
392 if self == Self::Complete {
393 ḤESHVAN_DEFAULT_LEN + 1
394 } else {
395 ḤESHVAN_DEFAULT_LEN
396 }
397 }
398
399 /// The length correction of Kislev
400 fn kislev_length(self) -> u8 {
401 if self == Self::Deficient {
402 KISLEV_DEFAULT_LEN - 1
403 } else {
404 KISLEV_DEFAULT_LEN
405 }
406 }
407 }
408 /// The day of the new year. Only these four days are permitted.
409 #[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Debug)]
410 #[allow(clippy::exhaustive_enums)] // This is intrinsic to the calendar
411 pub enum StartOfYear {
412 // Compiler forced me to document these, <https://en.wikipedia.org/wiki/Nowe_Ateny>
413 /// Monday (everyone knows what Monday is)
414 Monday = 2,
415 /// Tuesday (everyone knows what Tuesday is)
416 Tuesday = 3,
417 /// Thursday (everyone knows what Thursday is)
418 Thursday = 5,
419 /// Saturday (everyone knows what Saturday is)
420 Saturday = 7,
421 }
422
423 // Given a constant expression of the type FOO + BAR + BAZ convert
424 // every element into a u16 and return
425 macro_rules! u16_cvt(
426 // the $first / $rest pattern is needed since
427 // macros cannot use `+` as a separator in repetition
428 ($first:ident $(+ $rest:ident)*) => {
429 {
430 // make sure it is constant
431 // we use as here because it works in consts and in this context
432 // overflow will panic anyway
433 const COMPUTED: u16 = $first as u16 $(+ $rest as u16)*;
434 COMPUTED
435 }
436 };
437 );
438
439 // Month lengths (ref: https://en.wikipedia.org/wiki/Hebrew_calendar#Months)
440 const TISHREI_LEN: u8 = 30;
441 // except in Complete years
442 const ḤESHVAN_DEFAULT_LEN: u8 = 29;
443 // Except in Deficient years
444 const KISLEV_DEFAULT_LEN: u8 = 30;
445 const TEVET_LEN: u8 = 29;
446 const SHEVAT_LEN: u8 = 30;
447 const ADARI_LEN: u8 = 30;
448 const ADAR_LEN: u8 = 29;
449 const NISAN_LEN: u8 = 30;
450 const IYYAR_LEN: u8 = 29;
451 const SIVAN_LEN: u8 = 30;
452 const TAMMUZ_LEN: u8 = 29;
453 const AV_LEN: u8 = 30;
454 const ELUL_LEN: u8 = 29;
455
456 /// Normalized month constant for Tishrei
457 ///
458 /// These are not ordinal months, rather these are the month number in a regular year
459 /// Adar, Adar I and Adar II all normalize to 6
460 pub const TISHREI: u8 = 1;
461 /// Normalized month constant (see [`TISHREI`])
462 pub const ḤESHVAN: u8 = 2;
463 /// Normalized month constant (see [`TISHREI`])
464 pub const KISLEV: u8 = 3;
465 /// Normalized month constant (see [`TISHREI`])
466 pub const TEVET: u8 = 4;
467 /// Normalized month constant (see [`TISHREI`])
468 pub const SHEVAT: u8 = 5;
469 /// Normalized month constant (see [`TISHREI`])
470 pub const ADAR: u8 = 6;
471 /// Normalized month constant (see [`TISHREI`])
472 pub const NISAN: u8 = 7;
473 /// Normalized month constant (see [`TISHREI`])
474 pub const IYYAR: u8 = 8;
475 /// Normalized month constant (see [`TISHREI`])
476 pub const SIVAN: u8 = 9;
477 /// Normalized month constant (see [`TISHREI`])
478 pub const TAMMUZ: u8 = 10;
479 /// Normalized month constant (see [`TISHREI`])
480 pub const AV: u8 = 11;
481 /// Normalized month constant (see [`TISHREI`])
482 pub const ELUL: u8 = 12;
483
484 impl Keviyah {
485 /// Get the type of year for this Keviyah.
486 ///
487 /// Comes from the second letter in this Keviyah:
488 /// ח = D, כ = R, ש = C
489 #[inline]
490 pub fn year_type(self) -> YearType {
491 match self {
492 Self::בחג => YearType::Deficient,
493 Self::בשה => YearType::Complete,
494 Self::גכה => YearType::Regular,
495 Self::הכז => YearType::Regular,
496 Self::השא => YearType::Complete,
497 Self::זחא => YearType::Deficient,
498 Self::זשג => YearType::Complete,
499 Self::בחה => YearType::Deficient,
500 Self::בשז => YearType::Complete,
501 Self::גכז => YearType::Regular,
502 Self::החא => YearType::Deficient,
503 Self::השג => YearType::Complete,
504 Self::זחג => YearType::Deficient,
505 Self::זשה => YearType::Complete,
506 }
507 }
508 /// Get the day of the new year for this Keviyah
509 ///
510 /// Comes from the first letter in this Keviyah:
511 /// ב = 2 = Monday, ג = 3 = Tuesday, ה = 5 = Thursday, ז = 7 = Saturday
512 #[inline]
513 pub fn start_of_year(self) -> StartOfYear {
514 match self {
515 Self::בחג => StartOfYear::Monday,
516 Self::בשה => StartOfYear::Monday,
517 Self::גכה => StartOfYear::Tuesday,
518 Self::הכז => StartOfYear::Thursday,
519 Self::השא => StartOfYear::Thursday,
520 Self::זחא => StartOfYear::Saturday,
521 Self::זשג => StartOfYear::Saturday,
522 Self::בחה => StartOfYear::Monday,
523 Self::בשז => StartOfYear::Monday,
524 Self::גכז => StartOfYear::Tuesday,
525 Self::החא => StartOfYear::Thursday,
526 Self::השג => StartOfYear::Thursday,
527 Self::זחג => StartOfYear::Saturday,
528 Self::זשה => StartOfYear::Saturday,
529 }
530 }
531
532 /// Normalize the ordinal month to the "month number" in the year (ignoring
533 /// leap months), i.e. Adar and Adar II are both represented by 6.
534 ///
535 /// Returns None if given the index of Adar I (6 in a leap year)
536 #[inline]
537 fn normalized_ordinal_month(self, ordinal_month: u8) -> Option<u8> {
538 if self.is_leap() {
539 match ordinal_month.cmp(&6) {
540 // Adar I
541 Ordering::Equal => None,
542 Ordering::Less => Some(ordinal_month),
543 Ordering::Greater => Some(ordinal_month - 1),
544 }
545 } else {
546 Some(ordinal_month)
547 }
548 }
549
550 /// Given an ordinal, civil month (1-indexed month starting at Tishrei)
551 /// return its length
552 #[inline]
553 pub fn month_len(self, ordinal_month: u8) -> u8 {
554 // Normalize it to the month number
555 let Some(normalized_ordinal_month) = self.normalized_ordinal_month(ordinal_month) else {
556 return ADARI_LEN;
557 };
558 debug_assert!(normalized_ordinal_month <= 12 && normalized_ordinal_month > 0);
559 match normalized_ordinal_month {
560 TISHREI => TISHREI_LEN,
561 ḤESHVAN => self.year_type().ḥeshvan_length(),
562 KISLEV => self.year_type().kislev_length(),
563 TEVET => TEVET_LEN,
564 SHEVAT => SHEVAT_LEN,
565 ADAR => ADAR_LEN,
566 NISAN => NISAN_LEN,
567 IYYAR => IYYAR_LEN,
568 SIVAN => SIVAN_LEN,
569 TAMMUZ => TAMMUZ_LEN,
570 AV => AV_LEN,
571 ELUL => ELUL_LEN,
572 _ => {
573 debug_assert!(false, "Got unknown month index {ordinal_month}");
574 30
575 }
576 }
577 }
578
579 /// Get the number of days preceding this month
580 #[inline]
581 pub fn days_preceding(self, ordinal_month: u8) -> u16 {
582 // convenience constant to keep the additions smallish
583 // Number of days before (any) Adar in a regular year
584 const BEFORE_ADAR_DEFAULT_LEN: u16 = u16_cvt!(
585 TISHREI_LEN + ḤESHVAN_DEFAULT_LEN + KISLEV_DEFAULT_LEN + TEVET_LEN + SHEVAT_LEN
586 );
587
588 let Some(normalized_ordinal_month) = self.normalized_ordinal_month(ordinal_month) else {
589 // Get Adar I out of the way
590 let corrected =
591 BEFORE_ADAR_DEFAULT_LEN as i16 + i16::from(self.year_type().length_correction());
592 return corrected as u16;
593 };
594 debug_assert!(normalized_ordinal_month <= ELUL && normalized_ordinal_month > 0);
595
596 let year_type = self.year_type();
597
598 let mut days = match normalized_ordinal_month {
599 TISHREI => 0,
600 ḤESHVAN => u16_cvt!(TISHREI_LEN),
601 KISLEV => u16_cvt!(TISHREI_LEN) + u16::from(year_type.ḥeshvan_length()),
602 // Use default lengths after this, we'll apply the correction later
603 // (This helps optimize this into a simple jump table)
604 TEVET => u16_cvt!(TISHREI_LEN + ḤESHVAN_DEFAULT_LEN + KISLEV_DEFAULT_LEN),
605 SHEVAT => u16_cvt!(TISHREI_LEN + ḤESHVAN_DEFAULT_LEN + KISLEV_DEFAULT_LEN + TEVET_LEN),
606 ADAR => BEFORE_ADAR_DEFAULT_LEN,
607 NISAN => u16_cvt!(BEFORE_ADAR_DEFAULT_LEN + ADAR_LEN),
608 IYYAR => u16_cvt!(BEFORE_ADAR_DEFAULT_LEN + ADAR_LEN + NISAN_LEN),
609 SIVAN => u16_cvt!(BEFORE_ADAR_DEFAULT_LEN + ADAR_LEN + NISAN_LEN + IYYAR_LEN),
610 TAMMUZ => {
611 u16_cvt!(BEFORE_ADAR_DEFAULT_LEN + ADAR_LEN + NISAN_LEN + IYYAR_LEN + SIVAN_LEN)
612 }
613 #[rustfmt::skip]
614 AV => u16_cvt!(BEFORE_ADAR_DEFAULT_LEN + ADAR_LEN + NISAN_LEN + IYYAR_LEN + SIVAN_LEN + TAMMUZ_LEN),
615 #[rustfmt::skip]
616 _ => u16_cvt!(BEFORE_ADAR_DEFAULT_LEN + ADAR_LEN + NISAN_LEN + IYYAR_LEN + SIVAN_LEN + TAMMUZ_LEN + AV_LEN),
617 };
618
619 // If it is after Kislev and Ḥeshvan, we should add the year correction
620 if normalized_ordinal_month > KISLEV {
621 // Ensure the casts are fine
622 debug_assert!(days > 1 && year_type.length_correction().abs() <= 1);
623 days = (days as i16 + year_type.length_correction() as i16) as u16;
624 }
625
626 // In a leap year, after Adar (and including Adar II), we should add
627 // the length of Adar 1
628 if normalized_ordinal_month >= ADAR && self.is_leap() {
629 days += u16::from(ADARI_LEN);
630 }
631
632 days
633 }
634
635 /// Given a day of the year, return the ordinal month and day as (month, day).
636 pub fn month_day_for(self, mut day: u16) -> (u8, u8) {
637 for month in 1..14 {
638 let month_len = self.month_len(month);
639 if let Ok(day) = u8::try_from(day) {
640 if day <= month_len {
641 return (month, day);
642 }
643 }
644 day -= u16::from(month_len);
645 }
646 debug_assert!(false, "Attempted to get Hebrew date for {day:?}, in keviyah {self:?}, didn't have enough days in the year");
647 self.last_month_day_in_year()
648 }
649
650 /// Return the last ordinal month and day in this year as (month, day)
651 #[inline]
652 pub fn last_month_day_in_year(self) -> (u8, u8) {
653 // Elul is always the last month of the year
654 if self.is_leap() {
655 (13, ELUL_LEN)
656 } else {
657 (12, ELUL_LEN)
658 }
659 }
660
661 /// Whether this year is a leap year
662 #[inline]
663 pub fn is_leap(self) -> bool {
664 debug_assert_eq!(Self::בחה as u8, 7, "Representation of keviyot changed!");
665 // Because we have arranged our keviyot such that all leap keviyot come after
666 // the regular ones, this just a comparison
667 self >= Self::בחה
668 }
669
670 /// Given the hebrew year for this Keviyah, calculate the YearInfo
671 #[inline]
672 pub fn year_info(self, h_year: i32) -> YearInfo {
673 let (mut weeks_since_beharad, ḥalakim) = molad_details(h_year);
674
675 // The last six hours of Hebrew Saturday (i.e. after noon on Regular Saturday)
676 // get unconditionally postponed to Monday according to the Four Gates table. This
677 // puts us in a new week!
678 if ḥalakim > ḥal!(7 - 18 - 0) {
679 weeks_since_beharad += 1;
680 }
681
682 YearInfo {
683 keviyah: self,
684 weeks_since_beharad,
685 }
686 }
687
688 /// How many days are in this year
689 #[inline]
690 pub fn year_length(self) -> u16 {
691 let base_year_length = if self.is_leap() { 384 } else { 354 };
692
693 (base_year_length + i16::from(self.year_type().length_correction())) as u16
694 }
695 /// Construct this from an integer between 0 and 13
696 ///
697 /// Potentially useful for bitpacking
698 #[inline]
699 pub fn from_integer(integer: u8) -> Self {
700 debug_assert!(
701 integer < 14,
702 "Keviyah::from_integer() takes in a number between 0 and 13 inclusive"
703 );
704 match integer {
705 0 => Self::בחג,
706 1 => Self::בשה,
707 2 => Self::גכה,
708 3 => Self::הכז,
709 4 => Self::השא,
710 5 => Self::זחא,
711 6 => Self::זשג,
712 7 => Self::בחה,
713 8 => Self::בשז,
714 9 => Self::גכז,
715 10 => Self::החא,
716 11 => Self::השג,
717 12 => Self::זחג,
718 _ => Self::זשה,
719 }
720 }
721 }
722
723 // Four Gates Table
724 // ======================
725 ///
726 // The Four Gates table is a table that takes the time of week of the molad
727 // and produces a Keviyah for the year
728
729 /// "Metonic cycle" in general refers to any 19-year repeating pattern used by lunisolar
730 /// calendars. The Hebrew calendar uses one where years 3, 6, 8, 11, 14, 17, 19
731 /// are leap years.
732 ///
733 /// The Hebrew calendar further categorizes regular years as whether they come before/after/or
734 /// between leap years, and this is used when performing lookups.
735 #[derive(Copy, Clone, Eq, PartialEq, Debug)]
736 enum MetonicCycleType {
737 /// Before a leap year (2, 5, 10, 13, 16)
738 LMinusOne,
739 /// After a leap year (1, 4, 9, 12, 15)
740 LPlusOne,
741 /// Between leap years (7. 18)
742 LPlusMinusOne,
743 /// Leap year (3, 6, 8, 11, 14, 17, 19)
744 Leap,
745 }
746
747 impl MetonicCycleType {
748 fn for_h_year(h_year: i32) -> Self {
749 // h_year is 1-indexed, and our metonic cycle year numberings
750 // are 1-indexed, so we really need to do `(h_year - 1) % 19 + 1`
751 //
752 // However, that is equivalent to `h_year % 19` provided you handle the
753 // fact that that operation will produce 0 instead of 19.
754 // Both numbers end up in our wildcard leap year arm so that's fine.
755 let remainder = h_year.rem_euclid(19);
756 match remainder {
757 // These numbers are 1-indexed
758 2 | 5 | 10 | 13 | 16 => Self::LMinusOne,
759 1 | 4 | 9 | 12 | 15 => Self::LPlusOne,
760 7 | 18 => Self::LPlusMinusOne,
761 _ => {
762 debug_assert!(matches!(remainder, 3 | 6 | 8 | 11 | 14 | 17 | 0 | 19));
763 Self::Leap
764 }
765 }
766 }
767 }
768
769 // The actual Four Gates tables.
770 //
771 // Each entry is a range (ending at the next entry), and it corresponds to the equivalent discriminant value of the Keviyah type.
772 // Leap and regular years map to different Keviyah values, however regular years all map to the same set of
773 // seven values, with differing ḥalakim bounds for each. The first entry in the Four Gates table straddles the end of the previous week
774 // and the beginning of this one.
775 //
776 // The regular-year tables only differ by their third and last entries (We may be able to write this as more compact code)
777 //
778 // You can reference these tables from https://en.wikipedia.org/wiki/Hebrew_calendar#The_four_gates
779 // or from Adjler (Appendix 4). Be sure to look at the Adjler table referring the "modern calendar", older tables
780 // use slightly different numbers.
781 const FOUR_GATES_LMINUSONE: [i32; 7] = [
782 ḥal!(7 - 18 - 0),
783 ḥal!(1 - 9 - 204),
784 ḥal!(2 - 18 - 0),
785 ḥal!(3 - 9 - 204),
786 ḥal!(5 - 9 - 204),
787 ḥal!(5 - 18 - 0),
788 ḥal!(6 - 9 - 204),
789 ];
790 const FOUR_GATES_LPLUSONE: [i32; 7] = [
791 ḥal!(7 - 18 - 0),
792 ḥal!(1 - 9 - 204),
793 ḥal!(2 - 15 - 589),
794 ḥal!(3 - 9 - 204),
795 ḥal!(5 - 9 - 204),
796 ḥal!(5 - 18 - 0),
797 ḥal!(6 - 0 - 408),
798 ];
799
800 const FOUR_GATES_LPLUSMINUSONE: [i32; 7] = [
801 ḥal!(7 - 18 - 0),
802 ḥal!(1 - 9 - 204),
803 ḥal!(2 - 15 - 589),
804 ḥal!(3 - 9 - 204),
805 ḥal!(5 - 9 - 204),
806 ḥal!(5 - 18 - 0),
807 ḥal!(6 - 9 - 204),
808 ];
809
810 const FOUR_GATES_LEAP: [i32; 7] = [
811 ḥal!(7 - 18 - 0),
812 ḥal!(1 - 20 - 491),
813 ḥal!(2 - 18 - 0),
814 ḥal!(3 - 18 - 0),
815 ḥal!(4 - 11 - 695),
816 ḥal!(5 - 18 - 0),
817 ḥal!(6 - 20 - 491),
818 ];
819
820 /// Perform the four gates calculation, giving you the Keviyah for a given year type and
821 /// the ḥalakim-since-beginning-of-week of its molad Tishri
822 #[inline]
823 fn keviyah_for(year_type: MetonicCycleType, ḥalakim: i32) -> Keviyah {
824 let gate = match year_type {
825 MetonicCycleType::LMinusOne => FOUR_GATES_LMINUSONE,
826 MetonicCycleType::LPlusOne => FOUR_GATES_LPLUSONE,
827 MetonicCycleType::LPlusMinusOne => FOUR_GATES_LPLUSMINUSONE,
828 MetonicCycleType::Leap => FOUR_GATES_LEAP,
829 };
830
831 // Calculate the non-leap and leap keviyot for this year
832 // This could potentially be made more efficient by just finding
833 // the right window on `gate` and transmuting, but this unrolled loop should be fine too.
834 let keviyot = if ḥalakim >= gate[0] || ḥalakim < gate[1] {
835 (Keviyah::בחג, Keviyah::בחה)
836 } else if ḥalakim < gate[2] {
837 (Keviyah::בשה, Keviyah::בשז)
838 } else if ḥalakim < gate[3] {
839 (Keviyah::גכה, Keviyah::גכז)
840 } else if ḥalakim < gate[4] {
841 (Keviyah::הכז, Keviyah::החא)
842 } else if ḥalakim < gate[5] {
843 (Keviyah::השא, Keviyah::השג)
844 } else if ḥalakim < gate[6] {
845 (Keviyah::זחא, Keviyah::זחג)
846 } else {
847 (Keviyah::זשג, Keviyah::זשה)
848 };
849
850 // We have conveniently set the discriminant value of Keviyah to match the four gates index
851 // Let's just assert to make sure the table above is correct.
852 debug_assert!(
853 keviyot.0 as u8 + 7 == keviyot.1 as u8,
854 "The table above should produce matching-indexed keviyot for the leap/non-leap year"
855 );
856 #[cfg(debug_assertions)]
857 #[allow(clippy::indexing_slicing)] // debug_assertion code
858 if keviyot.0 as u8 == 0 {
859 // The first entry in the gates table straddles the ends of the week
860 debug_assert!(
861 ḥalakim >= gate[keviyot.0 as usize] || ḥalakim < gate[(keviyot.0 as usize + 1) % 7],
862 "The table above should produce the right indexed keviyah, instead found {keviyot:?} for time {ḥalakim} (year type {year_type:?})"
863 );
864 } else {
865 // Other entries must properly bound the ḥalakim
866 debug_assert!(
867 ḥalakim >= gate[keviyot.0 as usize] && ḥalakim < gate[(keviyot.0 as usize + 1) % 7],
868 "The table above should produce the right indexed keviyah, instead found {keviyot:?} for time {ḥalakim} (year type {year_type:?})"
869 );
870 }
871
872 if year_type == MetonicCycleType::Leap {
873 keviyot.1
874 } else {
875 keviyot.0
876 }
877 }
878
879 #[cfg(test)]
880 mod test {
881 use super::*;
882 use crate::hebrew::{self, BookHebrew};
883
884 #[test]
885 fn test_consts() {
886 assert_eq!(MOLAD_BEHERAD_OFFSET, 31524);
887 assert_eq!(ḤALAKIM_IN_WEEK, 181440);
888 // Adjler's printed value for this constant is incorrect (as confirmed by Adjler over email).
889 // Adjler is correct about the value being ḥal!(0-indexed 29-12-793).
890 // which matches the math used in `crate::hebrew::molad()` from Calendrical Calculations.
891 //
892 // The correct constant is seen in <https://en.wikibooks.org/wiki/Computer_Programming/Hebrew_calendar>
893 assert_eq!(HEBREW_LUNATION_TIME, 765433);
894
895 // Nicer to have the code be self-contained, but always worth asserting
896 assert_eq!(HEBREW_CALENDAR_EPOCH, hebrew::FIXED_HEBREW_EPOCH);
897 }
898
899 #[test]
900 fn test_roundtrip_days() {
901 for h_year in (1..10).chain(5775..5795).chain(10000..10010) {
902 let year_info = YearInfo::compute_for(h_year);
903 let ny = year_info.new_year();
904 for day in 1..=year_info.keviyah.year_length() {
905 let offset_date = ny + i64::from(day) - 1;
906 let (offset_yearinfo, offset_h_year) = YearInfo::year_containing_rd(offset_date);
907
908 assert_eq!(
909 offset_h_year, h_year,
910 "Backcomputed h_year should be same for day {day} in Hebrew Year {h_year}"
911 );
912 assert_eq!(
913 offset_yearinfo, year_info,
914 "Backcomputed YearInfo should be same for day {day} in Hebrew Year {h_year}"
915 );
916
917 let (month, day2) = year_info.keviyah.month_day_for(day);
918
919 let days_preceding = year_info.keviyah.days_preceding(month);
920
921 assert_eq!(
922 days_preceding + u16::from(day2),
923 day,
924 "{h_year}-{month}-{day2} should round trip for day-of-year {day}"
925 )
926 }
927 }
928 }
929 #[test]
930 fn test_book_parity() {
931 let mut last_year = None;
932 for h_year in (1..100).chain(5600..5900).chain(10000..10100) {
933 let book_date = BookHebrew::from_civil_date(h_year, 1, 1);
934 let book_ny = BookHebrew::fixed_from_book_hebrew(book_date);
935 let kv_yearinfo = YearInfo::compute_for(h_year);
936 let kv_ny = kv_yearinfo.new_year();
937 assert_eq!(
938 book_ny,
939 kv_ny,
940 "Book and Keviyah-based years should match for Hebrew Year {h_year}. Got YearInfo {kv_yearinfo:?}"
941 );
942 let book_is_leap = BookHebrew::is_hebrew_leap_year(h_year);
943 assert_eq!(
944 book_is_leap,
945 kv_yearinfo.keviyah.is_leap(),
946 "Book and Keviyah-based years should match for Hebrew Year {h_year}. Got YearInfo {kv_yearinfo:?}"
947 );
948
949 let book_year_len = BookHebrew::days_in_book_hebrew_year(h_year);
950 let book_year_type = match book_year_len {
951 355 | 385 => YearType::Complete,
952 354 | 384 => YearType::Regular,
953 353 | 383 => YearType::Deficient,
954 _ => unreachable!("Found unexpected book year len {book_year_len}"),
955 };
956 assert_eq!(
957 book_year_type,
958 kv_yearinfo.keviyah.year_type(),
959 "Book and Keviyah-based years should match for Hebrew Year {h_year}. Got YearInfo {kv_yearinfo:?}"
960 );
961
962 let kv_recomputed_yearinfo = kv_yearinfo.keviyah.year_info(h_year);
963 assert_eq!(
964 kv_recomputed_yearinfo,
965 kv_yearinfo,
966 "Recomputed YearInfo should match for Hebrew Year {h_year}. Got YearInfo {kv_yearinfo:?}"
967 );
968
969 let year_len = kv_yearinfo.keviyah.year_length();
970
971 let month_range = if kv_yearinfo.keviyah.is_leap() {
972 1..14
973 } else {
974 1..13
975 };
976
977 let mut days_preceding = 0;
978
979 for month in month_range {
980 let kv_month_len = kv_yearinfo.keviyah.month_len(month);
981 let book_date = BookHebrew::from_civil_date(h_year, month, 1);
982 let book_month_len =
983 BookHebrew::last_day_of_book_hebrew_month(book_date.year, book_date.month);
984 assert_eq!(kv_month_len, book_month_len, "Month lengths should be same for ordinal hebrew month {month} in year {h_year}. Got YearInfo {kv_yearinfo:?}");
985
986 assert_eq!(days_preceding, kv_yearinfo.keviyah.days_preceding(month), "Days preceding should be the sum of preceding days for ordinal hebrew month {month} in year {h_year}. Got YearInfo {kv_yearinfo:?}");
987 days_preceding += u16::from(kv_month_len);
988 }
989
990 for offset in [0, 1, 100, year_len - 100, year_len - 2, year_len - 1] {
991 let offset_date = kv_ny + offset.into();
992 let (offset_yearinfo, offset_h_year) = YearInfo::year_containing_rd(offset_date);
993
994 assert_eq!(offset_h_year, h_year, "Backcomputed h_year should be same for date {offset_date:?} in Hebrew Year {h_year} (offset from ny {offset})");
995 assert_eq!(offset_yearinfo, kv_yearinfo, "Backcomputed YearInfo should be same for date {offset_date:?} in Hebrew Year {h_year} (offset from ny {offset})");
996 }
997
998 if let Some((last_h_year, predicted_ny)) = last_year {
999 if last_h_year + 1 == h_year {
1000 assert_eq!(predicted_ny, kv_ny, "{last_h_year}'s YearInfo predicts New Year {predicted_ny:?}, which does not match current new year. Got YearInfo {kv_yearinfo:?}");
1001 }
1002 }
1003
1004 last_year = Some((h_year, kv_ny + year_len.into()))
1005 }
1006 }
1007 #[test]
1008 fn test_minmax() {
1009 let min = YearInfo::compute_for(HEBREW_MIN_YEAR);
1010 let min_ny = min.new_year();
1011 assert_eq!(min_ny, HEBREW_MIN_RD);
1012
1013 let (recomputed_yi, recomputed_y) = YearInfo::year_containing_rd(min_ny);
1014 assert_eq!(recomputed_y, HEBREW_MIN_YEAR);
1015 assert_eq!(recomputed_yi, min);
1016
1017 let max = YearInfo::compute_for(HEBREW_MAX_YEAR);
1018 let max_ny = max.new_year();
1019 // -1 since max_ny is also a part of the year
1020 let max_last = max_ny + i64::from(max.keviyah.year_length()) - 1;
1021 assert_eq!(max_last, HEBREW_MAX_RD);
1022
1023 let (recomputed_yi, recomputed_y) = YearInfo::year_containing_rd(max_last);
1024 assert_eq!(recomputed_y, HEBREW_MAX_YEAR);
1025 assert_eq!(recomputed_yi, max);
1026 }
1027
1028 #[test]
1029 fn test_leap_agreement() {
1030 for year0 in -1000..1000 {
1031 let year1 = year0 + 1;
1032 let info0 = YearInfo::compute_for(year0);
1033 let info1 = YearInfo::compute_for(year1);
1034 let num_months = (info1.new_year() - info0.new_year()) / 29;
1035 if info0.keviyah.is_leap() {
1036 assert_eq!(num_months, 13, "{year0}");
1037 } else {
1038 assert_eq!(num_months, 12, "{year0}");
1039 }
1040 }
1041 }
1042 }