xref: /aosp_15_r20/external/icu/icu4c/source/i18n/chnsecal.cpp (revision 0e209d3975ff4a8c132096b14b0e9364a753506e)
1 // © 2016 and later: Unicode, Inc. and others.
2 // License & terms of use: http://www.unicode.org/copyright.html
3 /*
4  ******************************************************************************
5  * Copyright (C) 2007-2014, International Business Machines Corporation
6  * and others. All Rights Reserved.
7  ******************************************************************************
8  *
9  * File CHNSECAL.CPP
10  *
11  * Modification History:
12  *
13  *   Date        Name        Description
14  *   9/18/2007  ajmacher         ported from java ChineseCalendar
15  *****************************************************************************
16  */
17 
18 #include "chnsecal.h"
19 
20 #include <cstdint>
21 
22 #if !UCONFIG_NO_FORMATTING
23 
24 #include "umutex.h"
25 #include <float.h>
26 #include "gregoimp.h" // Math
27 #include "astro.h" // CalendarAstronomer and CalendarCache
28 #include "unicode/simpletz.h"
29 #include "uhash.h"
30 #include "ucln_in.h"
31 #include "cstring.h"
32 
33 // Debugging
34 #ifdef U_DEBUG_CHNSECAL
35 # include <stdio.h>
36 # include <stdarg.h>
debug_chnsecal_loc(const char * f,int32_t l)37 static void debug_chnsecal_loc(const char *f, int32_t l)
38 {
39     fprintf(stderr, "%s:%d: ", f, l);
40 }
41 
debug_chnsecal_msg(const char * pat,...)42 static void debug_chnsecal_msg(const char *pat, ...)
43 {
44     va_list ap;
45     va_start(ap, pat);
46     vfprintf(stderr, pat, ap);
47     fflush(stderr);
48 }
49 // must use double parens, i.e.:  U_DEBUG_CHNSECAL_MSG(("four is: %d",4));
50 #define U_DEBUG_CHNSECAL_MSG(x) {debug_chnsecal_loc(__FILE__,__LINE__);debug_chnsecal_msg x;}
51 #else
52 #define U_DEBUG_CHNSECAL_MSG(x)
53 #endif
54 
55 
56 // Lazy Creation & Access synchronized by class CalendarCache with a mutex.
57 static icu::CalendarCache *gWinterSolsticeCache = nullptr;
58 static icu::CalendarCache *gNewYearCache = nullptr;
59 
60 static icu::TimeZone *gAstronomerTimeZone = nullptr;
61 static icu::UInitOnce gAstronomerTimeZoneInitOnce {};
62 
63 /**
64  * The start year of the Chinese calendar, the 61st year of the reign
65  * of Huang Di.  Some sources use the first year of his reign,
66  * resulting in EXTENDED_YEAR values 60 years greater and ERA (cycle)
67  * values one greater.
68  */
69 static const int32_t CHINESE_EPOCH_YEAR = -2636; // Gregorian year
70 
71 /**
72  * The offset from GMT in milliseconds at which we perform astronomical
73  * computations.  Some sources use a different historically accurate
74  * offset of GMT+7:45:40 for years before 1929; we do not do this.
75  */
76 static const int32_t CHINA_OFFSET = 8 * kOneHour;
77 
78 /**
79  * Value to be added or subtracted from the local days of a new moon to
80  * get close to the next or prior new moon, but not cross it.  Must be
81  * >= 1 and < CalendarAstronomer.SYNODIC_MONTH.
82  */
83 static const int32_t SYNODIC_GAP = 25;
84 
85 
86 U_CDECL_BEGIN
calendar_chinese_cleanup()87 static UBool calendar_chinese_cleanup() {
88     if (gWinterSolsticeCache) {
89         delete gWinterSolsticeCache;
90         gWinterSolsticeCache = nullptr;
91     }
92     if (gNewYearCache) {
93         delete gNewYearCache;
94         gNewYearCache = nullptr;
95     }
96     if (gAstronomerTimeZone) {
97         delete gAstronomerTimeZone;
98         gAstronomerTimeZone = nullptr;
99     }
100     gAstronomerTimeZoneInitOnce.reset();
101     return true;
102 }
103 U_CDECL_END
104 
105 U_NAMESPACE_BEGIN
106 
107 
108 // Implementation of the ChineseCalendar class
109 
110 
111 //-------------------------------------------------------------------------
112 // Constructors...
113 //-------------------------------------------------------------------------
114 
115 
116 namespace {
117 
118 const TimeZone* getAstronomerTimeZone();
119 int32_t newMoonNear(const TimeZone*, double, UBool);
120 int32_t newYear(const icu::ChineseCalendar::Setting&, int32_t);
121 UBool isLeapMonthBetween(const TimeZone*, int32_t, int32_t);
122 
123 } // namespace
124 
clone() const125 ChineseCalendar* ChineseCalendar::clone() const {
126     return new ChineseCalendar(*this);
127 }
128 
ChineseCalendar(const Locale & aLocale,UErrorCode & success)129 ChineseCalendar::ChineseCalendar(const Locale& aLocale, UErrorCode& success)
130 :   Calendar(TimeZone::forLocaleOrDefault(aLocale), aLocale, success),
131     hasLeapMonthBetweenWinterSolstices(false)
132 {
133     setTimeInMillis(getNow(), success); // Call this again now that the vtable is set up properly.
134 }
135 
ChineseCalendar(const ChineseCalendar & other)136 ChineseCalendar::ChineseCalendar(const ChineseCalendar& other) : Calendar(other) {
137     hasLeapMonthBetweenWinterSolstices = other.hasLeapMonthBetweenWinterSolstices;
138 }
139 
~ChineseCalendar()140 ChineseCalendar::~ChineseCalendar()
141 {
142 }
143 
getType() const144 const char *ChineseCalendar::getType() const {
145     return "chinese";
146 }
147 
148 namespace { // anonymous
149 
initAstronomerTimeZone()150 static void U_CALLCONV initAstronomerTimeZone() {
151     gAstronomerTimeZone = new SimpleTimeZone(CHINA_OFFSET, UNICODE_STRING_SIMPLE("CHINA_ZONE") );
152     ucln_i18n_registerCleanup(UCLN_I18N_CHINESE_CALENDAR, calendar_chinese_cleanup);
153 }
154 
getAstronomerTimeZone()155 const TimeZone* getAstronomerTimeZone() {
156     umtx_initOnce(gAstronomerTimeZoneInitOnce, &initAstronomerTimeZone);
157     return gAstronomerTimeZone;
158 }
159 
160 } // namespace anonymous
161 
162 //-------------------------------------------------------------------------
163 // Minimum / Maximum access functions
164 //-------------------------------------------------------------------------
165 
166 
167 static const int32_t LIMITS[UCAL_FIELD_COUNT][4] = {
168     // Minimum  Greatest     Least    Maximum
169     //           Minimum   Maximum
170     {        1,        1,    83333,    83333}, // ERA
171     {        1,        1,       60,       60}, // YEAR
172     {        0,        0,       11,       11}, // MONTH
173     {        1,        1,       50,       55}, // WEEK_OF_YEAR
174     {/*N/A*/-1,/*N/A*/-1,/*N/A*/-1,/*N/A*/-1}, // WEEK_OF_MONTH
175     {        1,        1,       29,       30}, // DAY_OF_MONTH
176     {        1,        1,      353,      385}, // DAY_OF_YEAR
177     {/*N/A*/-1,/*N/A*/-1,/*N/A*/-1,/*N/A*/-1}, // DAY_OF_WEEK
178     {       -1,       -1,        5,        5}, // DAY_OF_WEEK_IN_MONTH
179     {/*N/A*/-1,/*N/A*/-1,/*N/A*/-1,/*N/A*/-1}, // AM_PM
180     {/*N/A*/-1,/*N/A*/-1,/*N/A*/-1,/*N/A*/-1}, // HOUR
181     {/*N/A*/-1,/*N/A*/-1,/*N/A*/-1,/*N/A*/-1}, // HOUR_OF_DAY
182     {/*N/A*/-1,/*N/A*/-1,/*N/A*/-1,/*N/A*/-1}, // MINUTE
183     {/*N/A*/-1,/*N/A*/-1,/*N/A*/-1,/*N/A*/-1}, // SECOND
184     {/*N/A*/-1,/*N/A*/-1,/*N/A*/-1,/*N/A*/-1}, // MILLISECOND
185     {/*N/A*/-1,/*N/A*/-1,/*N/A*/-1,/*N/A*/-1}, // ZONE_OFFSET
186     {/*N/A*/-1,/*N/A*/-1,/*N/A*/-1,/*N/A*/-1}, // DST_OFFSET
187     { -5000000, -5000000,  5000000,  5000000}, // YEAR_WOY
188     {/*N/A*/-1,/*N/A*/-1,/*N/A*/-1,/*N/A*/-1}, // DOW_LOCAL
189     { -5000000, -5000000,  5000000,  5000000}, // EXTENDED_YEAR
190     {/*N/A*/-1,/*N/A*/-1,/*N/A*/-1,/*N/A*/-1}, // JULIAN_DAY
191     {/*N/A*/-1,/*N/A*/-1,/*N/A*/-1,/*N/A*/-1}, // MILLISECONDS_IN_DAY
192     {        0,        0,        1,        1}, // IS_LEAP_MONTH
193     {        0,        0,       11,       12}, // ORDINAL_MONTH
194 };
195 
196 
197 /**
198 * @draft ICU 2.4
199 */
handleGetLimit(UCalendarDateFields field,ELimitType limitType) const200 int32_t ChineseCalendar::handleGetLimit(UCalendarDateFields field, ELimitType limitType) const {
201     return LIMITS[field][limitType];
202 }
203 
204 
205 //----------------------------------------------------------------------
206 // Calendar framework
207 //----------------------------------------------------------------------
208 
209 /**
210  * Implement abstract Calendar method to return the extended year
211  * defined by the current fields.  This will use either the ERA and
212  * YEAR field as the cycle and year-of-cycle, or the EXTENDED_YEAR
213  * field as the continuous year count, depending on which is newer.
214  * @stable ICU 2.8
215  */
handleGetExtendedYear(UErrorCode & status)216 int32_t ChineseCalendar::handleGetExtendedYear(UErrorCode& status) {
217     if (U_FAILURE(status)) {
218         return 0;
219     }
220 
221     int32_t year;
222     if (newestStamp(UCAL_ERA, UCAL_YEAR, kUnset) <= fStamp[UCAL_EXTENDED_YEAR]) {
223         year = internalGet(UCAL_EXTENDED_YEAR, 1); // Default to year 1
224     } else {
225         // adjust to the instance specific epoch
226         int32_t cycle = internalGet(UCAL_ERA, 1);
227         year = internalGet(UCAL_YEAR, 1);
228         const Setting setting = getSetting(status);
229         if (U_FAILURE(status)) {
230             return 0;
231         }
232         // Handle int32 overflow calculation for
233         // year = year + (cycle-1) * 60 -(fEpochYear - CHINESE_EPOCH_YEAR)
234         if (uprv_add32_overflow(cycle, -1, &cycle) || // 0-based cycle
235             uprv_mul32_overflow(cycle, 60, &cycle) ||
236             uprv_add32_overflow(year, cycle, &year) ||
237             uprv_add32_overflow(year, -(setting.epochYear-CHINESE_EPOCH_YEAR),
238                                 &year)) {
239             status = U_ILLEGAL_ARGUMENT_ERROR;
240             return 0;
241         }
242     }
243     return year;
244 }
245 
246 /**
247  * Override Calendar method to return the number of days in the given
248  * extended year and month.
249  *
250  * <p>Note: This method also reads the IS_LEAP_MONTH field to determine
251  * whether or not the given month is a leap month.
252  * @stable ICU 2.8
253  */
handleGetMonthLength(int32_t extendedYear,int32_t month,UErrorCode & status) const254 int32_t ChineseCalendar::handleGetMonthLength(int32_t extendedYear, int32_t month, UErrorCode& status) const {
255     const Setting setting = getSetting(status);
256     int32_t thisStart = handleComputeMonthStart(extendedYear, month, true, status);
257     if (U_FAILURE(status)) {
258         return 0;
259     }
260     thisStart = thisStart -
261         kEpochStartAsJulianDay + 1; // Julian day -> local days
262     int32_t nextStart = newMoonNear(setting.zoneAstroCalc, thisStart + SYNODIC_GAP, true);
263     return nextStart - thisStart;
264 }
265 
266 /**
267  * Field resolution table that incorporates IS_LEAP_MONTH.
268  */
269 const UFieldResolutionTable ChineseCalendar::CHINESE_DATE_PRECEDENCE[] =
270 {
271     {
272         { UCAL_DAY_OF_MONTH, kResolveSTOP },
273         { UCAL_WEEK_OF_YEAR, UCAL_DAY_OF_WEEK, kResolveSTOP },
274         { UCAL_WEEK_OF_MONTH, UCAL_DAY_OF_WEEK, kResolveSTOP },
275         { UCAL_DAY_OF_WEEK_IN_MONTH, UCAL_DAY_OF_WEEK, kResolveSTOP },
276         { UCAL_WEEK_OF_YEAR, UCAL_DOW_LOCAL, kResolveSTOP },
277         { UCAL_WEEK_OF_MONTH, UCAL_DOW_LOCAL, kResolveSTOP },
278         { UCAL_DAY_OF_WEEK_IN_MONTH, UCAL_DOW_LOCAL, kResolveSTOP },
279         { UCAL_DAY_OF_YEAR, kResolveSTOP },
280         { kResolveRemap | UCAL_DAY_OF_MONTH, UCAL_IS_LEAP_MONTH, kResolveSTOP },
281         { kResolveSTOP }
282     },
283     {
284         { UCAL_WEEK_OF_YEAR, kResolveSTOP },
285         { UCAL_WEEK_OF_MONTH, kResolveSTOP },
286         { UCAL_DAY_OF_WEEK_IN_MONTH, kResolveSTOP },
287         { kResolveRemap | UCAL_DAY_OF_WEEK_IN_MONTH, UCAL_DAY_OF_WEEK, kResolveSTOP },
288         { kResolveRemap | UCAL_DAY_OF_WEEK_IN_MONTH, UCAL_DOW_LOCAL, kResolveSTOP },
289         { kResolveSTOP }
290     },
291     {{kResolveSTOP}}
292 };
293 
294 /**
295  * Override Calendar to add IS_LEAP_MONTH to the field resolution
296  * table.
297  * @stable ICU 2.8
298  */
getFieldResolutionTable() const299 const UFieldResolutionTable* ChineseCalendar::getFieldResolutionTable() const {
300     return CHINESE_DATE_PRECEDENCE;
301 }
302 
303 namespace {
304 
305 struct MonthInfo {
306   int32_t month;
307   int32_t ordinalMonth;
308   int32_t thisMoon;
309   bool isLeapMonth;
310   bool hasLeapMonthBetweenWinterSolstices;
311 };
312 struct MonthInfo computeMonthInfo(
313     const icu::ChineseCalendar::Setting& setting,
314     int32_t gyear, int32_t days);
315 
316 }  // namespace
317 
318 /**
319  * Return the Julian day number of day before the first day of the
320  * given month in the given extended year.
321  *
322  * <p>Note: This method reads the IS_LEAP_MONTH field to determine
323  * whether the given month is a leap month.
324  * @param eyear the extended year
325  * @param month the zero-based month.  The month is also determined
326  * by reading the IS_LEAP_MONTH field.
327  * @return the Julian day number of the day before the first
328  * day of the given month and year
329  * @stable ICU 2.8
330  */
handleComputeMonthStart(int32_t eyear,int32_t month,UBool useMonth,UErrorCode & status) const331 int64_t ChineseCalendar::handleComputeMonthStart(int32_t eyear, int32_t month, UBool useMonth, UErrorCode& status) const {
332     if (U_FAILURE(status)) {
333        return 0;
334     }
335     // If the month is out of range, adjust it into range, and
336     // modify the extended year value accordingly.
337     if (month < 0 || month > 11) {
338         double m = month;
339         if (uprv_add32_overflow(eyear, ClockMath::floorDivide(m, 12.0, &m), &eyear)) {
340             status = U_ILLEGAL_ARGUMENT_ERROR;
341             return 0;
342         }
343         month = (int32_t)m;
344     }
345 
346     const Setting setting = getSetting(status);
347     if (U_FAILURE(status)) {
348        return 0;
349     }
350     int32_t gyear;
351     if (uprv_add32_overflow(eyear, setting.epochYear - 1, &gyear)) {
352         status = U_ILLEGAL_ARGUMENT_ERROR;
353         return 0;
354     }
355 
356     int32_t theNewYear = newYear(setting, gyear);
357     int32_t newMoon = newMoonNear(setting.zoneAstroCalc, theNewYear + month * 29, true);
358 
359     // Ignore IS_LEAP_MONTH field if useMonth is false
360     bool isLeapMonth = false;
361     if (useMonth) {
362         isLeapMonth = internalGet(UCAL_IS_LEAP_MONTH) != 0;
363     }
364 
365     int32_t unusedMonth;
366     int32_t unusedDayOfWeek;
367     int32_t unusedDayOfMonth;
368     int32_t unusedDayOfYear;
369     Grego::dayToFields(newMoon, gyear, unusedMonth, unusedDayOfWeek, unusedDayOfMonth, unusedDayOfYear);
370 
371     struct MonthInfo monthInfo = computeMonthInfo(setting, gyear, newMoon);
372     if (month != monthInfo.month-1 || isLeapMonth != monthInfo.isLeapMonth) {
373         newMoon = newMoonNear(setting.zoneAstroCalc, newMoon + SYNODIC_GAP, true);
374     }
375     int32_t julianDay;
376     if (uprv_add32_overflow(newMoon-1, kEpochStartAsJulianDay, &julianDay)) {
377         status = U_ILLEGAL_ARGUMENT_ERROR;
378         return 0;
379     }
380 
381     return julianDay;
382 }
383 
384 
385 /**
386  * Override Calendar to handle leap months properly.
387  * @stable ICU 2.8
388  */
add(UCalendarDateFields field,int32_t amount,UErrorCode & status)389 void ChineseCalendar::add(UCalendarDateFields field, int32_t amount, UErrorCode& status) {
390     switch (field) {
391     case UCAL_MONTH:
392     case UCAL_ORDINAL_MONTH:
393         if (amount != 0) {
394             int32_t dom = get(UCAL_DAY_OF_MONTH, status);
395             if (U_FAILURE(status)) break;
396             int32_t day = get(UCAL_JULIAN_DAY, status) - kEpochStartAsJulianDay; // Get local day
397             if (U_FAILURE(status)) break;
398             int32_t moon = day - dom + 1; // New moon
399             offsetMonth(moon, dom, amount, status);
400         }
401         break;
402     default:
403         Calendar::add(field, amount, status);
404         break;
405     }
406 }
407 
408 /**
409  * Override Calendar to handle leap months properly.
410  * @stable ICU 2.8
411  */
add(EDateFields field,int32_t amount,UErrorCode & status)412 void ChineseCalendar::add(EDateFields field, int32_t amount, UErrorCode& status) {
413     add((UCalendarDateFields)field, amount, status);
414 }
415 
416 namespace {
417 
418 struct RollMonthInfo {
419     int32_t month;
420     int32_t newMoon;
421     int32_t thisMoon;
422 };
423 
rollMonth(const TimeZone * timeZone,int32_t amount,int32_t day,int32_t month,int32_t dayOfMonth,bool isLeapMonth,bool hasLeapMonthBetweenWinterSolstices,UErrorCode & status)424 struct RollMonthInfo rollMonth(const TimeZone* timeZone, int32_t amount, int32_t day, int32_t month, int32_t dayOfMonth,
425                                bool isLeapMonth, bool hasLeapMonthBetweenWinterSolstices,
426                                UErrorCode& status) {
427     struct RollMonthInfo output = {0, 0, 0};
428     if (U_FAILURE(status)) {
429         return output;
430     }
431 
432     output.thisMoon = day - dayOfMonth + 1; // New moon (start of this month)
433 
434     // Note throughout the following:  Months 12 and 1 are never
435     // followed by a leap month (D&R p. 185).
436 
437     // Compute the adjusted month number m.  This is zero-based
438     // value from 0..11 in a non-leap year, and from 0..12 in a
439     // leap year.
440     if (hasLeapMonthBetweenWinterSolstices) { // (member variable)
441         if (isLeapMonth) {
442             ++month;
443         } else {
444             // Check for a prior leap month.  (In the
445             // following, month 0 is the first month of the
446             // year.)  Month 0 is never followed by a leap
447             // month, and we know month m is not a leap month.
448             // moon1 will be the start of month 0 if there is
449             // no leap month between month 0 and month m;
450             // otherwise it will be the start of month 1.
451             int prevMoon = output.thisMoon -
452                 (int) (CalendarAstronomer::SYNODIC_MONTH * (month - 0.5));
453             prevMoon = newMoonNear(timeZone, prevMoon, true);
454             if (isLeapMonthBetween(timeZone, prevMoon, output.thisMoon)) {
455                 ++month;
456             }
457         }
458     }
459     // Now do the standard roll computation on month, with the
460     // allowed range of 0..n-1, where n is 12 or 13.
461     int32_t numberOfMonths = hasLeapMonthBetweenWinterSolstices ? 13 : 12; // Months in this year
462     if (uprv_add32_overflow(amount, month, &amount)) {
463         status = U_ILLEGAL_ARGUMENT_ERROR;
464         return output;
465     }
466     output.newMoon = amount % numberOfMonths;
467     if (output.newMoon < 0) {
468         output.newMoon += numberOfMonths;
469     }
470     output.month = month;
471     return output;
472 }
473 
474 }  // namespace
475 
476 /**
477  * Override Calendar to handle leap months properly.
478  * @stable ICU 2.8
479  */
roll(UCalendarDateFields field,int32_t amount,UErrorCode & status)480 void ChineseCalendar::roll(UCalendarDateFields field, int32_t amount, UErrorCode& status) {
481     switch (field) {
482     case UCAL_MONTH:
483     case UCAL_ORDINAL_MONTH:
484         if (amount != 0) {
485             const Setting setting = getSetting(status);
486             int32_t day = get(UCAL_JULIAN_DAY, status) - kEpochStartAsJulianDay; // Get local day
487             int32_t month = get(UCAL_MONTH, status); // 0-based month
488             int32_t dayOfMonth = get(UCAL_DAY_OF_MONTH, status);
489             bool isLeapMonth = get(UCAL_IS_LEAP_MONTH, status) == 1;
490             if (U_FAILURE(status)) break;
491             struct RollMonthInfo r = rollMonth(setting.zoneAstroCalc, amount,
492                                                day, month, dayOfMonth, isLeapMonth, hasLeapMonthBetweenWinterSolstices, status);
493             if (U_FAILURE(status)) break;
494             if (r.newMoon != r.month) {
495                 offsetMonth(r.thisMoon, dayOfMonth, r.newMoon - r.month, status);
496             }
497         }
498         break;
499     default:
500         Calendar::roll(field, amount, status);
501         break;
502     }
503 }
504 
roll(EDateFields field,int32_t amount,UErrorCode & status)505 void ChineseCalendar::roll(EDateFields field, int32_t amount, UErrorCode& status) {
506     roll((UCalendarDateFields)field, amount, status);
507 }
508 
509 
510 //------------------------------------------------------------------
511 // Support methods and constants
512 //------------------------------------------------------------------
513 
514 namespace {
515 /**
516  * Convert local days to UTC epoch milliseconds.
517  * This is not an accurate conversion in that getTimezoneOffset
518  * takes the milliseconds in GMT (not local time). In theory, more
519  * accurate algorithm can be implemented but practically we do not need
520  * to go through that complication as long as the historical timezone
521  * changes did not happen around the 'tricky' new moon (new moon around
522  * midnight).
523  *
524  * @param timeZone time zone for the Astro calculation.
525  * @param days days after January 1, 1970 0:00 in the astronomical base zone
526  * @return milliseconds after January 1, 1970 0:00 GMT
527  */
daysToMillis(const TimeZone * timeZone,double days)528 double daysToMillis(const TimeZone* timeZone, double days) {
529     double millis = days * (double)kOneDay;
530     if (timeZone != nullptr) {
531         int32_t rawOffset, dstOffset;
532         UErrorCode status = U_ZERO_ERROR;
533         timeZone->getOffset(millis, false, rawOffset, dstOffset, status);
534         if (U_SUCCESS(status)) {
535             return millis - (double)(rawOffset + dstOffset);
536         }
537     }
538     return millis - (double)CHINA_OFFSET;
539 }
540 
541 /**
542  * Convert UTC epoch milliseconds to local days.
543  * @param timeZone time zone for the Astro calculation.
544  * @param millis milliseconds after January 1, 1970 0:00 GMT
545  * @return days after January 1, 1970 0:00 in the astronomical base zone
546  */
millisToDays(const TimeZone * timeZone,double millis)547 double millisToDays(const TimeZone* timeZone, double millis) {
548     if (timeZone != nullptr) {
549         int32_t rawOffset, dstOffset;
550         UErrorCode status = U_ZERO_ERROR;
551         timeZone->getOffset(millis, false, rawOffset, dstOffset, status);
552         if (U_SUCCESS(status)) {
553             return ClockMath::floorDivide(millis + (double)(rawOffset + dstOffset), kOneDay);
554         }
555     }
556     return ClockMath::floorDivide(millis + (double)CHINA_OFFSET, kOneDay);
557 }
558 
559 //------------------------------------------------------------------
560 // Astronomical computations
561 //------------------------------------------------------------------
562 
563 
564 /**
565  * Return the major solar term on or after December 15 of the given
566  * Gregorian year, that is, the winter solstice of the given year.
567  * Computations are relative to Asia/Shanghai time zone.
568  * @param setting setting (time zone and caches) for the Astro calculation.
569  * @param gyear a Gregorian year
570  * @return days after January 1, 1970 0:00 Asia/Shanghai of the
571  * winter solstice of the given year
572  */
winterSolstice(const icu::ChineseCalendar::Setting & setting,int32_t gyear)573 int32_t winterSolstice(const icu::ChineseCalendar::Setting& setting,
574                        int32_t gyear) {
575     const TimeZone* timeZone = setting.zoneAstroCalc;
576 
577     UErrorCode status = U_ZERO_ERROR;
578     int32_t cacheValue = CalendarCache::get(setting.winterSolsticeCache, gyear, status);
579 
580     if (cacheValue == 0) {
581         // In books December 15 is used, but it fails for some years
582         // using our algorithms, e.g.: 1298 1391 1492 1553 1560.  That
583         // is, winterSolstice(1298) starts search at Dec 14 08:00:00
584         // PST 1298 with a final result of Dec 14 10:31:59 PST 1299.
585         double ms = daysToMillis(timeZone, Grego::fieldsToDay(gyear, UCAL_DECEMBER, 1));
586 
587         // Winter solstice is 270 degrees solar longitude aka Dongzhi
588         double days = millisToDays(timeZone,
589                                    CalendarAstronomer(ms)
590                                        .getSunTime(CalendarAstronomer::WINTER_SOLSTICE(), true));
591         if (days < INT32_MIN || days > INT32_MAX) {
592             status = U_ILLEGAL_ARGUMENT_ERROR;
593             return 0;
594         }
595         cacheValue = (int32_t) days;
596         CalendarCache::put(setting.winterSolsticeCache, gyear, cacheValue, status);
597     }
598     if(U_FAILURE(status)) {
599         cacheValue = 0;
600     }
601     return cacheValue;
602 }
603 
604 /**
605  * Return the closest new moon to the given date, searching either
606  * forward or backward in time.
607  * @param timeZone time zone for the Astro calculation.
608  * @param days days after January 1, 1970 0:00 Asia/Shanghai
609  * @param after if true, search for a new moon on or after the given
610  * date; otherwise, search for a new moon before it
611  * @return days after January 1, 1970 0:00 Asia/Shanghai of the nearest
612  * new moon after or before <code>days</code>
613  */
newMoonNear(const TimeZone * timeZone,double days,UBool after)614 int32_t newMoonNear(const TimeZone* timeZone, double days, UBool after) {
615     return (int32_t) millisToDays(
616         timeZone,
617         CalendarAstronomer(daysToMillis(timeZone, days))
618               .getMoonTime(CalendarAstronomer::NEW_MOON(), after));
619 }
620 
621 /**
622  * Return the nearest integer number of synodic months between
623  * two dates.
624  * @param day1 days after January 1, 1970 0:00 Asia/Shanghai
625  * @param day2 days after January 1, 1970 0:00 Asia/Shanghai
626  * @return the nearest integer number of months between day1 and day2
627  */
synodicMonthsBetween(int32_t day1,int32_t day2)628 int32_t synodicMonthsBetween(int32_t day1, int32_t day2) {
629     double roundme = ((day2 - day1) / CalendarAstronomer::SYNODIC_MONTH);
630     return (int32_t) (roundme + (roundme >= 0 ? .5 : -.5));
631 }
632 
633 /**
634  * Return the major solar term on or before a given date.  This
635  * will be an integer from 1..12, with 1 corresponding to 330 degrees,
636  * 2 to 0 degrees, 3 to 30 degrees,..., and 12 to 300 degrees.
637  * @param timeZone time zone for the Astro calculation.
638  * @param days days after January 1, 1970 0:00 Asia/Shanghai
639  */
majorSolarTerm(const TimeZone * timeZone,int32_t days)640 int32_t majorSolarTerm(const TimeZone* timeZone, int32_t days) {
641     // Compute (floor(solarLongitude / (pi/6)) + 2) % 12
642     int32_t term = ( ((int32_t)(6 * CalendarAstronomer(daysToMillis(timeZone, days))
643                                 .getSunLongitude() / CalendarAstronomer::PI)) + 2 ) % 12;
644     if (term < 1) {
645         term += 12;
646     }
647     return term;
648 }
649 
650 /**
651  * Return true if the given month lacks a major solar term.
652  * @param timeZone time zone for the Astro calculation.
653  * @param newMoon days after January 1, 1970 0:00 Asia/Shanghai of a new
654  * moon
655  */
hasNoMajorSolarTerm(const TimeZone * timeZone,int32_t newMoon)656 UBool hasNoMajorSolarTerm(const TimeZone* timeZone, int32_t newMoon) {
657     return majorSolarTerm(timeZone, newMoon) ==
658         majorSolarTerm(timeZone, newMoonNear(timeZone, newMoon + SYNODIC_GAP, true));
659 }
660 
661 
662 //------------------------------------------------------------------
663 // Time to fields
664 //------------------------------------------------------------------
665 
666 /**
667  * Return true if there is a leap month on or after month newMoon1 and
668  * at or before month newMoon2.
669  * @param timeZone time zone for the Astro calculation.
670  * @param newMoon1 days after January 1, 1970 0:00 astronomical base zone
671  * of a new moon
672  * @param newMoon2 days after January 1, 1970 0:00 astronomical base zone
673  * of a new moon
674  */
isLeapMonthBetween(const TimeZone * timeZone,int32_t newMoon1,int32_t newMoon2)675 UBool isLeapMonthBetween(const TimeZone* timeZone, int32_t newMoon1, int32_t newMoon2) {
676 
677 #ifdef U_DEBUG_CHNSECAL
678     // This is only needed to debug the timeOfAngle divergence bug.
679     // Remove this later. Liu 11/9/00
680     if (synodicMonthsBetween(newMoon1, newMoon2) >= 50) {
681         U_DEBUG_CHNSECAL_MSG((
682             "isLeapMonthBetween(%d, %d): Invalid parameters", newMoon1, newMoon2
683             ));
684     }
685 #endif
686 
687     while (newMoon2 >= newMoon1) {
688         if (hasNoMajorSolarTerm(timeZone, newMoon2)) {
689             return true;
690         }
691         newMoon2 = newMoonNear(timeZone, newMoon2 - SYNODIC_GAP, false);
692     }
693     return false;
694 }
695 
696 
697 /**
698  * Compute the information about the year.
699  * @param setting setting (time zone and caches) for the Astro calculation.
700  * @param gyear the Gregorian year of the given date
701  * @param days days after January 1, 1970 0:00 astronomical base zone
702  * of the date to compute fields for
703  * @return The MonthInfo result.
704  */
computeMonthInfo(const icu::ChineseCalendar::Setting & setting,int32_t gyear,int32_t days)705 struct MonthInfo computeMonthInfo(
706     const icu::ChineseCalendar::Setting& setting,
707     int32_t gyear, int32_t days) {
708     struct MonthInfo output;
709     // Find the winter solstices before and after the target date.
710     // These define the boundaries of this Chinese year, specifically,
711     // the position of month 11, which always contains the solstice.
712     // We want solsticeBefore <= date < solsticeAfter.
713     int32_t solsticeBefore;
714     int32_t solsticeAfter = winterSolstice(setting, gyear);
715     if (days < solsticeAfter) {
716         solsticeBefore = winterSolstice(setting, gyear - 1);
717     } else {
718         solsticeBefore = solsticeAfter;
719         solsticeAfter = winterSolstice(setting, gyear + 1);
720     }
721 
722     const TimeZone* timeZone = setting.zoneAstroCalc;
723     // Find the start of the month after month 11.  This will be either
724     // the prior month 12 or leap month 11 (very rare).  Also find the
725     // start of the following month 11.
726     int32_t firstMoon = newMoonNear(timeZone, solsticeBefore + 1, true);
727     int32_t lastMoon = newMoonNear(timeZone, solsticeAfter + 1, false);
728     output.thisMoon = newMoonNear(timeZone, days + 1, false); // Start of this month
729     output.hasLeapMonthBetweenWinterSolstices = synodicMonthsBetween(firstMoon, lastMoon) == 12;
730 
731     output.month = synodicMonthsBetween(firstMoon, output.thisMoon);
732     int32_t theNewYear = newYear(setting, gyear);
733     if (days < theNewYear) {
734         theNewYear = newYear(setting, gyear-1);
735     }
736     if (output.hasLeapMonthBetweenWinterSolstices &&
737         isLeapMonthBetween(timeZone, firstMoon, output.thisMoon)) {
738         output.month--;
739     }
740     if (output.month < 1) {
741         output.month += 12;
742     }
743     output.ordinalMonth = synodicMonthsBetween(theNewYear, output.thisMoon);
744     if (output.ordinalMonth < 0) {
745         output.ordinalMonth += 12;
746     }
747     output.isLeapMonth = output.hasLeapMonthBetweenWinterSolstices &&
748         hasNoMajorSolarTerm(timeZone, output.thisMoon) &&
749         !isLeapMonthBetween(timeZone, firstMoon,
750                             newMoonNear(timeZone, output.thisMoon - SYNODIC_GAP, false));
751     return output;
752 }
753 
754 }  // namespace
755 
756 /**
757  * Override Calendar to compute several fields specific to the Chinese
758  * calendar system.  These are:
759  *
760  * <ul><li>ERA
761  * <li>YEAR
762  * <li>MONTH
763  * <li>DAY_OF_MONTH
764  * <li>DAY_OF_YEAR
765  * <li>EXTENDED_YEAR</ul>
766  *
767  * The DAY_OF_WEEK and DOW_LOCAL fields are already set when this
768  * method is called.  The getGregorianXxx() methods return Gregorian
769  * calendar equivalents for the given Julian day.
770  *
771  * <p>Compute the ChineseCalendar-specific field IS_LEAP_MONTH.
772  * @stable ICU 2.8
773  */
handleComputeFields(int32_t julianDay,UErrorCode & status)774 void ChineseCalendar::handleComputeFields(int32_t julianDay, UErrorCode & status) {
775     if (U_FAILURE(status)) {
776         return;
777     }
778     int32_t days;
779     if (uprv_add32_overflow(julianDay, -kEpochStartAsJulianDay, &days)) {
780         status = U_ILLEGAL_ARGUMENT_ERROR;
781         return;
782     }
783     int32_t gyear = getGregorianYear();
784     int32_t gmonth = getGregorianMonth();
785 
786     const Setting setting = getSetting(status);
787     if (U_FAILURE(status)) {
788        return;
789     }
790     struct MonthInfo monthInfo = computeMonthInfo(setting, gyear, days);
791     hasLeapMonthBetweenWinterSolstices = monthInfo.hasLeapMonthBetweenWinterSolstices;
792 
793     // Extended year and cycle year is based on the epoch year
794     int32_t eyear = gyear - setting.epochYear;
795     int32_t cycle_year = gyear - CHINESE_EPOCH_YEAR;
796     if (monthInfo.month < 11 ||
797         gmonth >= UCAL_JULY) {
798         eyear++;
799         cycle_year++;
800     }
801     int32_t dayOfMonth = days - monthInfo.thisMoon + 1;
802 
803     // 0->0,60  1->1,1  60->1,60  61->2,1  etc.
804     int32_t yearOfCycle;
805     int32_t cycle = ClockMath::floorDivide(cycle_year - 1, 60, &yearOfCycle);
806 
807     // Days will be before the first new year we compute if this
808     // date is in month 11, leap 11, 12.  There is never a leap 12.
809     // New year computations are cached so this should be cheap in
810     // the long run.
811     int32_t theNewYear = newYear(setting, gyear);
812     if (days < theNewYear) {
813         theNewYear = newYear(setting, gyear-1);
814     }
815     cycle++;
816     yearOfCycle++;
817     int32_t dayOfYear = days - theNewYear + 1;
818 
819     int32_t minYear = this->handleGetLimit(UCAL_EXTENDED_YEAR, UCAL_LIMIT_MINIMUM);
820     if (eyear < minYear) {
821         if (!isLenient()) {
822             status = U_ILLEGAL_ARGUMENT_ERROR;
823             return;
824         }
825         eyear = minYear;
826     }
827     int32_t maxYear = this->handleGetLimit(UCAL_EXTENDED_YEAR, UCAL_LIMIT_MAXIMUM);
828     if (maxYear < eyear) {
829         if (!isLenient()) {
830             status = U_ILLEGAL_ARGUMENT_ERROR;
831             return;
832         }
833         eyear = maxYear;
834     }
835 
836     internalSet(UCAL_MONTH, monthInfo.month-1); // Convert from 1-based to 0-based
837     internalSet(UCAL_ORDINAL_MONTH, monthInfo.ordinalMonth); // Convert from 1-based to 0-based
838     internalSet(UCAL_IS_LEAP_MONTH, monthInfo.isLeapMonth?1:0);
839 
840     internalSet(UCAL_EXTENDED_YEAR, eyear);
841     internalSet(UCAL_ERA, cycle);
842     internalSet(UCAL_YEAR, yearOfCycle);
843     internalSet(UCAL_DAY_OF_MONTH, dayOfMonth);
844     internalSet(UCAL_DAY_OF_YEAR, dayOfYear);
845 }
846 
847 //------------------------------------------------------------------
848 // Fields to time
849 //------------------------------------------------------------------
850 
851 namespace {
852 
853 /**
854  * Return the Chinese new year of the given Gregorian year.
855  * @param setting setting (time zone and caches) for the Astro calculation.
856  * @param gyear a Gregorian year
857  * @return days after January 1, 1970 0:00 astronomical base zone of the
858  * Chinese new year of the given year (this will be a new moon)
859  */
newYear(const icu::ChineseCalendar::Setting & setting,int32_t gyear)860 int32_t newYear(const icu::ChineseCalendar::Setting& setting,
861                 int32_t gyear) {
862     const TimeZone* timeZone = setting.zoneAstroCalc;
863     UErrorCode status = U_ZERO_ERROR;
864     int32_t cacheValue = CalendarCache::get(setting.newYearCache, gyear, status);
865 
866     if (cacheValue == 0) {
867 
868         int32_t solsticeBefore= winterSolstice(setting, gyear - 1);
869         int32_t solsticeAfter = winterSolstice(setting, gyear);
870         int32_t newMoon1 = newMoonNear(timeZone, solsticeBefore + 1, true);
871         int32_t newMoon2 = newMoonNear(timeZone, newMoon1 + SYNODIC_GAP, true);
872         int32_t newMoon11 = newMoonNear(timeZone, solsticeAfter + 1, false);
873 
874         if (synodicMonthsBetween(newMoon1, newMoon11) == 12 &&
875             (hasNoMajorSolarTerm(timeZone, newMoon1) ||
876              hasNoMajorSolarTerm(timeZone, newMoon2))) {
877             cacheValue = newMoonNear(timeZone, newMoon2 + SYNODIC_GAP, true);
878         } else {
879             cacheValue = newMoon2;
880         }
881 
882         CalendarCache::put(setting.newYearCache, gyear, cacheValue, status);
883     }
884     if(U_FAILURE(status)) {
885         cacheValue = 0;
886     }
887     return cacheValue;
888 }
889 
890 }  // namespace
891 
892 /**
893  * Adjust this calendar to be delta months before or after a given
894  * start position, pinning the day of month if necessary.  The start
895  * position is given as a local days number for the start of the month
896  * and a day-of-month.  Used by add() and roll().
897  * @param newMoon the local days of the first day of the month of the
898  * start position (days after January 1, 1970 0:00 Asia/Shanghai)
899  * @param dayOfMonth the 1-based day-of-month of the start position
900  * @param delta the number of months to move forward or backward from
901  * the start position
902  * @param status The status.
903  */
offsetMonth(int32_t newMoon,int32_t dayOfMonth,int32_t delta,UErrorCode & status)904 void ChineseCalendar::offsetMonth(int32_t newMoon, int32_t dayOfMonth, int32_t delta,
905                                   UErrorCode& status) {
906     const Setting setting = getSetting(status);
907     if (U_FAILURE(status)) { return; }
908 
909     // Move to the middle of the month before our target month.
910     double value = newMoon;
911     value += (CalendarAstronomer::SYNODIC_MONTH *
912                           (static_cast<double>(delta) - 0.5));
913     if (value < INT32_MIN || value > INT32_MAX) {
914         status = U_ILLEGAL_ARGUMENT_ERROR;
915         return;
916     }
917     newMoon = static_cast<int32_t>(value);
918 
919     // Search forward to the target month's new moon
920     newMoon = newMoonNear(setting.zoneAstroCalc, newMoon, true);
921 
922     // Find the target dayOfMonth
923     int32_t jd = newMoon + kEpochStartAsJulianDay - 1 + dayOfMonth;
924 
925     // Pin the dayOfMonth.  In this calendar all months are 29 or 30 days
926     // so pinning just means handling dayOfMonth 30.
927     if (dayOfMonth > 29) {
928         set(UCAL_JULIAN_DAY, jd-1);
929         // TODO Fix this.  We really shouldn't ever have to
930         // explicitly call complete().  This is either a bug in
931         // this method, in ChineseCalendar, or in
932         // Calendar.getActualMaximum().  I suspect the last.
933         complete(status);
934         if (U_FAILURE(status)) return;
935         if (getActualMaximum(UCAL_DAY_OF_MONTH, status) >= dayOfMonth) {
936             if (U_FAILURE(status)) return;
937             set(UCAL_JULIAN_DAY, jd);
938         }
939     } else {
940         set(UCAL_JULIAN_DAY, jd);
941     }
942 }
943 
944 constexpr uint32_t kChineseRelatedYearDiff = -2637;
945 
getRelatedYear(UErrorCode & status) const946 int32_t ChineseCalendar::getRelatedYear(UErrorCode &status) const
947 {
948     int32_t year = get(UCAL_EXTENDED_YEAR, status);
949     if (U_FAILURE(status)) {
950         return 0;
951     }
952     if (uprv_add32_overflow(year, kChineseRelatedYearDiff, &year)) {
953         status = U_ILLEGAL_ARGUMENT_ERROR;
954         return 0;
955     }
956     return year;
957 }
958 
setRelatedYear(int32_t year)959 void ChineseCalendar::setRelatedYear(int32_t year)
960 {
961     // set extended year
962     set(UCAL_EXTENDED_YEAR, year - kChineseRelatedYearDiff);
963 }
964 
965 IMPL_SYSTEM_DEFAULT_CENTURY(ChineseCalendar, "@calendar=chinese")
966 
967 bool
inTemporalLeapYear(UErrorCode & status) const968 ChineseCalendar::inTemporalLeapYear(UErrorCode &status) const
969 {
970     int32_t days = getActualMaximum(UCAL_DAY_OF_YEAR, status);
971     if (U_FAILURE(status)) return false;
972     return days > 360;
973 }
974 
975 UOBJECT_DEFINE_RTTI_IMPLEMENTATION(ChineseCalendar)
976 
977 
978 static const char * const gTemporalLeapMonthCodes[] = {
979     "M01L", "M02L", "M03L", "M04L", "M05L", "M06L",
980     "M07L", "M08L", "M09L", "M10L", "M11L", "M12L", nullptr
981 };
982 
getTemporalMonthCode(UErrorCode & status) const983 const char* ChineseCalendar::getTemporalMonthCode(UErrorCode &status) const {
984     // We need to call get, not internalGet, to force the calculation
985     // from UCAL_ORDINAL_MONTH.
986     int32_t is_leap = get(UCAL_IS_LEAP_MONTH, status);
987     if (U_FAILURE(status)) return nullptr;
988     if (is_leap != 0) {
989         int32_t month = get(UCAL_MONTH, status);
990         if (U_FAILURE(status)) return nullptr;
991         return gTemporalLeapMonthCodes[month];
992     }
993     return Calendar::getTemporalMonthCode(status);
994 }
995 
996 void
setTemporalMonthCode(const char * code,UErrorCode & status)997 ChineseCalendar::setTemporalMonthCode(const char* code, UErrorCode& status )
998 {
999     if (U_FAILURE(status)) return;
1000     int32_t len = static_cast<int32_t>(uprv_strlen(code));
1001     if (len != 4 || code[0] != 'M' || code[3] != 'L') {
1002         set(UCAL_IS_LEAP_MONTH, 0);
1003         return Calendar::setTemporalMonthCode(code, status);
1004     }
1005     for (int m = 0; gTemporalLeapMonthCodes[m] != nullptr; m++) {
1006         if (uprv_strcmp(code, gTemporalLeapMonthCodes[m]) == 0) {
1007             set(UCAL_MONTH, m);
1008             set(UCAL_IS_LEAP_MONTH, 1);
1009             return;
1010         }
1011     }
1012     status = U_ILLEGAL_ARGUMENT_ERROR;
1013 }
1014 
internalGetMonth(UErrorCode & status) const1015 int32_t ChineseCalendar::internalGetMonth(UErrorCode& status) const {
1016     if (U_FAILURE(status)) {
1017         return 0;
1018     }
1019     if (resolveFields(kMonthPrecedence) == UCAL_MONTH) {
1020         return internalGet(UCAL_MONTH);
1021     }
1022     LocalPointer<Calendar> temp(this->clone());
1023     temp->set(UCAL_MONTH, 0);
1024     temp->set(UCAL_IS_LEAP_MONTH, 0);
1025     temp->set(UCAL_DATE, 1);
1026     // Calculate the UCAL_MONTH and UCAL_IS_LEAP_MONTH by adding number of
1027     // months.
1028     temp->roll(UCAL_MONTH, internalGet(UCAL_ORDINAL_MONTH), status);
1029     if (U_FAILURE(status)) {
1030         return 0;
1031     }
1032 
1033     ChineseCalendar *nonConstThis = (ChineseCalendar*)this; // cast away const
1034     nonConstThis->internalSet(UCAL_IS_LEAP_MONTH, temp->get(UCAL_IS_LEAP_MONTH, status));
1035     int32_t month = temp->get(UCAL_MONTH, status);
1036     if (U_FAILURE(status)) {
1037         return 0;
1038     }
1039     nonConstThis->internalSet(UCAL_MONTH, month);
1040     return month;
1041 }
1042 
internalGetMonth(int32_t defaultValue,UErrorCode & status) const1043 int32_t ChineseCalendar::internalGetMonth(int32_t defaultValue, UErrorCode& status) const {
1044     if (U_FAILURE(status)) {
1045         return 0;
1046     }
1047     if (resolveFields(kMonthPrecedence) == UCAL_MONTH) {
1048         return internalGet(UCAL_MONTH, defaultValue);
1049     }
1050     return internalGetMonth(status);
1051 }
1052 
getSetting(UErrorCode &) const1053 ChineseCalendar::Setting ChineseCalendar::getSetting(UErrorCode&) const {
1054   return {
1055         CHINESE_EPOCH_YEAR,
1056         getAstronomerTimeZone(),
1057         &gWinterSolsticeCache,
1058         &gNewYearCache
1059   };
1060 }
1061 
1062 U_NAMESPACE_END
1063 
1064 #endif
1065 
1066