Debian Codegraph @

debian/rust-vendor/icu_calendar/src/cal/japanese.rs

raw
1 // This file is part of ICU4X. For terms of use, please see the file
2 // called LICENSE at the top level of the ICU4X source tree
3 // (online at: https://github.com/unicode-org/icu4x/blob/main/LICENSE ).
4
5 use crate::cal::abstract_gregorian::{
6 AbstractGregorian, GregorianYears, impl_with_abstract_gregorian,
7 };
8 use crate::cal::gregorian::CeBce;
9 use crate::calendar_arithmetic::ArithmeticDate;
10 use crate::error::{DateError, UnknownEraError};
11 use crate::provider::{CalendarJapaneseModernV1, EraStartDate, JapaneseEras};
12 use crate::{AsCalendar, Date, types};
13 use icu_provider::prelude::*;
14
15 /// The [Japanese Calendar] (with modern eras only)
16 ///
17 /// The [Japanese Calendar] is a variant of the [`Gregorian`](crate::cal::Gregorian) calendar
18 /// created by the Japanese government. It is identical to the Gregorian calendar except that
19 /// is uses Japanese eras instead of the Common Era.
20 ///
21 /// This implementation extends proleptically for dates before the calendar's creation
22 /// in 6 Meiji (1873 CE). Gregorian eras are used before that.
23 ///
24 /// This corresponds to the `"japanese"` [CLDR calendar](https://unicode.org/reports/tr35/#UnicodeCalendarIdentifier).
25 ///
26 /// [Japanese calendar]: https://en.wikipedia.org/wiki/Japanese_calendar
27 ///
28 /// # Era codes
29 ///
30 /// This calendar currently supports seven era codes. It supports the five eras since its
31 /// introduction (`meiji`, `taisho`, `showa`, `heisei`, `reiwa`), as well as the Gregorian
32 /// `bce` (alias `bc`), and `ce` (alias `ad`) for earlier dates.
33 ///
34 /// Future eras will also be added to this type when they are decided.
35 ///
36 /// These eras are loaded from data, requiring a data provider capable of providing [`CalendarJapaneseModernV1`]
37 /// data.
38 #[derive(Clone, Debug, Default, Copy)]
39 pub struct Japanese(JapaneseEras);
40
41 impl Japanese {
42 /// Creates a new [`Japanese`] using only modern eras (post-meiji) from compiled data.
43 ///
44 /// ✨ *Enabled with the `compiled_data` Cargo feature.*
45 ///
46 /// [📚 Help choosing a constructor](icu_provider::constructors)
47 #[cfg(feature = "compiled_data")]
48 pub const fn new() -> Self {
49 const { Self(*crate::provider::Baked::SINGLETON_CALENDAR_JAPANESE_MODERN_V1) }
50 }
51
52 icu_provider::gen_buffer_data_constructors!(() -> error: DataError,
53 functions: [
54 new: skip,
55 try_new_with_buffer_provider,
56 try_new_unstable,
57 Self,
58 ]);
59
60 #[doc = icu_provider::gen_buffer_unstable_docs!(UNSTABLE, Self::new)]
61 pub fn try_new_unstable<D: DataProvider<CalendarJapaneseModernV1> + ?Sized>(
62 provider: &D,
63 ) -> Result<Self, DataError> {
64 Ok(Self(*provider.load(Default::default())?.payload.get()))
65 }
66 }
67
68 impl GregorianYears for Japanese {
69 fn extended_from_era_year(
70 &self,
71 era: Option<&[u8]>,
72 year: i32,
73 ) -> Result<i32, UnknownEraError> {
74 if let Ok(g) = CeBce.extended_from_era_year(era, year) {
75 return Ok(g);
76 }
77
78 let (start, ..) = self
79 .0
80 .eras()
81 .rfind(|(_, name, _)| era == Some(name.as_bytes()))
82 .ok_or(UnknownEraError)?;
83
84 Ok(year - 1 + start.year)
85 }
86
87 fn era_year_from_extended(&self, year: i32, month: u8, day: u8) -> types::EraYear {
88 let date: EraStartDate = EraStartDate { year, month, day };
89
90 let ret =
91 if let Some((start, code, idx)) = self.0.eras().rfind(|&(start, ..)| date >= start) {
92 types::EraYear {
93 era: code.resize(),
94 era_index: Some(idx),
95 year: year - start.year + 1,
96 extended_year: year,
97 ambiguity: types::YearAmbiguity::CenturyRequired,
98 }
99 } else {
100 CeBce.era_year_from_extended(year, month, day)
101 };
102
103 // Special case: Meiji 1 to 5 are treated as CE.
104 //
105 // This calendar was adopted in Meiji 6 (1873), but Meiji started
106 // on 1868-10-23, so for Meiji 1 - 5 the lunisolar calendar was still
107 // in use. In order to not produce incorrect pre-Meiji 6
108 // dates, we force the Gregorian calendar there.
109 //
110 // https://tc39.es/proposal-intl-era-monthcode/#table-calendar-types
111 // https://github.com/tc39/proposal-intl-era-monthcode/issues/86
112 if ret.era == "meiji" && ret.year < 6 {
113 return CeBce.era_year_from_extended(year, month, day);
114 }
115
116 ret
117 }
118
119 fn debug_name(&self) -> &'static str {
120 "Japanese"
121 }
122
123 fn calendar_algorithm(&self) -> Option<crate::preferences::CalendarAlgorithm> {
124 Some(crate::preferences::CalendarAlgorithm::Japanese)
125 }
126 }
127
128 impl_with_abstract_gregorian!(Japanese, JapaneseDateInner, Japanese, this, *this);
129
130 impl Date<Japanese> {
131 /// Construct a new Japanese [`Date`].
132 ///
133 /// Years are specified in the era provided, and must be in range for Japanese
134 /// eras (e.g. dates past April 30 Heisei 31 must be in Reiwa; "Jun 5 Heisei 31" and "Jan 1 Heisei 32"
135 /// will not be adjusted to being in Reiwa 1 and 2 respectively)
136 ///
137 /// However, dates may always be specified in "bce" or "ce" and they will be adjusted as necessary.
138 ///
139 /// This function accepts years in the range `-9999..=9999`, where the Gregorian year
140 /// is also in the range `-9999..=9999`.
141 ///
142 /// ```rust
143 /// use icu::calendar::cal::Japanese;
144 /// use icu::calendar::{Date, Ref};
145 /// use tinystr::tinystr;
146 ///
147 /// let era = "heisei";
148 ///
149 /// let date =
150 /// Date::try_new_japanese_with_calendar(era, 14, 1, 2, Japanese::new())
151 /// .expect("Constructing a date should succeed");
152 ///
153 /// assert_eq!(date.era_year().era, era);
154 /// assert_eq!(date.era_year().year, 14);
155 /// assert_eq!(date.month().ordinal, 1);
156 /// assert_eq!(date.day_of_month().0, 2);
157 ///
158 /// // This function will error for unknown eras
159 /// let fake_era = "neko"; // 🐱
160 /// let fake_date = Date::try_new_japanese_with_calendar(
161 /// fake_era,
162 /// 10,
163 /// 1,
164 /// 2,
165 /// Japanese::new(),
166 /// );
167 /// assert!(fake_date.is_err());
168 /// ```
169 pub fn try_new_japanese_with_calendar<A: AsCalendar<Calendar = Japanese>>(
170 era: &str,
171 year: i32,
172 month: u8,
173 day: u8,
174 japanese_calendar: A,
175 ) -> Result<Date<A>, DateError> {
176 ArithmeticDate::from_era_year_month_day(
177 era,
178 year,
179 month,
180 day,
181 &AbstractGregorian(*japanese_calendar.as_calendar()),
182 )
183 .map(ArithmeticDate::cast)
184 .map(JapaneseDateInner)
185 .map(|i| Date::from_raw(i, japanese_calendar))
186 }
187 }
188
189 impl Date<Japanese> {
190 /// Use [`Self::try_new_japanese_with_calendar`]
191 #[deprecated(since = "2.2.0", note = "use `try_new_japanese_with_calendar`")]
192 pub fn try_new_japanese_extended_with_calendar<A: AsCalendar<Calendar = Japanese>>(
193 era: &str,
194 year: i32,
195 month: u8,
196 day: u8,
197 japanese_calendar: A,
198 ) -> Result<Date<A>, DateError> {
199 Self::try_new_japanese_with_calendar(era, year, month, day, japanese_calendar)
200 }
201 }
202
203 #[cfg(test)]
204 mod tests {
205 use super::*;
206 use tinystr::tinystr;
207
208 const CALENDAR: Japanese = Japanese(
209 JapaneseEras::with_last_era(
210 EraStartDate {
211 year: 2086,
212 month: 11,
213 day: 1,
214 },
215 tinystr!(8, "fuzu"),
216 8,
217 )
218 .unwrap(),
219 );
220
221 fn single_test_roundtrip(era: &str, year: i32, month: u8, day: u8) {
222 let date = Date::try_new_japanese_with_calendar(era, year, month, day, CALENDAR)
223 .unwrap_or_else(|e| {
224 panic!("Failed to construct date with {era:?}, {year}, {month}, {day}: {e:?}")
225 });
226 let reconstructed = Date::from_rata_die(date.to_rata_die(), CALENDAR);
227 assert_eq!(
228 date, reconstructed,
229 "Failed to roundtrip with {era:?}, {year}, {month}, {day}"
230 );
231
232 // Extra coverage for https://github.com/unicode-org/icu4x/issues/4968
233 assert_eq!(reconstructed.era_year().era, era);
234 assert_eq!(reconstructed.era_year().year, year);
235 }
236
237 // test that out-of-range era values convert to other eras
238 fn single_test_era_range_roundtrip(
239 era: &str,
240 year: i32,
241 month: u8,
242 day: u8,
243 era2: &str,
244 year2: i32,
245 ) {
246 let expected = Date::try_new_japanese_with_calendar(era2, year2, month, day, CALENDAR)
247 .unwrap_or_else(|e| {
248 panic!(
249 "Failed to construct expectation date with {era2:?}, {year2}, {month}, {day}: {e:?}"
250 )
251 });
252
253 let date = Date::try_new_japanese_with_calendar(era, year, month, day, CALENDAR)
254 .unwrap_or_else(|e| {
255 panic!("Failed to construct date with {era:?}, {year}, {month}, {day}: {e:?}")
256 });
257 assert_eq!(
258 expected, date,
259 "Failed to convert with {era:?}, {year}, {month}, {day}"
260 )
261 }
262
263 #[test]
264 fn test_japanese() {
265 single_test_roundtrip("heisei", 12, 3, 1);
266 single_test_roundtrip("taisho", 3, 3, 1);
267 // Heisei did not start until later in the year
268 single_test_era_range_roundtrip("heisei", 1, 1, 1, "showa", 64);
269
270 // handle bce/ce
271 single_test_roundtrip("bce", 100, 3, 1);
272 single_test_roundtrip("bce", 1, 3, 1);
273 single_test_roundtrip("ce", 1, 3, 1);
274 single_test_roundtrip("ce", 100, 3, 1);
275 single_test_roundtrip("ce", 1000, 3, 1);
276 single_test_era_range_roundtrip("ce", 0, 3, 1, "bce", 1);
277 single_test_era_range_roundtrip("bce", -1, 3, 1, "ce", 2);
278
279 // check post-reiwa
280 single_test_roundtrip("reiwa", 68, 10, 31);
281 single_test_era_range_roundtrip("fuzu", 1, 10, 31, "reiwa", 68);
282 single_test_roundtrip("fuzu", 1, 11, 1);
283
284 // handle the cases where bce/ce get adjusted to different eras
285 // single_test_gregorian_roundtrip("ce", 2021, 3, 1, "reiwa", 3);
286 single_test_era_range_roundtrip("ce", 2024, 3, 1, "reiwa", 6);
287 }
288
289 #[test]
290 /// Pre-Meiji 6 dates are treated as CE, make sure that works right
291 fn test_meiji_6_switchover() {
292 // Pre-meiji 6 dates specified as CE
293 single_test_roundtrip("ce", 1868, 1, 1);
294 single_test_roundtrip("ce", 1868, 10, 1);
295 single_test_roundtrip("ce", 1868, 10, 23);
296 single_test_roundtrip("ce", 1868, 10, 24);
297 single_test_roundtrip("ce", 1868, 11, 1);
298 single_test_roundtrip("ce", 1869, 1, 1);
299 single_test_roundtrip("ce", 1871, 1, 1);
300
301 // Pre-meiji 6 dates specified as Meiji
302 single_test_era_range_roundtrip("meiji", 1, 1, 1, "ce", 1868);
303 single_test_era_range_roundtrip("meiji", 1, 10, 1, "ce", 1868);
304 single_test_era_range_roundtrip("meiji", 1, 10, 23, "ce", 1868);
305 single_test_era_range_roundtrip("meiji", 1, 10, 24, "ce", 1868);
306 single_test_era_range_roundtrip("meiji", 1, 11, 1, "ce", 1868);
307 single_test_era_range_roundtrip("meiji", 1, 11, 1, "ce", 1868);
308 single_test_era_range_roundtrip("meiji", 2, 1, 1, "ce", 1869);
309 single_test_era_range_roundtrip("meiji", 5, 1, 1, "ce", 1872);
310
311 // Post-Meiji 6 dates specified as Meiji
312 single_test_roundtrip("meiji", 6, 1, 1);
313 single_test_roundtrip("meiji", 6, 5, 1);
314 single_test_roundtrip("meiji", 7, 1, 1);
315
316 // Post-Meiji 6 dates specified as CE
317 single_test_era_range_roundtrip("ce", 1873, 1, 1, "meiji", 6);
318 single_test_era_range_roundtrip("ce", 1873, 5, 1, "meiji", 6);
319 single_test_era_range_roundtrip("ce", 1874, 1, 1, "meiji", 7);
320 }
321
322 #[test]
323 fn test_constructor_roundtrip() {
324 let rds = crate::tests::get_interesting_rds();
325 for rd in rds {
326 let date = Date::from_rata_die(rd, Japanese::new());
327 let reconstructed = Date::try_new_japanese_with_calendar(
328 date.era_year().era.as_str(),
329 date.era_year().year,
330 date.month().ordinal,
331 date.day_of_month().0,
332 Japanese::new(),
333 )
334 .unwrap();
335 assert_eq!(
336 reconstructed.to_rata_die(),
337 rd,
338 "Japanese failed for RD {:?}",
339 rd
340 );
341 }
342 }
343 }