| 1 |
/* This Source Code Form is subject to the terms of the Mozilla Public |
| 2 |
* License, v. 2.0. If a copy of the MPL was not distributed with this |
| 3 |
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */ |
| 4 |
|
| 5 |
#include "mozilla/Assertions.h" |
| 6 |
#include "mozilla/intl/calendar/ISODate.h" |
| 7 |
|
| 8 |
#include <array> |
| 9 |
#include <stddef.h> |
| 10 |
#include <stdint.h> |
| 11 |
|
| 12 |
namespace mozilla::intl::calendar { |
| 13 |
|
| 14 |
// Copied from js/src/builtin/temporal/Calendar.cpp |
| 15 |
|
| 16 |
static int32_t DayFromYear(int32_t year) { |
| 17 |
return 365 * (year - 1970) + FloorDiv(year - 1969, 4) - |
| 18 |
FloorDiv(year - 1901, 100) + FloorDiv(year - 1601, 400); |
| 19 |
} |
| 20 |
|
| 21 |
static constexpr bool IsISOLeapYear(int32_t year) { |
| 22 |
return (year % 4 == 0) && ((year % 100 != 0) || (year % 400 == 0)); |
| 23 |
} |
| 24 |
|
| 25 |
static constexpr int32_t ISODaysInMonth(int32_t year, int32_t month) { |
| 26 |
MOZ_ASSERT(1 <= month && month <= 12); |
| 27 |
|
| 28 |
constexpr uint8_t daysInMonth[2][13] = { |
| 29 |
{0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}, |
| 30 |
{0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}}; |
| 31 |
|
| 32 |
return daysInMonth[IsISOLeapYear(year)][month]; |
| 33 |
} |
| 34 |
|
| 35 |
static constexpr auto FirstDayOfMonth(int32_t year) { |
| 36 |
// The following array contains the day of year for the first day of each |
| 37 |
// month, where index 0 is January, and day 0 is January 1. |
| 38 |
std::array<int32_t, 13> days = {}; |
| 39 |
for (int32_t month = 1; month <= 12; ++month) { |
| 40 |
days[month] = days[month - 1] + ISODaysInMonth(year, month); |
| 41 |
} |
| 42 |
return days; |
| 43 |
} |
| 44 |
|
| 45 |
static int32_t ISODayOfYear(const ISODate& isoDate) { |
| 46 |
const auto& [year, month, day] = isoDate; |
| 47 |
|
| 48 |
// First day of month arrays for non-leap and leap years. |
| 49 |
constexpr decltype(FirstDayOfMonth(0)) firstDayOfMonth[2] = { |
| 50 |
FirstDayOfMonth(1), FirstDayOfMonth(0)}; |
| 51 |
|
| 52 |
return firstDayOfMonth[IsISOLeapYear(year)][month - 1] + day; |
| 53 |
} |
| 54 |
|
| 55 |
int32_t MakeDay(const ISODate& date) { |
| 56 |
return DayFromYear(date.year) + ISODayOfYear(date) - 1; |
| 57 |
} |
| 58 |
|
| 59 |
} // namespace mozilla::intl::calendar |