MonthCode.h (2016B)
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 #ifndef intl_components_calendar_MonthCode_h_ 5 #define intl_components_calendar_MonthCode_h_ 6 7 #include <stddef.h> 8 #include <stdint.h> 9 #include <string_view> 10 11 namespace mozilla::intl::calendar { 12 13 // Copied from js/src/builtin/temporal/MonthCode.h 14 15 class MonthCode final { 16 public: 17 enum class Code { 18 Invalid = 0, 19 20 // Months 01 - M12. 21 M01 = 1, 22 M02, 23 M03, 24 M04, 25 M05, 26 M06, 27 M07, 28 M08, 29 M09, 30 M10, 31 M11, 32 M12, 33 34 // Epagomenal month M13. 35 M13, 36 37 // Leap months M01 - M12. 38 M01L, 39 M02L, 40 M03L, 41 M04L, 42 M05L, 43 M06L, 44 M07L, 45 M08L, 46 M09L, 47 M10L, 48 M11L, 49 M12L, 50 }; 51 52 private: 53 static constexpr int32_t toLeapMonth = 54 static_cast<int32_t>(Code::M01L) - static_cast<int32_t>(Code::M01); 55 56 Code code_ = Code::Invalid; 57 58 public: 59 constexpr MonthCode() = default; 60 61 constexpr explicit MonthCode(Code code) : code_(code) {} 62 63 constexpr explicit MonthCode(int32_t month, bool isLeapMonth = false) { 64 code_ = static_cast<Code>(month + (isLeapMonth ? toLeapMonth : 0)); 65 } 66 67 constexpr auto code() const { return code_; } 68 69 constexpr int32_t ordinal() const { 70 int32_t ordinal = static_cast<int32_t>(code_); 71 if (isLeapMonth()) { 72 ordinal -= toLeapMonth; 73 } 74 return ordinal; 75 } 76 77 constexpr bool isLeapMonth() const { return code_ >= Code::M01L; } 78 79 constexpr explicit operator std::string_view() const { 80 constexpr const char* name = 81 "M01L" 82 "M02L" 83 "M03L" 84 "M04L" 85 "M05L" 86 "M06L" 87 "M07L" 88 "M08L" 89 "M09L" 90 "M10L" 91 "M11L" 92 "M12L" 93 "M13"; 94 size_t index = (ordinal() - 1) * 4; 95 size_t length = 3 + isLeapMonth(); 96 return {name + index, length}; 97 } 98 }; 99 100 } // namespace mozilla::intl::calendar 101 102 #endif