Debian Codegraph @

debian/rust-vendor/icu_calendar/src/error.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 //! Error types for functions in the calendar crate
6
7 use crate::types::MonthCode;
8 use displaydoc::Display;
9
10 /// Error type for date creation via [`Date::try_new`].
11 ///
12 /// [`Date::try_new`]: crate::Date::try_new
13 #[derive(Debug, Copy, Clone, PartialEq, Display)]
14 #[non_exhaustive]
15 pub enum DateError {
16 /// A field is out of range for its domain.
17 #[displaydoc("The {field} = {value} argument is out of range {min}..={max}")]
18 Range {
19 /// The field that is out of range, such as "year"
20 field: &'static str,
21 /// The actual value
22 value: i32,
23 /// The minimum value (inclusive). This might not be tight.
24 min: i32,
25 /// The maximum value (inclusive). This might not be tight.
26 max: i32,
27 },
28 /// The era code is invalid for the calendar.
29 #[displaydoc("Unknown era")]
30 UnknownEra,
31 /// The month code is invalid for the calendar or year.
32 ///
33 /// # Examples
34 ///
35 /// ```
36 /// # #![allow(deprecated)]
37 /// use icu::calendar::Date;
38 /// use icu::calendar::DateError;
39 /// use icu::calendar::cal::Hebrew;
40 /// use icu::calendar::types::Month;
41 ///
42 /// Date::try_new_from_codes(None, 5784, Month::leap(5).code(), 1, Hebrew)
43 /// .expect("5784 is a leap year");
44 ///
45 /// let err =
46 /// Date::try_new_from_codes(None, 5785, Month::leap(5).code(), 1, Hebrew)
47 /// .expect_err("5785 is a common year");
48 ///
49 /// assert!(matches!(err, DateError::UnknownMonthCode(_)));
50 /// ```
51 #[displaydoc("Unknown month code {0:?}")]
52 UnknownMonthCode(MonthCode),
53 }
54
55 impl core::error::Error for DateError {}
56
57 /// Error type for date creation for lunisolar calendars.
58 #[derive(Debug, Copy, Clone, PartialEq, Display)]
59 #[non_exhaustive]
60 pub enum LunisolarDateError {
61 /// The day is invalid for the given month.
62 ///
63 /// # Examples
64 ///
65 /// ```
66 /// use icu::calendar::Date;
67 /// use icu::calendar::error::LunisolarDateError;
68 /// use icu::calendar::types::Month;
69 ///
70 /// let err = Date::try_new_hebrew_v2(5785, Month::new(5), 50)
71 /// .expect_err("no month has 50 days");
72 ///
73 /// assert!(matches!(err, LunisolarDateError::InvalidDay { max: 30 }));
74 /// ```
75 #[displaydoc("Invalid day for month, max is {max}")]
76 InvalidDay {
77 /// The maximum allowed value (the minimum is 1).
78 max: u8,
79 },
80 /// The month is invalid for the given year.
81 ///
82 /// # Examples
83 ///
84 /// ```
85 /// use icu::calendar::Date;
86 /// use icu::calendar::error::LunisolarDateError;
87 /// use icu::calendar::types::Month;
88 ///
89 /// Date::try_new_hebrew_v2(5784, Month::leap(5), 1)
90 /// .expect("5784 is a leap year");
91 ///
92 /// let err = Date::try_new_hebrew_v2(5785, Month::leap(5), 1)
93 /// .expect_err("5785 is a common year");
94 ///
95 /// assert!(matches!(err, LunisolarDateError::MonthNotInYear));
96 /// ```
97 #[displaydoc("The specified month exists in this calendar, but not for this year")]
98 MonthNotInYear,
99 /// The month is invalid for the calendar.
100 ///
101 /// # Examples
102 ///
103 /// ```
104 /// use icu::calendar::Date;
105 /// use icu::calendar::error::LunisolarDateError;
106 /// use icu::calendar::types::Month;
107 ///
108 /// let err = Date::try_new_hebrew_v2(5785, Month::leap(1), 1)
109 /// .expect_err("Tishrei does not have a leap month");
110 ///
111 /// assert!(matches!(err, LunisolarDateError::MonthNotInCalendar));
112 /// ```
113 #[displaydoc("The specified month does not exist in this calendar")]
114 MonthNotInCalendar,
115 /// The year exceeds the allowed range.
116 ///
117 /// # Examples
118 ///
119 /// ```
120 /// use icu::calendar::Date;
121 /// use icu::calendar::error::LunisolarDateError;
122 /// use icu::calendar::types::Month;
123 ///
124 /// let err = Date::try_new_hebrew_v2(56812, Month::leap(5), 1)
125 /// .expect_err("56812 is too big");
126 ///
127 /// assert!(matches!(err, LunisolarDateError::InvalidYear));
128 /// ```
129 #[displaydoc("Invalid year")]
130 InvalidYear,
131 }
132
133 impl core::error::Error for LunisolarDateError {}
134
135 /// Error type for date creation via [`Date::try_from_fields`].
136 ///
137 /// [`Date::try_from_fields`]: crate::Date::try_from_fields
138 #[derive(Debug, Copy, Clone, PartialEq, Display)]
139 #[non_exhaustive]
140 pub enum DateFromFieldsError {
141 /// The day is invalid for the given month.
142 ///
143 /// # Examples
144 ///
145 /// ```
146 /// use icu::calendar::Date;
147 /// use icu::calendar::Iso;
148 /// use icu::calendar::error::DateFromFieldsError;
149 /// use icu::calendar::error::RangeError;
150 /// use icu::calendar::types::DateFields;
151 ///
152 /// let mut fields = DateFields::default();
153 /// fields.extended_year = Some(2000);
154 /// fields.ordinal_month = Some(11);
155 /// fields.day = Some(31);
156 ///
157 /// let err = Date::try_from_fields(fields, Default::default(), Iso)
158 /// .expect_err("no day 31 in November");
159 ///
160 /// assert!(matches!(err, DateFromFieldsError::InvalidDay { max: 30 }));
161 /// ```
162 #[displaydoc("Invalid day for month, max is {max}")]
163 InvalidDay {
164 /// The maximum allowed value (the minimum is 1).
165 max: u8,
166 },
167 /// The ordinal month is is invalid for the given year.
168 ///
169 /// # Examples
170 ///
171 /// ```
172 /// use icu::calendar::Date;
173 /// use icu::calendar::Iso;
174 /// use icu::calendar::error::DateFromFieldsError;
175 /// use icu::calendar::error::RangeError;
176 /// use icu::calendar::types::DateFields;
177 ///
178 /// let mut fields = DateFields::default();
179 /// fields.extended_year = Some(2000);
180 /// fields.ordinal_month = Some(13);
181 /// fields.day = Some(1);
182 ///
183 /// let err = Date::try_from_fields(fields, Default::default(), Iso)
184 /// .expect_err("no month 13 in the ISO calendar");
185 ///
186 /// assert!(matches!(
187 /// err,
188 /// DateFromFieldsError::InvalidOrdinalMonth { max: 12 }
189 /// ));
190 /// ```
191 #[displaydoc("Invalid ordinal month for year, max is {max}")]
192 InvalidOrdinalMonth {
193 /// The maximum allowed value (the minimum is 1).
194 max: u8,
195 },
196 /// The month code syntax is invalid.
197 ///
198 /// # Examples
199 ///
200 /// ```
201 /// use icu::calendar::Date;
202 /// use icu::calendar::Iso;
203 /// use icu::calendar::error::DateFromFieldsError;
204 /// use icu::calendar::types::DateFields;
205 ///
206 /// let mut fields = DateFields::default();
207 /// fields.extended_year = Some(2000);
208 /// fields.month_code = Some(b"sep");
209 /// fields.day = Some(1);
210 ///
211 /// let err = Date::try_from_fields(fields, Default::default(), Iso)
212 /// .expect_err("month code is invalid");
213 ///
214 /// assert_eq!(err, DateFromFieldsError::MonthCodeInvalidSyntax);
215 /// ```
216 #[displaydoc("Invalid month code syntax")]
217 MonthCodeInvalidSyntax,
218 /// The specified month does not exist in this calendar.
219 ///
220 /// # Examples
221 ///
222 /// ```
223 /// use icu::calendar::Date;
224 /// use icu::calendar::cal::Hebrew;
225 /// use icu::calendar::error::DateFromFieldsError;
226 /// use icu::calendar::types::{DateFields, Month};
227 ///
228 /// let mut fields = DateFields::default();
229 /// fields.extended_year = Some(5783);
230 /// fields.month = Some(Month::new(13));
231 /// fields.day = Some(1);
232 ///
233 /// let err = Date::try_from_fields(fields, Default::default(), Hebrew)
234 /// .expect_err("no month M13 in Hebrew");
235 /// assert_eq!(err, DateFromFieldsError::MonthNotInCalendar);
236 /// ```
237 #[displaydoc("The specified month does not exist in this calendar")]
238 MonthNotInCalendar,
239 /// The specified month exists in this calendar, but not in the specified year.
240 ///
241 /// # Examples
242 ///
243 /// ```
244 /// use icu::calendar::Date;
245 /// use icu::calendar::cal::Hebrew;
246 /// use icu::calendar::error::DateFromFieldsError;
247 /// use icu::calendar::types::{DateFields, Month};
248 ///
249 /// let mut fields = DateFields::default();
250 /// fields.extended_year = Some(5783);
251 /// fields.month = Some(Month::leap(5));
252 /// fields.day = Some(1);
253 ///
254 /// let err = Date::try_from_fields(fields, Default::default(), Hebrew)
255 /// .expect_err("no month M05L in Hebrew year 5783");
256 /// assert_eq!(err, DateFromFieldsError::MonthNotInYear);
257 /// ```
258 #[displaydoc("The specified month exists in this calendar, but not for this year")]
259 MonthNotInYear,
260 /// The era code is invalid for the calendar.
261 ///
262 /// # Examples
263 ///
264 /// ```
265 /// use icu::calendar::Date;
266 /// use icu::calendar::cal::Hebrew;
267 /// use icu::calendar::error::DateFromFieldsError;
268 /// use icu::calendar::types::DateFields;
269 ///
270 /// let mut fields = DateFields::default();
271 /// fields.era = Some(b"ce"); // valid in Gregorian, but not Hebrew
272 /// fields.era_year = Some(1);
273 /// fields.ordinal_month = Some(1);
274 /// fields.day = Some(1);
275 ///
276 /// let err = Date::try_from_fields(fields, Default::default(), Hebrew::new())
277 /// .expect_err("era is unknown for Hebrew");
278 ///
279 /// assert_eq!(err, DateFromFieldsError::InvalidEra);
280 /// ```
281 #[displaydoc("Unknown era or invalid syntax")]
282 InvalidEra,
283 /// The year was specified in multiple inconsistent ways.
284 ///
285 /// # Examples
286 ///
287 /// ```
288 /// use icu::calendar::Date;
289 /// use icu::calendar::cal::Japanese;
290 /// use icu::calendar::error::DateFromFieldsError;
291 /// use icu::calendar::types::DateFields;
292 ///
293 /// let mut fields = DateFields::default();
294 /// fields.era = Some(b"reiwa");
295 /// fields.era_year = Some(6);
296 /// fields.ordinal_month = Some(1);
297 /// fields.day = Some(1);
298 ///
299 /// Date::try_from_fields(fields, Default::default(), Japanese::new())
300 /// .expect("a well-defined Japanese date");
301 ///
302 /// fields.extended_year = Some(1900);
303 ///
304 /// let err =
305 /// Date::try_from_fields(fields, Default::default(), Japanese::new())
306 /// .expect_err("year 1900 is not the same as 6 Reiwa");
307 ///
308 /// assert_eq!(err, DateFromFieldsError::InconsistentYear);
309 /// ```
310 #[displaydoc("Inconsistent year")]
311 InconsistentYear,
312 /// The month was specified in multiple inconsistent ways.
313 ///
314 /// # Examples
315 ///
316 /// ```
317 /// use icu::calendar::Date;
318 /// use icu::calendar::cal::Hebrew;
319 /// use icu::calendar::error::DateFromFieldsError;
320 /// use icu::calendar::types::{DateFields, Month};
321 /// use tinystr::tinystr;
322 ///
323 /// let mut fields = DateFields::default();
324 /// fields.extended_year = Some(5783);
325 /// fields.month = Some(Month::new(6));
326 /// fields.ordinal_month = Some(6);
327 /// fields.day = Some(1);
328 ///
329 /// Date::try_from_fields(fields, Default::default(), Hebrew)
330 /// .expect("a well-defined Hebrew date in a common year");
331 ///
332 /// fields.extended_year = Some(5784);
333 ///
334 /// let err = Date::try_from_fields(fields, Default::default(), Hebrew)
335 /// .expect_err("month M06 is not the 6th month in leap year 5784");
336 ///
337 /// assert_eq!(err, DateFromFieldsError::InconsistentMonth);
338 /// ```
339 #[displaydoc("Inconsistent month")]
340 InconsistentMonth,
341 /// Too many fields were specified to form a well-defined date.
342 ///
343 /// # Examples
344 ///
345 /// ```
346 /// use icu::calendar::Date;
347 /// use icu::calendar::Iso;
348 /// use icu::calendar::error::DateFromFieldsError;
349 /// use icu::calendar::types::{DateFields, Month};
350 ///
351 /// let mut fields = DateFields::default();
352 /// fields.extended_year = Some(2000);
353 /// fields.month = Some(Month::new(1));
354 /// fields.month_code = Some(b"M01");
355 /// fields.day = Some(1);
356 ///
357 /// let err = Date::try_from_fields(fields, Default::default(), Iso)
358 /// .expect_err("cannot specify both month and month_code");
359 ///
360 /// assert_eq!(err, DateFromFieldsError::TooManyFields);
361 /// ```
362 #[displaydoc("Too many fields")]
363 TooManyFields,
364 /// Not enough fields were specified to form a well-defined date.
365 ///
366 /// # Examples
367 ///
368 /// ```
369 /// use icu::calendar::Date;
370 /// use icu::calendar::cal::Hebrew;
371 /// use icu::calendar::error::DateFromFieldsError;
372 /// use icu::calendar::types::DateFields;
373 /// use tinystr::tinystr;
374 ///
375 /// let mut fields = DateFields::default();
376 ///
377 /// fields.ordinal_month = Some(3);
378 ///
379 /// let err = Date::try_from_fields(fields, Default::default(), Hebrew)
380 /// .expect_err("need more than just an ordinal month");
381 /// assert_eq!(err, DateFromFieldsError::NotEnoughFields);
382 ///
383 /// fields.era_year = Some(5783);
384 ///
385 /// let err = Date::try_from_fields(fields, Default::default(), Hebrew)
386 /// .expect_err("need more than an ordinal month and an era year");
387 /// assert_eq!(err, DateFromFieldsError::NotEnoughFields);
388 ///
389 /// fields.extended_year = Some(5783);
390 ///
391 /// let err = Date::try_from_fields(fields, Default::default(), Hebrew)
392 /// .expect_err("era year still needs an era");
393 /// assert_eq!(err, DateFromFieldsError::NotEnoughFields);
394 ///
395 /// fields.era = Some(b"am");
396 ///
397 /// let date = Date::try_from_fields(fields, Default::default(), Hebrew)
398 /// .expect_err("still missing the day");
399 /// assert_eq!(err, DateFromFieldsError::NotEnoughFields);
400 ///
401 /// fields.day = Some(1);
402 /// let date = Date::try_from_fields(fields, Default::default(), Hebrew)
403 /// .expect("we have enough fields!");
404 /// ```
405 #[displaydoc("Not enough fields")]
406 NotEnoughFields,
407 /// The date is out of range (see docs on [`Date`](crate::Date)
408 /// for more information about `Date`'s fundamental range invariant).
409 ///
410 /// # Examples
411 ///
412 /// ```
413 /// use icu::calendar::error::DateFromFieldsError;
414 /// use icu::calendar::error::RangeError;
415 /// use icu::calendar::types::DateFields;
416 /// use icu::calendar::Date;
417 /// use icu::calendar::Iso;
418 ///
419 /// let mut fields = DateFields::default();
420 /// fields.extended_year = Some(12345678);
421 /// fields.ordinal_month = Some(12);
422 /// fields.day = Some(31);
423 ///
424 /// let err = Date::try_from_fields(fields, Default::default(), Iso)
425 /// .expect_err("date out of range");
426 ///
427 /// assert!(matches!(
428 /// err,
429 /// DateFromFieldsError::Overflow
430 /// ));
431 #[displaydoc("Result out of range")]
432 Overflow,
433 }
434
435 impl core::error::Error for DateFromFieldsError {}
436
437 /// Error type for date addition via [`Date::try_add_with_options`].
438 ///
439 /// [`Date::try_add_with_options`]: crate::Date::try_add_with_options
440 #[derive(Debug, Copy, Clone, PartialEq, Display)]
441 #[non_exhaustive]
442 pub enum DateAddError {
443 /// The day is invalid for the given month.
444 ///
445 /// This is only possible with [`Overflow::Reject`](crate::options::Overflow::Reject).
446 ///
447 /// # Examples
448 ///
449 /// ```
450 /// use icu::calendar::Date;
451 /// use icu::calendar::error::DateAddError;
452 /// use icu::calendar::options::{DateAddOptions, Overflow};
453 /// use icu::calendar::types::DateDuration;
454 ///
455 /// // There is a day 31 in October but not in November.
456 /// let d = Date::try_new_iso(2025, 10, 31).unwrap();
457 /// let duration = DateDuration::for_months(1);
458 ///
459 /// let mut options = DateAddOptions::default();
460 /// options.overflow = Some(Overflow::Reject);
461 ///
462 /// let err = d
463 /// .try_added_with_options(duration, options)
464 /// .expect_err("no day 31 in November");
465 ///
466 /// assert!(matches!(err, DateAddError::InvalidDay { max: 30 }));
467 /// ```
468 #[displaydoc("Invalid day for month, max is {max}")]
469 InvalidDay {
470 /// The maximum allowed value (the minimum is 1).
471 max: u8,
472 },
473 /// The specified month exists in this calendar, but not in the specified year.
474 ///
475 /// This is only possible with [`Overflow::Reject`](crate::options::Overflow::Reject).
476 ///
477 /// # Examples
478 ///
479 /// ```
480 /// use icu::calendar::Date;
481 /// use icu::calendar::cal::Hebrew;
482 /// use icu::calendar::error::DateAddError;
483 /// use icu::calendar::options::{DateAddOptions, Overflow};
484 /// use icu::calendar::types::{DateDuration, Month};
485 ///
486 /// // Hebrew year 5784 is a leap year, 5785 is not.
487 /// // Adar I (the leap month) is month 5 in a leap year.
488 /// let d = Date::try_new_hebrew_v2(5784, Month::leap(5), 1).unwrap();
489 /// let duration = DateDuration::for_years(1);
490 ///
491 /// let mut options = DateAddOptions::default();
492 /// options.overflow = Some(Overflow::Reject);
493 ///
494 /// let err = d
495 /// .try_added_with_options(duration, options)
496 /// .expect_err("5785 is not a leap year");
497 ///
498 /// assert_eq!(err, DateAddError::MonthNotInYear);
499 /// ```
500 #[displaydoc("The specified month exists in this calendar, but not for this year")]
501 MonthNotInYear,
502 /// The date is out of range (see docs on [`Date`](crate::Date)
503 /// for more information about `Date`'s fundamental range invariant).
504 ///
505 /// # Examples
506 ///
507 /// ```
508 /// use icu::calendar::Date;
509 /// use icu::calendar::error::DateAddError;
510 /// use icu::calendar::types::DateDuration;
511 ///
512 /// let d = Date::try_new_iso(2025, 1, 1).unwrap();
513 /// let duration = DateDuration::for_years(1_000_000);
514 ///
515 /// let err = d
516 /// .try_added_with_options(duration, Default::default())
517 /// .expect_err("date overflow");
518 ///
519 /// assert_eq!(err, DateAddError::Overflow);
520 /// ```
521 #[displaydoc("Result out of range")]
522 Overflow,
523 }
524
525 impl core::error::Error for DateAddError {}
526
527 /// Error returned when interacting two [`Date`](crate::Date)s with non-singleton calendars.
528 ///
529 /// # Examples
530 ///
531 /// ```
532 /// use icu::calendar::Date;
533 /// use icu::calendar::error::MismatchedCalendarError;
534 /// use icu::calendar::options::DateDifferenceOptions;
535 /// use icu::calendar::options::DateDurationUnit;
536 ///
537 /// let d1 = Date::try_new_gregorian(2000, 1, 1).unwrap().to_any();
538 /// let d2 = Date::try_new_persian(1562, 1, 1).unwrap().to_any();
539 ///
540 /// assert_eq!(
541 /// d1.try_until_with_options(&d2, Default::default())
542 /// .unwrap_err(),
543 /// MismatchedCalendarError,
544 /// );
545 ///
546 /// // To compare the dates, convert them to the same calendar.
547 /// // Note that the result may differ based on the calendar used,
548 /// // e.g if comparing in months and days.
549 ///
550 /// let mut options = DateDifferenceOptions::default();
551 /// options.largest_unit = Some(DateDurationUnit::Months);
552 ///
553 /// let diff1 = d1
554 /// .to_calendar(d2.calendar().clone())
555 /// .try_until_with_options(&d2, options)
556 /// .unwrap();
557 /// let diff2 = d1
558 /// .try_until_with_options(&d2.to_calendar(d1.calendar().clone()), options)
559 /// .unwrap();
560 ///
561 /// assert_ne!(diff1, diff2);
562 /// ```
563 #[derive(Clone, Copy, PartialEq, Debug, Display)]
564 #[displaydoc("Attempted to interact two `Date`s with different calendars")]
565 #[allow(
566 clippy::exhaustive_structs,
567 reason = "This is the only possible error with multi-calendar operations"
568 )]
569 pub struct MismatchedCalendarError;
570
571 impl core::error::Error for MismatchedCalendarError {}
572
573 /// Error type for date creation via [`Date::try_new`].
574 ///
575 /// [`Date::try_new`]: crate::Date::try_new
576 #[derive(Debug, Copy, Clone, PartialEq, Display)]
577 #[non_exhaustive]
578 pub enum DateNewError {
579 /// The day is invalid for the given month.
580 #[displaydoc("Invalid day for month, max is {max}")]
581 InvalidDay {
582 /// The maximum allowed value (the minimum is 1).
583 max: u8,
584 },
585 /// The specified month does not exist in this calendar.
586 #[displaydoc("The specified month does not exist in this calendar")]
587 MonthNotInCalendar,
588 /// The specified month exists in this calendar, but not in the specified year.
589 #[displaydoc("The specified month exists in this calendar, but not for this year")]
590 MonthNotInYear,
591 /// The era code is invalid for the calendar.
592 #[displaydoc("Unknown era or invalid syntax")]
593 InvalidEra,
594
595 /// The year was out of range
596 #[displaydoc("Invalid year, must be within -9999..=9999")]
597 InvalidYear,
598 }
599
600 impl core::error::Error for DateNewError {}
601
602 impl From<UnknownEraError> for DateNewError {
603 fn from(_: UnknownEraError) -> Self {
604 Self::InvalidEra
605 }
606 }
607
608 /// Internal narrow error type for functions that only fail on unknown eras
609 pub(crate) struct UnknownEraError;
610
611 impl From<UnknownEraError> for DateError {
612 #[inline]
613 fn from(_value: UnknownEraError) -> Self {
614 DateError::UnknownEra
615 }
616 }
617
618 impl From<UnknownEraError> for DateFromFieldsError {
619 #[inline]
620 fn from(_value: UnknownEraError) -> Self {
621 DateFromFieldsError::InvalidEra
622 }
623 }
624
625 /// Error for [`Month`](crate::types::Month) parsing
626 #[derive(Debug, Copy, Clone, PartialEq, Eq)]
627 #[non_exhaustive]
628 pub enum MonthCodeParseError {
629 /// Invalid syntax
630 InvalidSyntax,
631 }
632
633 impl From<MonthCodeParseError> for DateFromFieldsError {
634 #[inline]
635 fn from(value: MonthCodeParseError) -> Self {
636 match value {
637 MonthCodeParseError::InvalidSyntax => DateFromFieldsError::MonthCodeInvalidSyntax,
638 }
639 }
640 }
641
642 /// Internal narrow error type for functions that only fail on month operations
643 #[derive(Debug, PartialEq)]
644 pub(crate) enum MonthError {
645 NotInCalendar,
646 NotInYear,
647 }
648
649 impl From<MonthError> for DateFromFieldsError {
650 #[inline]
651 fn from(value: MonthError) -> Self {
652 match value {
653 MonthError::NotInCalendar => DateFromFieldsError::MonthNotInCalendar,
654 MonthError::NotInYear => DateFromFieldsError::MonthNotInYear,
655 }
656 }
657 }
658
659 /// Errors that can occur when parsing an ISO 8601 date-only duration string.
660 #[derive(Debug, Copy, Clone, Eq, PartialEq)]
661 #[non_exhaustive]
662 pub enum DateDurationParseError {
663 /// The input does not follow the expected ISO 8601 date only duration structure.
664 ///
665 /// This error occurs when the duration string is incomplete,
666 /// or contains unexpected characters.
667 ///
668 /// # Examples
669 ///
670 /// ```rust
671 /// use icu::calendar::error::DateDurationParseError;
672 /// use icu::calendar::types::DateDuration;
673 ///
674 /// assert_eq!(
675 /// DateDuration::try_from_str("P"),
676 /// Err(DateDurationParseError::InvalidStructure)
677 /// );
678 /// assert_eq!(
679 /// DateDuration::try_from_str("P1"),
680 /// Err(DateDurationParseError::InvalidStructure)
681 /// );
682 /// ```
683 InvalidStructure,
684
685 /// The duration contains a time component, which is not supported.
686 ///
687 /// Only date based units (`Y`, `M`, `W`, `D`) are supported. Any duration
688 /// containing a `T` time separator is rejected.
689 ///
690 /// # Examples
691 ///
692 /// ```rust
693 /// use icu::calendar::error::DateDurationParseError;
694 /// use icu::calendar::types::DateDuration;
695 ///
696 /// assert_eq!(
697 /// DateDuration::try_from_str("PT5M"),
698 /// Err(DateDurationParseError::TimeNotSupported)
699 /// );
700 /// assert_eq!(
701 /// DateDuration::try_from_str("P1DT"),
702 /// Err(DateDurationParseError::TimeNotSupported)
703 /// );
704 /// ```
705 TimeNotSupported,
706
707 /// A duration unit appeared without a number before it.
708 ///
709 /// For example, the string contains `Y`, `M`, `W`, or `D` without a
710 /// numeric value directly in front of it.
711 ///
712 /// # Examples
713 ///
714 /// ```rust
715 /// use icu::calendar::error::DateDurationParseError;
716 /// use icu::calendar::types::DateDuration;
717 ///
718 /// assert_eq!(
719 /// DateDuration::try_from_str("PY"),
720 /// Err(DateDurationParseError::MissingValue)
721 /// );
722 /// assert_eq!(
723 /// DateDuration::try_from_str("PX1D"),
724 /// Err(DateDurationParseError::MissingValue)
725 /// );
726 /// ```
727 MissingValue,
728
729 /// A duration unit was specified more than once.
730 ///
731 /// Each unit (`Y`, `M`, `W`, `D`) may appear at most once only.
732 ///
733 /// # Examples
734 ///
735 /// ```rust
736 /// use icu::calendar::error::DateDurationParseError;
737 /// use icu::calendar::types::DateDuration;
738 ///
739 /// assert_eq!(
740 /// DateDuration::try_from_str("P1Y2Y"),
741 /// Err(DateDurationParseError::DuplicateUnit)
742 /// );
743 /// assert_eq!(
744 /// DateDuration::try_from_str("P1D1D"),
745 /// Err(DateDurationParseError::DuplicateUnit)
746 /// );
747 /// ```
748 DuplicateUnit,
749
750 /// A numeric value exceeded or was more than the supported range.
751 ///
752 /// # Examples
753 ///
754 /// ```rust
755 /// use icu::calendar::error::DateDurationParseError;
756 /// use icu::calendar::types::DateDuration;
757 ///
758 /// assert_eq!(
759 /// DateDuration::try_from_str("P4294967296Y"),
760 /// Err(DateDurationParseError::NumberOverflow)
761 /// );
762 /// ```
763 NumberOverflow,
764
765 /// A duration starts with a `+` sign, which is not allowed.
766 ///
767 /// Only negative durations using a leading `-` are supported.
768 ///
769 /// # Examples
770 ///
771 /// ```rust
772 /// use icu::calendar::error::DateDurationParseError;
773 /// use icu::calendar::types::DateDuration;
774 ///
775 /// assert_eq!(
776 /// DateDuration::try_from_str("+P1D"),
777 /// Err(DateDurationParseError::PlusNotAllowed)
778 /// );
779 /// ```
780 PlusNotAllowed,
781 }
782
783 mod inner {
784 /// Internal narrow error type for calculating the ECMA reference year
785 ///
786 /// Public but unstable because it is used on [`hijri::Rules`](crate::cal::hijri::Rules)
787 ///
788 /// <div class="stab unstable">
789 /// 🚧 This code is considered unstable; it may change at any time, in breaking or non-breaking ways,
790 /// including in SemVer minor releases. Do not use this type unless you are prepared for things to occasionally break.
791 ///
792 /// Graduation tracking issue: [issue #6962](https://github.com/unicode-org/icu4x/issues/6962).
793 /// </div>
794 #[derive(Debug, Copy, Clone, PartialEq, Eq)]
795 #[allow(missing_docs)] // TODO: fix when graduating
796 #[non_exhaustive]
797 pub enum EcmaReferenceYearError {
798 Unimplemented,
799 MonthNotInCalendar,
800 /// This leap month could not be found within recent times.
801 /// Constrain to the regular month if allowed, otherwise reject.
802 ///
803 /// Note: This currently encodes Chinese/Dangi-specific specced
804 /// semantics. Before graduation, we should consider having this be
805 /// something like UseIfConstrain(y, m, d).
806 UseRegularIfConstrain,
807 }
808 }
809
810 #[cfg(feature = "unstable")]
811 pub use inner::EcmaReferenceYearError;
812 #[cfg(not(feature = "unstable"))]
813 pub(crate) use inner::EcmaReferenceYearError;
814
815 impl From<EcmaReferenceYearError> for DateFromFieldsError {
816 #[inline]
817 fn from(value: EcmaReferenceYearError) -> Self {
818 match value {
819 EcmaReferenceYearError::Unimplemented => DateFromFieldsError::NotEnoughFields,
820 EcmaReferenceYearError::MonthNotInCalendar => DateFromFieldsError::MonthNotInCalendar,
821 // This only happens when the month-day combo isn't in the year, and if not rejecting
822 // we constrain to the non-leap month
823 //
824 // We can potentially consider turning this into a RangeError, then UseRegularIfConstrain
825 // would need to carry a range error inside it.
826 EcmaReferenceYearError::UseRegularIfConstrain => DateFromFieldsError::MonthNotInYear,
827 }
828 }
829 }
830
831 #[derive(Debug, Copy, Clone, PartialEq, Display)]
832 /// An argument is out of range for its domain.
833 #[displaydoc("The {field} = {value} argument is out of range {min}..={max}")]
834 #[allow(clippy::exhaustive_structs)]
835 pub struct RangeError {
836 /// The argument that is out of range, such as "year"
837 pub field: &'static str,
838 /// The actual value
839 pub value: i32,
840 /// The minimum value (inclusive). This might not be tight.
841 pub min: i32,
842 /// The maximum value (inclusive). This might not be tight.
843 pub max: i32,
844 }
845
846 impl core::error::Error for RangeError {}
847
848 impl From<RangeError> for DateError {
849 #[inline]
850 fn from(value: RangeError) -> Self {
851 let RangeError {
852 field,
853 value,
854 min,
855 max,
856 } = value;
857 DateError::Range {
858 field,
859 value,
860 min,
861 max,
862 }
863 }
864 }
865
866 pub(crate) fn range_check<T: Ord + Into<i32> + Copy>(
867 value: T,
868 field: &'static str,
869 bounds: core::ops::RangeInclusive<T>,
870 ) -> Result<T, RangeError> {
871 if !bounds.contains(&value) {
872 return Err(RangeError {
873 field,
874 value: value.into(),
875 min: (*bounds.start()).into(),
876 max: (*bounds.end()).into(),
877 });
878 }
879 Ok(value)
880 }