xref: /aosp_15_r20/external/cronet/third_party/icu/source/i18n/hebrwcal.cpp (revision 6777b5387eb2ff775bb5750e3f5d96f37fb7352b)
1 // © 2016 and later: Unicode, Inc. and others.
2 // License & terms of use: http://www.unicode.org/copyright.html
3 /*
4 ******************************************************************************
5 * Copyright (C) 2003-2016, International Business Machines Corporation
6 * and others. All Rights Reserved.
7 ******************************************************************************
8 *
9 * File HEBRWCAL.CPP
10 *
11 * Modification History:
12 *
13 *   Date        Name        Description
14 *   12/03/2003  srl         ported from java HebrewCalendar
15 *****************************************************************************
16 */
17 
18 #include "hebrwcal.h"
19 
20 #if !UCONFIG_NO_FORMATTING
21 
22 #include "cmemory.h"
23 #include "cstring.h"
24 #include "umutex.h"
25 #include <float.h>
26 #include "gregoimp.h" // ClockMath
27 #include "astro.h" // CalendarCache
28 #include "uhash.h"
29 #include "ucln_in.h"
30 
31 // Hebrew Calendar implementation
32 
33 /**
34 * The absolute date, in milliseconds since 1/1/1970 AD, Gregorian,
35 * of the start of the Hebrew calendar.  In order to keep this calendar's
36 * time of day in sync with that of the Gregorian calendar, we use
37 * midnight, rather than sunset the day before.
38 */
39 //static const double EPOCH_MILLIS = -180799862400000.; // 1/1/1 HY
40 
41 static const int32_t LIMITS[UCAL_FIELD_COUNT][4] = {
42     // Minimum  Greatest    Least  Maximum
43     //           Minimum  Maximum
44     {        0,        0,        0,        0}, // ERA
45     { -5000000, -5000000,  5000000,  5000000}, // YEAR
46     {        0,        0,       12,       12}, // MONTH
47     {        1,        1,       51,       56}, // WEEK_OF_YEAR
48     {/*N/A*/-1,/*N/A*/-1,/*N/A*/-1,/*N/A*/-1}, // WEEK_OF_MONTH
49     {        1,        1,       29,       30}, // DAY_OF_MONTH
50     {        1,        1,      353,      385}, // DAY_OF_YEAR
51     {/*N/A*/-1,/*N/A*/-1,/*N/A*/-1,/*N/A*/-1}, // DAY_OF_WEEK
52     {       -1,       -1,        5,        5}, // DAY_OF_WEEK_IN_MONTH
53     {/*N/A*/-1,/*N/A*/-1,/*N/A*/-1,/*N/A*/-1}, // AM_PM
54     {/*N/A*/-1,/*N/A*/-1,/*N/A*/-1,/*N/A*/-1}, // HOUR
55     {/*N/A*/-1,/*N/A*/-1,/*N/A*/-1,/*N/A*/-1}, // HOUR_OF_DAY
56     {/*N/A*/-1,/*N/A*/-1,/*N/A*/-1,/*N/A*/-1}, // MINUTE
57     {/*N/A*/-1,/*N/A*/-1,/*N/A*/-1,/*N/A*/-1}, // SECOND
58     {/*N/A*/-1,/*N/A*/-1,/*N/A*/-1,/*N/A*/-1}, // MILLISECOND
59     {/*N/A*/-1,/*N/A*/-1,/*N/A*/-1,/*N/A*/-1}, // ZONE_OFFSET
60     {/*N/A*/-1,/*N/A*/-1,/*N/A*/-1,/*N/A*/-1}, // DST_OFFSET
61     { -5000000, -5000000,  5000000,  5000000}, // YEAR_WOY
62     {/*N/A*/-1,/*N/A*/-1,/*N/A*/-1,/*N/A*/-1}, // DOW_LOCAL
63     { -5000000, -5000000,  5000000,  5000000}, // EXTENDED_YEAR
64     {/*N/A*/-1,/*N/A*/-1,/*N/A*/-1,/*N/A*/-1}, // JULIAN_DAY
65     {/*N/A*/-1,/*N/A*/-1,/*N/A*/-1,/*N/A*/-1}, // MILLISECONDS_IN_DAY
66     {/*N/A*/-1,/*N/A*/-1,/*N/A*/-1,/*N/A*/-1}, // IS_LEAP_MONTH
67     {        0,        0,       11,       12}, // ORDINAL_MONTH
68 };
69 
70 /**
71 * The lengths of the Hebrew months.  This is complicated, because there
72 * are three different types of years, or six if you count leap years.
73 * Due to the rules for postponing the start of the year to avoid having
74 * certain holidays fall on the sabbath, the year can end up being three
75 * different lengths, called "deficient", "normal", and "complete".
76 */
77 static const int8_t MONTH_LENGTH[][3] = {
78     // Deficient  Normal     Complete
79     {   30,         30,         30     },           //Tishri
80     {   29,         29,         30     },           //Heshvan
81     {   29,         30,         30     },           //Kislev
82     {   29,         29,         29     },           //Tevet
83     {   30,         30,         30     },           //Shevat
84     {   30,         30,         30     },           //Adar I (leap years only)
85     {   29,         29,         29     },           //Adar
86     {   30,         30,         30     },           //Nisan
87     {   29,         29,         29     },           //Iyar
88     {   30,         30,         30     },           //Sivan
89     {   29,         29,         29     },           //Tammuz
90     {   30,         30,         30     },           //Av
91     {   29,         29,         29     },           //Elul
92 };
93 
94 /**
95 * The cumulative # of days to the end of each month in a non-leap year
96 * Although this can be calculated from the MONTH_LENGTH table,
97 * keeping it around separately makes some calculations a lot faster
98 */
99 
100 static const int16_t MONTH_START[][3] = {
101     // Deficient  Normal     Complete
102     {    0,          0,          0  },          // (placeholder)
103     {   30,         30,         30  },          // Tishri
104     {   59,         59,         60  },          // Heshvan
105     {   88,         89,         90  },          // Kislev
106     {  117,        118,        119  },          // Tevet
107     {  147,        148,        149  },          // Shevat
108     {  147,        148,        149  },          // (Adar I placeholder)
109     {  176,        177,        178  },          // Adar
110     {  206,        207,        208  },          // Nisan
111     {  235,        236,        237  },          // Iyar
112     {  265,        266,        267  },          // Sivan
113     {  294,        295,        296  },          // Tammuz
114     {  324,        325,        326  },          // Av
115     {  353,        354,        355  },          // Elul
116 };
117 
118 /**
119 * The cumulative # of days to the end of each month in a leap year
120 */
121 static const int16_t  LEAP_MONTH_START[][3] = {
122     // Deficient  Normal     Complete
123     {    0,          0,          0  },          // (placeholder)
124     {   30,         30,         30  },          // Tishri
125     {   59,         59,         60  },          // Heshvan
126     {   88,         89,         90  },          // Kislev
127     {  117,        118,        119  },          // Tevet
128     {  147,        148,        149  },          // Shevat
129     {  177,        178,        179  },          // Adar I
130     {  206,        207,        208  },          // Adar II
131     {  236,        237,        238  },          // Nisan
132     {  265,        266,        267  },          // Iyar
133     {  295,        296,        297  },          // Sivan
134     {  324,        325,        326  },          // Tammuz
135     {  354,        355,        356  },          // Av
136     {  383,        384,        385  },          // Elul
137 };
138 
139 static icu::CalendarCache *gCache =  nullptr;
140 
141 U_CDECL_BEGIN
calendar_hebrew_cleanup()142 static UBool calendar_hebrew_cleanup() {
143     delete gCache;
144     gCache = nullptr;
145     return true;
146 }
147 U_CDECL_END
148 
149 U_NAMESPACE_BEGIN
150 //-------------------------------------------------------------------------
151 // Constructors...
152 //-------------------------------------------------------------------------
153 
154 /**
155 * Constructs a default <code>HebrewCalendar</code> using the current time
156 * in the default time zone with the default locale.
157 * @internal
158 */
HebrewCalendar(const Locale & aLocale,UErrorCode & success)159 HebrewCalendar::HebrewCalendar(const Locale& aLocale, UErrorCode& success)
160 :   Calendar(TimeZone::forLocaleOrDefault(aLocale), aLocale, success)
161 
162 {
163     setTimeInMillis(getNow(), success); // Call this again now that the vtable is set up properly.
164 }
165 
166 
~HebrewCalendar()167 HebrewCalendar::~HebrewCalendar() {
168 }
169 
getType() const170 const char *HebrewCalendar::getType() const {
171     return "hebrew";
172 }
173 
clone() const174 HebrewCalendar* HebrewCalendar::clone() const {
175     return new HebrewCalendar(*this);
176 }
177 
HebrewCalendar(const HebrewCalendar & other)178 HebrewCalendar::HebrewCalendar(const HebrewCalendar& other) : Calendar(other) {
179 }
180 
181 
182 //-------------------------------------------------------------------------
183 // Rolling and adding functions overridden from Calendar
184 //
185 // These methods call through to the default implementation in IBMCalendar
186 // for most of the fields and only handle the unusual ones themselves.
187 //-------------------------------------------------------------------------
188 
189 /**
190 * Add a signed amount to a specified field, using this calendar's rules.
191 * For example, to add three days to the current date, you can call
192 * <code>add(Calendar.DATE, 3)</code>.
193 * <p>
194 * When adding to certain fields, the values of other fields may conflict and
195 * need to be changed.  For example, when adding one to the {@link #MONTH MONTH} field
196 * for the date "30 Av 5758", the {@link #DAY_OF_MONTH DAY_OF_MONTH} field
197 * must be adjusted so that the result is "29 Elul 5758" rather than the invalid
198 * "30 Elul 5758".
199 * <p>
200 * This method is able to add to
201 * all fields except for {@link #ERA ERA}, {@link #DST_OFFSET DST_OFFSET},
202 * and {@link #ZONE_OFFSET ZONE_OFFSET}.
203 * <p>
204 * <b>Note:</b> You should always use {@link #roll roll} and add rather
205 * than attempting to perform arithmetic operations directly on the fields
206 * of a <tt>HebrewCalendar</tt>.  Since the {@link #MONTH MONTH} field behaves
207 * discontinuously in non-leap years, simple arithmetic can give invalid results.
208 * <p>
209 * @param field     the time field.
210 * @param amount    the amount to add to the field.
211 *
212 * @exception   IllegalArgumentException if the field is invalid or refers
213 *              to a field that cannot be handled by this method.
214 * @internal
215 */
add(UCalendarDateFields field,int32_t amount,UErrorCode & status)216 void HebrewCalendar::add(UCalendarDateFields field, int32_t amount, UErrorCode& status)
217 {
218     if(U_FAILURE(status)) {
219         return;
220     }
221     switch (field) {
222   case UCAL_MONTH:
223   case UCAL_ORDINAL_MONTH:
224       {
225           // We can't just do a set(MONTH, get(MONTH) + amount).  The
226           // reason is ADAR_1.  Suppose amount is +2 and we land in
227           // ADAR_1 -- then we have to bump to ADAR_2 aka ADAR.  But
228           // if amount is -2 and we land in ADAR_1, then we have to
229           // bump the other way -- down to SHEVAT.  - Alan 11/00
230           int32_t month = get(UCAL_MONTH, status);
231           int32_t year = get(UCAL_YEAR, status);
232           UBool acrossAdar1;
233           if (amount > 0) {
234               acrossAdar1 = (month < ADAR_1); // started before ADAR_1?
235               month += amount;
236               for (;;) {
237                   if (acrossAdar1 && month>=ADAR_1 && !isLeapYear(year)) {
238                       ++month;
239                   }
240                   if (month <= ELUL) {
241                       break;
242                   }
243                   month -= ELUL+1;
244                   ++year;
245                   acrossAdar1 = true;
246               }
247           } else {
248               acrossAdar1 = (month > ADAR_1); // started after ADAR_1?
249               month += amount;
250               for (;;) {
251                   if (acrossAdar1 && month<=ADAR_1 && !isLeapYear(year)) {
252                       --month;
253                   }
254                   if (month >= 0) {
255                       break;
256                   }
257                   month += ELUL+1;
258                   --year;
259                   acrossAdar1 = true;
260               }
261           }
262           set(UCAL_MONTH, month);
263           set(UCAL_YEAR, year);
264           pinField(UCAL_DAY_OF_MONTH, status);
265           break;
266       }
267 
268   default:
269       Calendar::add(field, amount, status);
270       break;
271     }
272 }
273 
274 /**
275 * @deprecated ICU 2.6 use UCalendarDateFields instead of EDateFields
276 */
add(EDateFields field,int32_t amount,UErrorCode & status)277 void HebrewCalendar::add(EDateFields field, int32_t amount, UErrorCode& status)
278 {
279     add((UCalendarDateFields)field, amount, status);
280 }
281 
282 /**
283 * Rolls (up/down) a specified amount time on the given field.  For
284 * example, to roll the current date up by three days, you can call
285 * <code>roll(Calendar.DATE, 3)</code>.  If the
286 * field is rolled past its maximum allowable value, it will "wrap" back
287 * to its minimum and continue rolling.
288 * For example, calling <code>roll(Calendar.DATE, 10)</code>
289 * on a Hebrew calendar set to "25 Av 5758" will result in the date "5 Av 5758".
290 * <p>
291 * When rolling certain fields, the values of other fields may conflict and
292 * need to be changed.  For example, when rolling the {@link #MONTH MONTH} field
293 * upward by one for the date "30 Av 5758", the {@link #DAY_OF_MONTH DAY_OF_MONTH} field
294 * must be adjusted so that the result is "29 Elul 5758" rather than the invalid
295 * "30 Elul".
296 * <p>
297 * This method is able to roll
298 * all fields except for {@link #ERA ERA}, {@link #DST_OFFSET DST_OFFSET},
299 * and {@link #ZONE_OFFSET ZONE_OFFSET}.  Subclasses may, of course, add support for
300 * additional fields in their overrides of <code>roll</code>.
301 * <p>
302 * <b>Note:</b> You should always use roll and {@link #add add} rather
303 * than attempting to perform arithmetic operations directly on the fields
304 * of a <tt>HebrewCalendar</tt>.  Since the {@link #MONTH MONTH} field behaves
305 * discontinuously in non-leap years, simple arithmetic can give invalid results.
306 * <p>
307 * @param field     the time field.
308 * @param amount    the amount by which the field should be rolled.
309 *
310 * @exception   IllegalArgumentException if the field is invalid or refers
311 *              to a field that cannot be handled by this method.
312 * @internal
313 */
roll(UCalendarDateFields field,int32_t amount,UErrorCode & status)314 void HebrewCalendar::roll(UCalendarDateFields field, int32_t amount, UErrorCode& status)
315 {
316     if(U_FAILURE(status)) {
317         return;
318     }
319     switch (field) {
320   case UCAL_MONTH:
321   case UCAL_ORDINAL_MONTH:
322       {
323           int32_t month = get(UCAL_MONTH, status);
324           int32_t year = get(UCAL_YEAR, status);
325 
326           UBool leapYear = isLeapYear(year);
327           int32_t yearLength = monthsInYear(year);
328           int32_t newMonth = month + (amount % yearLength);
329           //
330           // If it's not a leap year and we're rolling past the missing month
331           // of ADAR_1, we need to roll an extra month to make up for it.
332           //
333           if (!leapYear) {
334               if (amount > 0 && month < ADAR_1 && newMonth >= ADAR_1) {
335                   newMonth++;
336               } else if (amount < 0 && month > ADAR_1 && newMonth <= ADAR_1) {
337                   newMonth--;
338               }
339           }
340           set(UCAL_MONTH, (newMonth + 13) % 13);
341           pinField(UCAL_DAY_OF_MONTH, status);
342           return;
343       }
344   default:
345       Calendar::roll(field, amount, status);
346     }
347 }
348 
roll(EDateFields field,int32_t amount,UErrorCode & status)349 void HebrewCalendar::roll(EDateFields field, int32_t amount, UErrorCode& status) {
350     roll((UCalendarDateFields)field, amount, status);
351 }
352 
353 //-------------------------------------------------------------------------
354 // Support methods
355 //-------------------------------------------------------------------------
356 
357 // Hebrew date calculations are performed in terms of days, hours, and
358 // "parts" (or halakim), which are 1/1080 of an hour, or 3 1/3 seconds.
359 static const int32_t HOUR_PARTS = 1080;
360 static const int32_t DAY_PARTS  = 24*HOUR_PARTS;
361 
362 // An approximate value for the length of a lunar month.
363 // It is used to calculate the approximate year and month of a given
364 // absolute date.
365 static const int32_t  MONTH_DAYS = 29;
366 static const int32_t MONTH_FRACT = 12*HOUR_PARTS + 793;
367 static const int32_t MONTH_PARTS = MONTH_DAYS*DAY_PARTS + MONTH_FRACT;
368 
369 // The time of the new moon (in parts) on 1 Tishri, year 1 (the epoch)
370 // counting from noon on the day before.  BAHARAD is an abbreviation of
371 // Bet (Monday), Hey (5 hours from sunset), Resh-Daled (204).
372 static const int32_t BAHARAD = 11*HOUR_PARTS + 204;
373 
374 /**
375 * Finds the day # of the first day in the given Hebrew year.
376 * To do this, we want to calculate the time of the Tishri 1 new moon
377 * in that year.
378 * <p>
379 * The algorithm here is similar to ones described in a number of
380 * references, including:
381 * <ul>
382 * <li>"Calendrical Calculations", by Nachum Dershowitz & Edward Reingold,
383 *     Cambridge University Press, 1997, pages 85-91.
384 *
385 * <li>Hebrew Calendar Science and Myths,
386 *     <a href="http://www.geocities.com/Athens/1584/">
387 *     http://www.geocities.com/Athens/1584/</a>
388 *
389 * <li>The Calendar FAQ,
390 *      <a href="http://www.faqs.org/faqs/calendars/faq/">
391 *      http://www.faqs.org/faqs/calendars/faq/</a>
392 * </ul>
393 */
startOfYear(int32_t year,UErrorCode & status)394 int32_t HebrewCalendar::startOfYear(int32_t year, UErrorCode &status)
395 {
396     ucln_i18n_registerCleanup(UCLN_I18N_HEBREW_CALENDAR, calendar_hebrew_cleanup);
397     int32_t day = CalendarCache::get(&gCache, year, status);
398 
399     if (day == 0) {
400         // # of months before year
401         int32_t months = (int32_t)ClockMath::floorDivide((235 * (int64_t)year - 234), (int64_t)19);
402 
403         int64_t frac = (int64_t)months * MONTH_FRACT + BAHARAD;  // Fractional part of day #
404         day  = months * 29 + (int32_t)(frac / DAY_PARTS);        // Whole # part of calculation
405         frac = frac % DAY_PARTS;                        // Time of day
406 
407         int32_t wd = (day % 7);                        // Day of week (0 == Monday)
408 
409         if (wd == 2 || wd == 4 || wd == 6) {
410             // If the 1st is on Sun, Wed, or Fri, postpone to the next day
411             day += 1;
412             wd = (day % 7);
413         }
414         if (wd == 1 && frac > 15*HOUR_PARTS+204 && !isLeapYear(year) ) {
415             // If the new moon falls after 3:11:20am (15h204p from the previous noon)
416             // on a Tuesday and it is not a leap year, postpone by 2 days.
417             // This prevents 356-day years.
418             day += 2;
419         }
420         else if (wd == 0 && frac > 21*HOUR_PARTS+589 && isLeapYear(year-1) ) {
421             // If the new moon falls after 9:32:43 1/3am (21h589p from yesterday noon)
422             // on a Monday and *last* year was a leap year, postpone by 1 day.
423             // Prevents 382-day years.
424             day += 1;
425         }
426         CalendarCache::put(&gCache, year, day, status);
427     }
428     return day;
429 }
430 
431 /**
432 * Find the day of the week for a given day
433 *
434 * @param day   The # of days since the start of the Hebrew calendar,
435 *              1-based (i.e. 1/1/1 AM is day 1).
436 */
absoluteDayToDayOfWeek(int32_t day)437 int32_t HebrewCalendar::absoluteDayToDayOfWeek(int32_t day)
438 {
439     // We know that 1/1/1 AM is a Monday, which makes the math easy...
440     return (day % 7) + 1;
441 }
442 
443 /**
444 * Returns the the type of a given year.
445 *  0   "Deficient" year with 353 or 383 days
446 *  1   "Normal"    year with 354 or 384 days
447 *  2   "Complete"  year with 355 or 385 days
448 */
yearType(int32_t year) const449 int32_t HebrewCalendar::yearType(int32_t year) const
450 {
451     int32_t yearLength = handleGetYearLength(year);
452 
453     if (yearLength > 380) {
454         yearLength -= 30;        // Subtract length of leap month.
455     }
456 
457     int type = 0;
458 
459     switch (yearLength) {
460   case 353:
461       type = 0; break;
462   case 354:
463       type = 1; break;
464   case 355:
465       type = 2; break;
466   default:
467       //throw new RuntimeException("Illegal year length " + yearLength + " in year " + year);
468       type = 1;
469     }
470     return type;
471 }
472 
473 /**
474 * Determine whether a given Hebrew year is a leap year
475 *
476 * The rule here is that if (year % 19) == 0, 3, 6, 8, 11, 14, or 17.
477 * The formula below performs the same test, believe it or not.
478 */
isLeapYear(int32_t year)479 UBool HebrewCalendar::isLeapYear(int32_t year) {
480     //return (year * 12 + 17) % 19 >= 12;
481     int32_t x = (year*12 + 17) % 19;
482     return x >= ((x < 0) ? -7 : 12);
483 }
484 
monthsInYear(int32_t year)485 int32_t HebrewCalendar::monthsInYear(int32_t year) {
486     return isLeapYear(year) ? 13 : 12;
487 }
488 
489 //-------------------------------------------------------------------------
490 // Calendar framework
491 //-------------------------------------------------------------------------
492 
493 /**
494 * @internal
495 */
handleGetLimit(UCalendarDateFields field,ELimitType limitType) const496 int32_t HebrewCalendar::handleGetLimit(UCalendarDateFields field, ELimitType limitType) const {
497     return LIMITS[field][limitType];
498 }
499 
500 /**
501 * Returns the length of the given month in the given year
502 * @internal
503 */
handleGetMonthLength(int32_t extendedYear,int32_t month) const504 int32_t HebrewCalendar::handleGetMonthLength(int32_t extendedYear, int32_t month) const {
505     // Resolve out-of-range months.  This is necessary in order to
506     // obtain the correct year.  We correct to
507     // a 12- or 13-month year (add/subtract 12 or 13, depending
508     // on the year) but since we _always_ number from 0..12, and
509     // the leap year determines whether or not month 5 (Adar 1)
510     // is present, we allow 0..12 in any given year.
511     while (month < 0) {
512         month += monthsInYear(--extendedYear);
513     }
514     // Careful: allow 0..12 in all years
515     while (month > 12) {
516         month -= monthsInYear(extendedYear++);
517     }
518 
519     switch (month) {
520     case HESHVAN:
521     case KISLEV:
522       // These two month lengths can vary
523       return MONTH_LENGTH[month][yearType(extendedYear)];
524 
525     default:
526       // The rest are a fixed length
527       return MONTH_LENGTH[month][0];
528     }
529 }
530 
531 /**
532 * Returns the number of days in the given Hebrew year
533 * @internal
534 */
handleGetYearLength(int32_t eyear) const535 int32_t HebrewCalendar::handleGetYearLength(int32_t eyear) const {
536     UErrorCode status = U_ZERO_ERROR;
537     return startOfYear(eyear+1, status) - startOfYear(eyear, status);
538 }
539 
validateField(UCalendarDateFields field,UErrorCode & status)540 void HebrewCalendar::validateField(UCalendarDateFields field, UErrorCode &status) {
541     if ((field == UCAL_MONTH || field == UCAL_ORDINAL_MONTH)
542         && !isLeapYear(handleGetExtendedYear()) && internalGetMonth() == ADAR_1) {
543         status = U_ILLEGAL_ARGUMENT_ERROR;
544         return;
545     }
546     Calendar::validateField(field, status);
547 }
548 //-------------------------------------------------------------------------
549 // Functions for converting from milliseconds to field values
550 //-------------------------------------------------------------------------
551 
552 /**
553 * Subclasses may override this method to compute several fields
554 * specific to each calendar system.  These are:
555 *
556 * <ul><li>ERA
557 * <li>YEAR
558 * <li>MONTH
559 * <li>DAY_OF_MONTH
560 * <li>DAY_OF_YEAR
561 * <li>EXTENDED_YEAR</ul>
562 *
563 * Subclasses can refer to the DAY_OF_WEEK and DOW_LOCAL fields,
564 * which will be set when this method is called.  Subclasses can
565 * also call the getGregorianXxx() methods to obtain Gregorian
566 * calendar equivalents for the given Julian day.
567 *
568 * <p>In addition, subclasses should compute any subclass-specific
569 * fields, that is, fields from BASE_FIELD_COUNT to
570 * getFieldCount() - 1.
571 * @internal
572 */
handleComputeFields(int32_t julianDay,UErrorCode & status)573 void HebrewCalendar::handleComputeFields(int32_t julianDay, UErrorCode &status) {
574     int32_t d = julianDay - 347997;
575     double m = ClockMath::floorDivide((d * (double)DAY_PARTS), (double) MONTH_PARTS);  // Months (approx)
576     int32_t year = (int32_t)(ClockMath::floorDivide((19. * m + 234.), 235.) + 1.);     // Years (approx)
577     int32_t ys  = startOfYear(year, status);                   // 1st day of year
578     int32_t dayOfYear = (d - ys);
579 
580     // Because of the postponement rules, it's possible to guess wrong.  Fix it.
581     while (dayOfYear < 1) {
582         year--;
583         ys  = startOfYear(year, status);
584         dayOfYear = (d - ys);
585     }
586 
587     // Now figure out which month we're in, and the date within that month
588     int32_t type = yearType(year);
589     UBool isLeap = isLeapYear(year);
590 
591     int32_t month = 0;
592     int32_t momax = UPRV_LENGTHOF(MONTH_START);
593     while (month < momax && dayOfYear > (  isLeap ? LEAP_MONTH_START[month][type] : MONTH_START[month][type] ) ) {
594         month++;
595     }
596     if (month >= momax || month<=0) {
597         // TODO: I found dayOfYear could be out of range when
598         // a large value is set to julianDay.  I patched startOfYear
599         // to reduce the chace, but it could be still reproduced either
600         // by startOfYear or other places.  For now, we check
601         // the month is in valid range to avoid out of array index
602         // access problem here.  However, we need to carefully review
603         // the calendar implementation to check the extreme limit of
604         // each calendar field and the code works well for any values
605         // in the valid value range.  -yoshito
606         status = U_ILLEGAL_ARGUMENT_ERROR;
607         return;
608     }
609     month--;
610     int dayOfMonth = dayOfYear - (isLeap ? LEAP_MONTH_START[month][type] : MONTH_START[month][type]);
611 
612     internalSet(UCAL_ERA, 0);
613     internalSet(UCAL_YEAR, year);
614     internalSet(UCAL_EXTENDED_YEAR, year);
615     int32_t ordinal_month = month;
616     if (!isLeap && ordinal_month > ADAR_1) {
617       ordinal_month--;
618     }
619     internalSet(UCAL_ORDINAL_MONTH, ordinal_month);
620     internalSet(UCAL_MONTH, month);
621     internalSet(UCAL_DAY_OF_MONTH, dayOfMonth);
622     internalSet(UCAL_DAY_OF_YEAR, dayOfYear);
623 }
624 
625 //-------------------------------------------------------------------------
626 // Functions for converting from field values to milliseconds
627 //-------------------------------------------------------------------------
628 
629 /**
630 * @internal
631 */
handleGetExtendedYear()632 int32_t HebrewCalendar::handleGetExtendedYear() {
633     int32_t year;
634     if (newerField(UCAL_EXTENDED_YEAR, UCAL_YEAR) == UCAL_EXTENDED_YEAR) {
635         year = internalGet(UCAL_EXTENDED_YEAR, 1); // Default to year 1
636     } else {
637         year = internalGet(UCAL_YEAR, 1); // Default to year 1
638     }
639     return year;
640 }
641 
642 /**
643 * Return JD of start of given month/year.
644 * @internal
645 */
handleComputeMonthStart(int32_t eyear,int32_t month,UBool) const646 int32_t HebrewCalendar::handleComputeMonthStart(int32_t eyear, int32_t month, UBool /*useMonth*/) const {
647     UErrorCode status = U_ZERO_ERROR;
648     // Resolve out-of-range months.  This is necessary in order to
649     // obtain the correct year.  We correct to
650     // a 12- or 13-month year (add/subtract 12 or 13, depending
651     // on the year) but since we _always_ number from 0..12, and
652     // the leap year determines whether or not month 5 (Adar 1)
653     // is present, we allow 0..12 in any given year.
654     while (month < 0) {
655         month += monthsInYear(--eyear);
656     }
657     // Careful: allow 0..12 in all years
658     while (month > 12) {
659         month -= monthsInYear(eyear++);
660     }
661 
662     int32_t day = startOfYear(eyear, status);
663 
664     if(U_FAILURE(status)) {
665         return 0;
666     }
667 
668     if (month != 0) {
669         if (isLeapYear(eyear)) {
670             day += LEAP_MONTH_START[month][yearType(eyear)];
671         } else {
672             day += MONTH_START[month][yearType(eyear)];
673         }
674     }
675 
676     return (int) (day + 347997);
677 }
678 
679 constexpr uint32_t kHebrewRelatedYearDiff = -3760;
680 
getRelatedYear(UErrorCode & status) const681 int32_t HebrewCalendar::getRelatedYear(UErrorCode &status) const
682 {
683     int32_t year = get(UCAL_EXTENDED_YEAR, status);
684     if (U_FAILURE(status)) {
685         return 0;
686     }
687     return year + kHebrewRelatedYearDiff;
688 }
689 
setRelatedYear(int32_t year)690 void HebrewCalendar::setRelatedYear(int32_t year)
691 {
692     // set extended year
693     set(UCAL_EXTENDED_YEAR, year - kHebrewRelatedYearDiff);
694 }
695 
696 /**
697  * The system maintains a static default century start date and Year.  They are
698  * initialized the first time they are used.  Once the system default century date
699  * and year are set, they do not change.
700  */
701 static UDate           gSystemDefaultCenturyStart       = DBL_MIN;
702 static int32_t         gSystemDefaultCenturyStartYear   = -1;
703 static icu::UInitOnce  gSystemDefaultCenturyInit        {};
704 
haveDefaultCentury() const705 UBool HebrewCalendar::haveDefaultCentury() const
706 {
707     return true;
708 }
709 
initializeSystemDefaultCentury()710 static void U_CALLCONV initializeSystemDefaultCentury()
711 {
712     // initialize systemDefaultCentury and systemDefaultCenturyYear based
713     // on the current time.  They'll be set to 80 years before
714     // the current time.
715     UErrorCode status = U_ZERO_ERROR;
716     HebrewCalendar calendar(Locale("@calendar=hebrew"),status);
717     if (U_SUCCESS(status)) {
718         calendar.setTime(Calendar::getNow(), status);
719         calendar.add(UCAL_YEAR, -80, status);
720 
721         gSystemDefaultCenturyStart = calendar.getTime(status);
722         gSystemDefaultCenturyStartYear = calendar.get(UCAL_YEAR, status);
723     }
724     // We have no recourse upon failure unless we want to propagate the failure
725     // out.
726 }
727 
728 
defaultCenturyStart() const729 UDate HebrewCalendar::defaultCenturyStart() const {
730     // lazy-evaluate systemDefaultCenturyStart
731     umtx_initOnce(gSystemDefaultCenturyInit, &initializeSystemDefaultCentury);
732     return gSystemDefaultCenturyStart;
733 }
734 
defaultCenturyStartYear() const735 int32_t HebrewCalendar::defaultCenturyStartYear() const {
736     // lazy-evaluate systemDefaultCenturyStartYear
737     umtx_initOnce(gSystemDefaultCenturyInit, &initializeSystemDefaultCentury);
738     return gSystemDefaultCenturyStartYear;
739 }
740 
inTemporalLeapYear(UErrorCode & status) const741 bool HebrewCalendar::inTemporalLeapYear(UErrorCode& status) const {
742     if (U_FAILURE(status)) return false;
743     int32_t eyear = get(UCAL_EXTENDED_YEAR, status);
744     if (U_FAILURE(status)) return false;
745     return isLeapYear(eyear);
746 }
747 
748 static const char * const gTemporalMonthCodesForHebrew[] = {
749     "M01", "M02", "M03", "M04", "M05", "M05L", "M06",
750     "M07", "M08", "M09", "M10", "M11", "M12", nullptr
751 };
752 
getTemporalMonthCode(UErrorCode & status) const753 const char* HebrewCalendar::getTemporalMonthCode(UErrorCode& status) const {
754     int32_t month = get(UCAL_MONTH, status);
755     if (U_FAILURE(status)) return nullptr;
756     return gTemporalMonthCodesForHebrew[month];
757 }
758 
setTemporalMonthCode(const char * code,UErrorCode & status)759 void HebrewCalendar::setTemporalMonthCode(const char* code, UErrorCode& status )
760 {
761     if (U_FAILURE(status)) return;
762     int32_t len = static_cast<int32_t>(uprv_strlen(code));
763     if (len == 3 || len == 4) {
764         for (int m = 0; gTemporalMonthCodesForHebrew[m] != nullptr; m++) {
765             if (uprv_strcmp(code, gTemporalMonthCodesForHebrew[m]) == 0) {
766                 set(UCAL_MONTH, m);
767                 return;
768             }
769         }
770     }
771     status = U_ILLEGAL_ARGUMENT_ERROR;
772 }
773 
internalGetMonth() const774 int32_t HebrewCalendar::internalGetMonth() const {
775     if (resolveFields(kMonthPrecedence) == UCAL_ORDINAL_MONTH) {
776         int32_t ordinalMonth = internalGet(UCAL_ORDINAL_MONTH);
777         HebrewCalendar *nonConstThis = (HebrewCalendar*)this; // cast away const
778 
779         int32_t year = nonConstThis->handleGetExtendedYear();
780         return ordinalMonth + (((!isLeapYear(year)) && (ordinalMonth > ADAR_1)) ? 1: 0);
781     }
782     return Calendar::internalGetMonth();
783 }
784 
785 UOBJECT_DEFINE_RTTI_IMPLEMENTATION(HebrewCalendar)
786 
787 U_NAMESPACE_END
788 
789 #endif // UCONFIG_NO_FORMATTING
790 
791