1use crate::oxsdatatypes::{DateTime, Decimal};
2use serde::{Deserialize, Serialize};
3use std::cmp::Ordering;
4use std::fmt;
5use std::str::FromStr;
6use std::time::Duration as StdDuration;
7
8#[derive(Eq, PartialEq, Debug, Clone, Copy, Hash, Default, Serialize, Deserialize)]
12pub struct Duration {
13 year_month: YearMonthDuration,
14 day_time: DayTimeDuration,
15}
16
17impl Duration {
18 pub const MAX: Self = Self {
19 year_month: YearMonthDuration::MAX,
20 day_time: DayTimeDuration::MAX,
21 };
22 pub const MIN: Self = Self {
23 year_month: YearMonthDuration::MIN,
24 day_time: DayTimeDuration::MIN,
25 };
26
27 #[inline]
28 pub fn new(
29 months: impl Into<i64>,
30 seconds: impl Into<Decimal>,
31 ) -> Result<Self, OppositeSignInDurationComponentsError> {
32 Self::construct(
33 YearMonthDuration::new(months),
34 DayTimeDuration::new(seconds),
35 )
36 }
37
38 #[inline]
39 fn construct(
40 year_month: YearMonthDuration,
41 day_time: DayTimeDuration,
42 ) -> Result<Self, OppositeSignInDurationComponentsError> {
43 if (year_month > YearMonthDuration::default() && day_time < DayTimeDuration::default())
44 || (year_month < YearMonthDuration::default() && day_time > DayTimeDuration::default())
45 {
46 return Err(OppositeSignInDurationComponentsError);
47 }
48 Ok(Self {
49 year_month,
50 day_time,
51 })
52 }
53
54 #[inline]
55 #[must_use]
56 pub fn from_be_bytes(bytes: [u8; 24]) -> Self {
57 Self {
58 year_month: YearMonthDuration::from_be_bytes(bytes[0..8].try_into().unwrap()),
59 day_time: DayTimeDuration::from_be_bytes(bytes[8..24].try_into().unwrap()),
60 }
61 }
62
63 #[inline]
65 #[must_use]
66 pub fn years(self) -> i64 {
67 self.year_month.years()
68 }
69
70 #[inline]
72 #[must_use]
73 pub fn months(self) -> i64 {
74 self.year_month.months()
75 }
76
77 #[inline]
79 #[must_use]
80 pub fn days(self) -> i64 {
81 self.day_time.days()
82 }
83
84 #[inline]
86 #[must_use]
87 pub fn hours(self) -> i64 {
88 self.day_time.hours()
89 }
90
91 #[inline]
93 #[must_use]
94 pub fn minutes(self) -> i64 {
95 self.day_time.minutes()
96 }
97
98 #[inline]
100 #[must_use]
101 pub fn seconds(self) -> Decimal {
102 self.day_time.seconds()
103 }
104
105 #[inline]
106 #[must_use]
107 pub(crate) const fn all_months(self) -> i64 {
108 self.year_month.all_months()
109 }
110
111 #[inline]
112 #[must_use]
113 pub(crate) const fn all_seconds(self) -> Decimal {
114 self.day_time.as_seconds()
115 }
116
117 #[inline]
118 #[must_use]
119 pub fn to_be_bytes(self) -> [u8; 24] {
120 let mut bytes = [0; 24];
121 bytes[0..8].copy_from_slice(&self.year_month.to_be_bytes());
122 bytes[8..24].copy_from_slice(&self.day_time.to_be_bytes());
123 bytes
124 }
125
126 #[inline]
130 #[must_use]
131 pub fn checked_add(self, rhs: impl Into<Self>) -> Option<Self> {
132 let rhs = rhs.into();
133 Self::construct(
134 self.year_month.checked_add(rhs.year_month)?,
135 self.day_time.checked_add(rhs.day_time)?,
136 )
137 .ok()
138 }
139
140 #[inline]
144 #[must_use]
145 pub fn checked_sub(self, rhs: impl Into<Self>) -> Option<Self> {
146 let rhs = rhs.into();
147 Self::construct(
148 self.year_month.checked_sub(rhs.year_month)?,
149 self.day_time.checked_sub(rhs.day_time)?,
150 )
151 .ok()
152 }
153
154 #[inline]
158 #[must_use]
159 pub fn checked_neg(self) -> Option<Self> {
160 Some(Self {
161 year_month: self.year_month.checked_neg()?,
162 day_time: self.day_time.checked_neg()?,
163 })
164 }
165
166 #[inline]
168 #[must_use]
169 pub fn is_identical_with(self, other: Self) -> bool {
170 self == other
171 }
172}
173
174impl TryFrom<StdDuration> for Duration {
175 type Error = DurationOverflowError;
176
177 #[inline]
178 fn try_from(value: StdDuration) -> Result<Self, Self::Error> {
179 Ok(DayTimeDuration::try_from(value)?.into())
180 }
181}
182
183impl FromStr for Duration {
184 type Err = ParseDurationError;
185
186 fn from_str(input: &str) -> Result<Self, Self::Err> {
187 let parts = ensure_complete(input, duration_parts)?;
188 if parts.year_month.is_none() && parts.day_time.is_none() {
189 return Err(Self::Err::msg("Empty duration"));
190 }
191 Ok(Self::new(
192 parts.year_month.unwrap_or(0),
193 parts.day_time.unwrap_or_default(),
194 )?)
195 }
196}
197
198impl fmt::Display for Duration {
199 #[allow(clippy::many_single_char_names)]
200 #[inline]
201 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
202 let ym = self.year_month.months;
203 let ss = self.day_time.seconds;
204
205 if (ym < 0 && ss > 0.into()) || (ym > 0 && ss < 0.into()) {
206 return Err(fmt::Error); }
208 if ym < 0 || ss < 0.into() {
209 f.write_str("-")?;
210 }
211 f.write_str("P")?;
212
213 if ym == 0 && ss == 0.into() {
214 return f.write_str("T0S");
215 }
216
217 {
218 let y = ym / 12;
219 let m = ym % 12;
220
221 if y != 0 {
222 if m == 0 {
223 write!(f, "{}Y", y.abs())?;
224 } else {
225 write!(f, "{}Y{}M", y.abs(), m.abs())?;
226 }
227 } else if m != 0 || ss == 0.into() {
228 write!(f, "{}M", m.abs())?;
229 }
230 }
231
232 {
233 let s_int = ss.as_i128();
234 let d = s_int / 86400;
235 let h = (s_int % 86400) / 3600;
236 let m = (s_int % 3600) / 60;
237 let s = ss
238 .checked_sub(
239 Decimal::try_from(d * 86400 + h * 3600 + m * 60).map_err(|_| fmt::Error)?,
240 )
241 .ok_or(fmt::Error)?;
242
243 if d != 0 {
244 write!(f, "{}D", d.abs())?;
245 }
246
247 if h != 0 || m != 0 || s != 0.into() {
248 f.write_str("T")?;
249 if h != 0 {
250 write!(f, "{}H", h.abs())?;
251 }
252 if m != 0 {
253 write!(f, "{}M", m.abs())?;
254 }
255 if s != 0.into() {
256 write!(f, "{}S", s.checked_abs().ok_or(fmt::Error)?)?;
257 }
258 }
259 }
260 Ok(())
261 }
262}
263
264impl PartialOrd for Duration {
265 #[inline]
266 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
267 let first = DateTime::new(1969, 9, 1, 0, 0, 0.into(), None).ok()?;
268 let first_result = first
269 .checked_add_duration(*self)?
270 .partial_cmp(&first.checked_add_duration(*other)?);
271 let second = DateTime::new(1697, 2, 1, 0, 0, 0.into(), None).ok()?;
272 let second_result = second
273 .checked_add_duration(*self)?
274 .partial_cmp(&second.checked_add_duration(*other)?);
275 let third = DateTime::new(1903, 3, 1, 0, 0, 0.into(), None).ok()?;
276 let third_result = third
277 .checked_add_duration(*self)?
278 .partial_cmp(&third.checked_add_duration(*other)?);
279 let fourth = DateTime::new(1903, 7, 1, 0, 0, 0.into(), None).ok()?;
280 let fourth_result = fourth
281 .checked_add_duration(*self)?
282 .partial_cmp(&fourth.checked_add_duration(*other)?);
283 if first_result == second_result
284 && second_result == third_result
285 && third_result == fourth_result
286 {
287 first_result
288 } else {
289 None
290 }
291 }
292}
293
294#[derive(
298 Eq, PartialEq, Ord, PartialOrd, Debug, Clone, Copy, Hash, Default, Serialize, Deserialize,
299)]
300pub struct YearMonthDuration {
301 months: i64,
302}
303
304impl YearMonthDuration {
305 pub const MAX: Self = Self { months: i64::MAX };
306 pub const MIN: Self = Self { months: i64::MIN };
307
308 #[inline]
309 pub fn new(months: impl Into<i64>) -> Self {
310 Self {
311 months: months.into(),
312 }
313 }
314
315 #[inline]
316 pub fn from_be_bytes(bytes: [u8; 8]) -> Self {
317 Self {
318 months: i64::from_be_bytes(bytes),
319 }
320 }
321
322 #[inline]
324 pub fn years(self) -> i64 {
325 self.months / 12
326 }
327
328 #[inline]
330 pub fn months(self) -> i64 {
331 self.months % 12
332 }
333
334 #[inline]
335 pub(crate) const fn all_months(self) -> i64 {
336 self.months
337 }
338
339 #[inline]
340 pub fn to_be_bytes(self) -> [u8; 8] {
341 self.months.to_be_bytes()
342 }
343
344 #[inline]
348 pub fn checked_add(self, rhs: impl Into<Self>) -> Option<Self> {
349 let rhs = rhs.into();
350 Some(Self {
351 months: self.months.checked_add(rhs.months)?,
352 })
353 }
354
355 #[inline]
359 pub fn checked_sub(self, rhs: impl Into<Self>) -> Option<Self> {
360 let rhs = rhs.into();
361 Some(Self {
362 months: self.months.checked_sub(rhs.months)?,
363 })
364 }
365
366 #[inline]
370 pub fn checked_neg(self) -> Option<Self> {
371 Some(Self {
372 months: self.months.checked_neg()?,
373 })
374 }
375
376 #[inline]
378 pub fn is_identical_with(self, other: Self) -> bool {
379 self == other
380 }
381}
382
383impl From<YearMonthDuration> for Duration {
384 #[inline]
385 fn from(value: YearMonthDuration) -> Self {
386 Self {
387 year_month: value,
388 day_time: DayTimeDuration::default(),
389 }
390 }
391}
392
393impl TryFrom<Duration> for YearMonthDuration {
394 type Error = DurationOverflowError;
395
396 #[inline]
397 fn try_from(value: Duration) -> Result<Self, Self::Error> {
398 if value.day_time == DayTimeDuration::default() {
399 Ok(value.year_month)
400 } else {
401 Err(DurationOverflowError)
402 }
403 }
404}
405
406impl FromStr for YearMonthDuration {
407 type Err = ParseDurationError;
408
409 fn from_str(input: &str) -> Result<Self, Self::Err> {
410 let parts = ensure_complete(input, duration_parts)?;
411 if parts.day_time.is_some() {
412 return Err(Self::Err::msg(
413 "There must not be any day or time component in a yearMonthDuration",
414 ));
415 }
416 Ok(Self::new(
417 parts
418 .year_month
419 .ok_or(Self::Err::msg("No year and month values found"))?,
420 ))
421 }
422}
423
424impl fmt::Display for YearMonthDuration {
425 #[inline]
426 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
427 if self.months == 0 {
428 f.write_str("P0M")
429 } else {
430 Duration::from(*self).fmt(f)
431 }
432 }
433}
434
435impl PartialEq<Duration> for YearMonthDuration {
436 #[inline]
437 fn eq(&self, other: &Duration) -> bool {
438 Duration::from(*self).eq(other)
439 }
440}
441
442impl PartialEq<YearMonthDuration> for Duration {
443 #[inline]
444 fn eq(&self, other: &YearMonthDuration) -> bool {
445 self.eq(&Self::from(*other))
446 }
447}
448
449impl PartialOrd<Duration> for YearMonthDuration {
450 #[inline]
451 fn partial_cmp(&self, other: &Duration) -> Option<Ordering> {
452 Duration::from(*self).partial_cmp(other)
453 }
454}
455
456impl PartialOrd<YearMonthDuration> for Duration {
457 #[inline]
458 fn partial_cmp(&self, other: &YearMonthDuration) -> Option<Ordering> {
459 self.partial_cmp(&Self::from(*other))
460 }
461}
462
463#[derive(
467 Eq, PartialEq, Ord, PartialOrd, Debug, Clone, Copy, Hash, Default, Serialize, Deserialize,
468)]
469pub struct DayTimeDuration {
470 seconds: Decimal,
471}
472
473impl DayTimeDuration {
474 pub const MAX: Self = Self {
475 seconds: Decimal::MAX,
476 };
477 pub const MIN: Self = Self {
478 seconds: Decimal::MIN,
479 };
480
481 #[inline]
482 pub fn new(seconds: impl Into<Decimal>) -> Self {
483 Self {
484 seconds: seconds.into(),
485 }
486 }
487
488 #[inline]
489 pub fn from_be_bytes(bytes: [u8; 16]) -> Self {
490 Self {
491 seconds: Decimal::from_be_bytes(bytes),
492 }
493 }
494
495 #[allow(clippy::cast_possible_truncation)]
497 #[inline]
498 pub fn days(self) -> i64 {
499 (self.seconds.as_i128() / 86400) as i64
500 }
501
502 #[allow(clippy::cast_possible_truncation)]
504 #[inline]
505 pub fn hours(self) -> i64 {
506 ((self.seconds.as_i128() % 86400) / 3600) as i64
507 }
508
509 #[allow(clippy::cast_possible_truncation)]
511 #[inline]
512 pub fn minutes(self) -> i64 {
513 ((self.seconds.as_i128() % 3600) / 60) as i64
514 }
515
516 #[inline]
518 pub fn seconds(self) -> Decimal {
519 self.seconds.checked_rem(60).unwrap()
520 }
521
522 #[inline]
524 pub const fn as_seconds(self) -> Decimal {
525 self.seconds
526 }
527
528 #[inline]
529 pub fn to_be_bytes(self) -> [u8; 16] {
530 self.seconds.to_be_bytes()
531 }
532
533 #[inline]
537 pub fn checked_add(self, rhs: impl Into<Self>) -> Option<Self> {
538 let rhs = rhs.into();
539 Some(Self {
540 seconds: self.seconds.checked_add(rhs.seconds)?,
541 })
542 }
543
544 #[inline]
548 pub fn checked_sub(self, rhs: impl Into<Self>) -> Option<Self> {
549 let rhs = rhs.into();
550 Some(Self {
551 seconds: self.seconds.checked_sub(rhs.seconds)?,
552 })
553 }
554
555 #[inline]
559 pub fn checked_neg(self) -> Option<Self> {
560 Some(Self {
561 seconds: self.seconds.checked_neg()?,
562 })
563 }
564
565 #[inline]
567 pub fn is_identical_with(self, other: Self) -> bool {
568 self == other
569 }
570}
571
572impl From<DayTimeDuration> for Duration {
573 #[inline]
574 fn from(value: DayTimeDuration) -> Self {
575 Self {
576 year_month: YearMonthDuration::default(),
577 day_time: value,
578 }
579 }
580}
581
582impl TryFrom<Duration> for DayTimeDuration {
583 type Error = DurationOverflowError;
584
585 #[inline]
586 fn try_from(value: Duration) -> Result<Self, Self::Error> {
587 if value.year_month == YearMonthDuration::default() {
588 Ok(value.day_time)
589 } else {
590 Err(DurationOverflowError)
591 }
592 }
593}
594
595impl TryFrom<StdDuration> for DayTimeDuration {
596 type Error = DurationOverflowError;
597
598 #[inline]
599 fn try_from(value: StdDuration) -> Result<Self, Self::Error> {
600 Ok(Self {
601 seconds: Decimal::new(
602 i128::try_from(value.as_nanos()).map_err(|_| DurationOverflowError)?,
603 9,
604 )
605 .map_err(|_| DurationOverflowError)?,
606 })
607 }
608}
609
610impl TryFrom<DayTimeDuration> for StdDuration {
611 type Error = DurationOverflowError;
612
613 #[inline]
614 fn try_from(value: DayTimeDuration) -> Result<Self, Self::Error> {
615 if value.seconds.is_negative() {
616 return Err(DurationOverflowError);
617 }
618 let secs = value.seconds.checked_floor().ok_or(DurationOverflowError)?;
619 let nanos = value
620 .seconds
621 .checked_sub(secs)
622 .ok_or(DurationOverflowError)?
623 .checked_mul(1_000_000_000)
624 .ok_or(DurationOverflowError)?
625 .checked_floor()
626 .ok_or(DurationOverflowError)?;
627 Ok(Self::new(
628 secs.as_i128()
629 .try_into()
630 .map_err(|_| DurationOverflowError)?,
631 nanos
632 .as_i128()
633 .try_into()
634 .map_err(|_| DurationOverflowError)?,
635 ))
636 }
637}
638
639impl FromStr for DayTimeDuration {
640 type Err = ParseDurationError;
641
642 fn from_str(input: &str) -> Result<Self, Self::Err> {
643 let parts = ensure_complete(input, duration_parts)?;
644 if parts.year_month.is_some() {
645 return Err(Self::Err::msg(
646 "There must not be any year or month component in a dayTimeDuration",
647 ));
648 }
649 Ok(Self::new(
650 parts
651 .day_time
652 .ok_or(Self::Err::msg("No day or time values found"))?,
653 ))
654 }
655}
656
657impl fmt::Display for DayTimeDuration {
658 #[inline]
659 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
660 Duration::from(*self).fmt(f)
661 }
662}
663
664impl PartialEq<Duration> for DayTimeDuration {
665 #[inline]
666 fn eq(&self, other: &Duration) -> bool {
667 Duration::from(*self).eq(other)
668 }
669}
670
671impl PartialEq<DayTimeDuration> for Duration {
672 #[inline]
673 fn eq(&self, other: &DayTimeDuration) -> bool {
674 self.eq(&Self::from(*other))
675 }
676}
677
678impl PartialEq<YearMonthDuration> for DayTimeDuration {
679 #[inline]
680 fn eq(&self, other: &YearMonthDuration) -> bool {
681 Duration::from(*self).eq(&Duration::from(*other))
682 }
683}
684
685impl PartialEq<DayTimeDuration> for YearMonthDuration {
686 #[inline]
687 fn eq(&self, other: &DayTimeDuration) -> bool {
688 Duration::from(*self).eq(&Duration::from(*other))
689 }
690}
691
692impl PartialOrd<Duration> for DayTimeDuration {
693 #[inline]
694 fn partial_cmp(&self, other: &Duration) -> Option<Ordering> {
695 Duration::from(*self).partial_cmp(other)
696 }
697}
698
699impl PartialOrd<DayTimeDuration> for Duration {
700 #[inline]
701 fn partial_cmp(&self, other: &DayTimeDuration) -> Option<Ordering> {
702 self.partial_cmp(&Self::from(*other))
703 }
704}
705
706impl PartialOrd<YearMonthDuration> for DayTimeDuration {
707 #[inline]
708 fn partial_cmp(&self, other: &YearMonthDuration) -> Option<Ordering> {
709 Duration::from(*self).partial_cmp(&Duration::from(*other))
710 }
711}
712
713impl PartialOrd<DayTimeDuration> for YearMonthDuration {
714 #[inline]
715 fn partial_cmp(&self, other: &DayTimeDuration) -> Option<Ordering> {
716 Duration::from(*self).partial_cmp(&Duration::from(*other))
717 }
718}
719
720struct DurationParts {
731 year_month: Option<i64>,
732 day_time: Option<Decimal>,
733}
734
735fn duration_parts(input: &str) -> Result<(DurationParts, &str), ParseDurationError> {
736 const START: u32 = 0;
738 const AFTER_YEAR: u32 = 1;
739 const AFTER_MONTH: u32 = 2;
740 const AFTER_DAY: u32 = 3;
741 const AFTER_T: u32 = 4;
742 const AFTER_HOUR: u32 = 5;
743 const AFTER_MINUTE: u32 = 6;
744 const AFTER_SECOND: u32 = 7;
745
746 let (is_negative, input) = if let Some(left) = input.strip_prefix('-') {
747 (true, left)
748 } else {
749 (false, input)
750 };
751 let mut input = expect_char(input, 'P', "Durations must start with 'P'")?;
752 let mut state = START;
753 let mut year_month: Option<i64> = None;
754 let mut day_time: Option<Decimal> = None;
755 while !input.is_empty() {
756 if let Some(left) = input.strip_prefix('T') {
757 if state >= AFTER_T {
758 return Err(ParseDurationError::msg("Duplicated time separator 'T'"));
759 }
760 state = AFTER_T;
761 input = left;
762 } else {
763 let (number_str, left) = decimal_prefix(input);
764 match left.chars().next() {
765 Some('Y') if state < AFTER_YEAR => {
766 year_month = Some(
767 year_month
768 .unwrap_or_default()
769 .checked_add(
770 apply_i64_neg(
771 i64::from_str(number_str).map_err(|_| OVERFLOW_ERROR)?,
772 is_negative,
773 )?
774 .checked_mul(12)
775 .ok_or(OVERFLOW_ERROR)?,
776 )
777 .ok_or(OVERFLOW_ERROR)?,
778 );
779 state = AFTER_YEAR;
780 }
781 Some('M') if state < AFTER_MONTH => {
782 year_month = Some(
783 year_month
784 .unwrap_or_default()
785 .checked_add(apply_i64_neg(
786 i64::from_str(number_str).map_err(|_| OVERFLOW_ERROR)?,
787 is_negative,
788 )?)
789 .ok_or(OVERFLOW_ERROR)?,
790 );
791 state = AFTER_MONTH;
792 }
793 Some('D') if state < AFTER_DAY => {
794 if number_str.contains('.') {
795 return Err(ParseDurationError::msg(
796 "Decimal numbers are not allowed for days",
797 ));
798 }
799 day_time = Some(
800 day_time
801 .unwrap_or_default()
802 .checked_add(
803 apply_decimal_neg(
804 Decimal::from_str(number_str).map_err(|_| OVERFLOW_ERROR)?,
805 is_negative,
806 )?
807 .checked_mul(86400)
808 .ok_or(OVERFLOW_ERROR)?,
809 )
810 .ok_or(OVERFLOW_ERROR)?,
811 );
812 state = AFTER_DAY;
813 }
814 Some('H') if state == AFTER_T => {
815 if number_str.contains('.') {
816 return Err(ParseDurationError::msg(
817 "Decimal numbers are not allowed for hours",
818 ));
819 }
820 day_time = Some(
821 day_time
822 .unwrap_or_default()
823 .checked_add(
824 apply_decimal_neg(
825 Decimal::from_str(number_str).map_err(|_| OVERFLOW_ERROR)?,
826 is_negative,
827 )?
828 .checked_mul(3600)
829 .ok_or(OVERFLOW_ERROR)?,
830 )
831 .ok_or(OVERFLOW_ERROR)?,
832 );
833 state = AFTER_HOUR;
834 }
835 Some('M') if (AFTER_T..AFTER_MINUTE).contains(&state) => {
836 if number_str.contains('.') {
837 return Err(ParseDurationError::msg(
838 "Decimal numbers are not allowed for minutes",
839 ));
840 }
841 day_time = Some(
842 day_time
843 .unwrap_or_default()
844 .checked_add(
845 apply_decimal_neg(
846 Decimal::from_str(number_str).map_err(|_| OVERFLOW_ERROR)?,
847 is_negative,
848 )?
849 .checked_mul(60)
850 .ok_or(OVERFLOW_ERROR)?,
851 )
852 .ok_or(OVERFLOW_ERROR)?,
853 );
854 state = AFTER_MINUTE;
855 }
856 Some('S') if (AFTER_T..AFTER_SECOND).contains(&state) => {
857 day_time = Some(
858 day_time
859 .unwrap_or_default()
860 .checked_add(apply_decimal_neg(
861 Decimal::from_str(number_str).map_err(|_| OVERFLOW_ERROR)?,
862 is_negative,
863 )?)
864 .ok_or(OVERFLOW_ERROR)?,
865 );
866 state = AFTER_SECOND;
867 }
868 Some(_) => return Err(ParseDurationError::msg("Unexpected type character")),
869 None => {
870 return Err(ParseDurationError::msg(
871 "Numbers in durations must be followed by a type character",
872 ))
873 }
874 }
875 input = &left[1..];
876 }
877 }
878
879 Ok((
880 DurationParts {
881 year_month,
882 day_time,
883 },
884 input,
885 ))
886}
887
888fn apply_i64_neg(value: i64, is_negative: bool) -> Result<i64, ParseDurationError> {
889 if is_negative {
890 value.checked_neg().ok_or(OVERFLOW_ERROR)
891 } else {
892 Ok(value)
893 }
894}
895
896fn apply_decimal_neg(value: Decimal, is_negative: bool) -> Result<Decimal, ParseDurationError> {
897 if is_negative {
898 value.checked_neg().ok_or(OVERFLOW_ERROR)
899 } else {
900 Ok(value)
901 }
902}
903
904fn ensure_complete<T>(
905 input: &str,
906 parse: impl FnOnce(&str) -> Result<(T, &str), ParseDurationError>,
907) -> Result<T, ParseDurationError> {
908 let (result, left) = parse(input)?;
909 if !left.is_empty() {
910 return Err(ParseDurationError::msg("Unrecognized value suffix"));
911 }
912 Ok(result)
913}
914
915fn expect_char<'a>(
916 input: &'a str,
917 constant: char,
918 error_message: &'static str,
919) -> Result<&'a str, ParseDurationError> {
920 if let Some(left) = input.strip_prefix(constant) {
921 Ok(left)
922 } else {
923 Err(ParseDurationError::msg(error_message))
924 }
925}
926
927fn decimal_prefix(input: &str) -> (&str, &str) {
928 let mut end = input.len();
929 let mut dot_seen = false;
930 for (i, c) in input.char_indices() {
931 if c.is_ascii_digit() {
932 } else if c == '.' && !dot_seen {
934 dot_seen = true;
935 } else {
936 end = i;
937 break;
938 }
939 }
940 input.split_at(end)
941}
942
943#[derive(Debug, Clone, thiserror::Error)]
945#[error("{msg}")]
946pub struct ParseDurationError {
947 msg: &'static str,
948}
949
950const OVERFLOW_ERROR: ParseDurationError = ParseDurationError {
951 msg: "Overflow error",
952};
953
954impl ParseDurationError {
955 const fn msg(msg: &'static str) -> Self {
956 Self { msg }
957 }
958}
959
960#[derive(Debug, Clone, Copy, thiserror::Error)]
964#[error("overflow during xsd:duration computation")]
965pub struct DurationOverflowError;
966
967#[derive(Debug, Clone, Copy, thiserror::Error)]
969#[error("The xsd:yearMonthDuration and xsd:dayTimeDuration components of a xsd:duration can't have opposite sign")]
970pub struct OppositeSignInDurationComponentsError;
971
972impl From<OppositeSignInDurationComponentsError> for ParseDurationError {
973 #[inline]
974 fn from(_: OppositeSignInDurationComponentsError) -> Self {
975 Self {
976 msg: "The xsd:yearMonthDuration and xsd:dayTimeDuration components of a xsd:duration can't have opposite sign"
977 }
978 }
979}
980
981#[cfg(test)]
982#[allow(clippy::panic_in_result_fn)]
983mod tests {
984 use super::*;
985 use std::error::Error;
986
987 #[test]
988 fn from_str() -> Result<(), ParseDurationError> {
989 let min = Duration::new(i64::MIN, Decimal::MIN)?;
990 let max = Duration::new(i64::MAX, Decimal::MAX)?;
991
992 assert_eq!(YearMonthDuration::from_str("P1Y")?.to_string(), "P1Y");
993 assert_eq!(Duration::from_str("P1Y")?.to_string(), "P1Y");
994 assert_eq!(YearMonthDuration::from_str("P1M")?.to_string(), "P1M");
995 assert_eq!(Duration::from_str("P1M")?.to_string(), "P1M");
996 assert_eq!(DayTimeDuration::from_str("P1D")?.to_string(), "P1D");
997 assert_eq!(Duration::from_str("P1D")?.to_string(), "P1D");
998 assert_eq!(DayTimeDuration::from_str("PT1H")?.to_string(), "PT1H");
999 assert_eq!(Duration::from_str("PT1H")?.to_string(), "PT1H");
1000 assert_eq!(DayTimeDuration::from_str("PT1M")?.to_string(), "PT1M");
1001 assert_eq!(Duration::from_str("PT1M")?.to_string(), "PT1M");
1002 assert_eq!(DayTimeDuration::from_str("PT1.1S")?.to_string(), "PT1.1S");
1003 assert_eq!(Duration::from_str("PT1.1S")?.to_string(), "PT1.1S");
1004 assert_eq!(YearMonthDuration::from_str("-P1Y")?.to_string(), "-P1Y");
1005 assert_eq!(Duration::from_str("-P1Y")?.to_string(), "-P1Y");
1006 assert_eq!(YearMonthDuration::from_str("-P1M")?.to_string(), "-P1M");
1007 assert_eq!(Duration::from_str("-P1M")?.to_string(), "-P1M");
1008 assert_eq!(DayTimeDuration::from_str("-P1D")?.to_string(), "-P1D");
1009 assert_eq!(Duration::from_str("-P1D")?.to_string(), "-P1D");
1010 assert_eq!(DayTimeDuration::from_str("-PT1H")?.to_string(), "-PT1H");
1011 assert_eq!(Duration::from_str("-PT1H")?.to_string(), "-PT1H");
1012 assert_eq!(DayTimeDuration::from_str("-PT1M")?.to_string(), "-PT1M");
1013 assert_eq!(Duration::from_str("-PT1M")?.to_string(), "-PT1M");
1014 assert_eq!(DayTimeDuration::from_str("-PT1S")?.to_string(), "-PT1S");
1015 assert_eq!(Duration::from_str("-PT1S")?.to_string(), "-PT1S");
1016 assert_eq!(DayTimeDuration::from_str("-PT1.1S")?.to_string(), "-PT1.1S");
1017 assert_eq!(Duration::from_str("-PT1.1S")?.to_string(), "-PT1.1S");
1018 assert_eq!(Duration::from_str(&max.to_string())?, max);
1019 assert_eq!(Duration::from_str(&min.to_string())?, min);
1020 assert_eq!(Duration::from_str("PT0H")?.to_string(), "PT0S");
1021 assert_eq!(Duration::from_str("-PT0H")?.to_string(), "PT0S");
1022 assert_eq!(YearMonthDuration::from_str("P0Y")?.to_string(), "P0M");
1023 assert_eq!(DayTimeDuration::from_str("PT0H")?.to_string(), "PT0S");
1024 Ok(())
1025 }
1026
1027 #[test]
1028 fn from_std() -> Result<(), DurationOverflowError> {
1029 assert_eq!(
1030 Duration::try_from(StdDuration::new(10, 10))?.to_string(),
1031 "PT10.00000001S"
1032 );
1033 Ok(())
1034 }
1035
1036 #[test]
1037 fn to_std() -> Result<(), Box<dyn Error>> {
1038 let duration = StdDuration::try_from(DayTimeDuration::from_str("PT10.00000001S")?)?;
1039 assert_eq!(duration.as_secs(), 10);
1040 assert_eq!(duration.subsec_nanos(), 10);
1041 Ok(())
1042 }
1043
1044 #[test]
1045 fn to_be_bytes() {
1046 assert_eq!(
1047 Duration::from_be_bytes(Duration::MIN.to_be_bytes()),
1048 Duration::MIN
1049 );
1050 assert_eq!(
1051 Duration::from_be_bytes(Duration::MAX.to_be_bytes()),
1052 Duration::MAX
1053 );
1054 assert_eq!(
1055 YearMonthDuration::from_be_bytes(YearMonthDuration::MIN.to_be_bytes()),
1056 YearMonthDuration::MIN
1057 );
1058 assert_eq!(
1059 YearMonthDuration::from_be_bytes(YearMonthDuration::MAX.to_be_bytes()),
1060 YearMonthDuration::MAX
1061 );
1062 assert_eq!(
1063 DayTimeDuration::from_be_bytes(DayTimeDuration::MIN.to_be_bytes()),
1064 DayTimeDuration::MIN
1065 );
1066 assert_eq!(
1067 DayTimeDuration::from_be_bytes(DayTimeDuration::MAX.to_be_bytes()),
1068 DayTimeDuration::MAX
1069 );
1070 }
1071
1072 #[test]
1073 fn equals() -> Result<(), ParseDurationError> {
1074 assert_eq!(
1075 YearMonthDuration::from_str("P1Y")?,
1076 YearMonthDuration::from_str("P12M")?
1077 );
1078 assert_eq!(
1079 YearMonthDuration::from_str("P1Y")?,
1080 Duration::from_str("P12M")?
1081 );
1082 assert_eq!(
1083 Duration::from_str("P1Y")?,
1084 YearMonthDuration::from_str("P12M")?
1085 );
1086 assert_eq!(Duration::from_str("P1Y")?, Duration::from_str("P12M")?);
1087 assert_eq!(
1088 DayTimeDuration::from_str("PT24H")?,
1089 DayTimeDuration::from_str("P1D")?
1090 );
1091 assert_eq!(
1092 DayTimeDuration::from_str("PT24H")?,
1093 Duration::from_str("P1D")?
1094 );
1095 assert_eq!(
1096 Duration::from_str("PT24H")?,
1097 DayTimeDuration::from_str("P1D")?
1098 );
1099 assert_eq!(Duration::from_str("PT24H")?, Duration::from_str("P1D")?);
1100 assert_ne!(Duration::from_str("P1Y")?, Duration::from_str("P365D")?);
1101 assert_eq!(Duration::from_str("P0Y")?, Duration::from_str("P0D")?);
1102 assert_ne!(Duration::from_str("P1Y")?, Duration::from_str("P365D")?);
1103 assert_eq!(Duration::from_str("P2Y")?, Duration::from_str("P24M")?);
1104 assert_eq!(Duration::from_str("P10D")?, Duration::from_str("PT240H")?);
1105 assert_eq!(
1106 Duration::from_str("P2Y0M0DT0H0M0S")?,
1107 Duration::from_str("P24M")?
1108 );
1109 assert_eq!(
1110 Duration::from_str("P0Y0M10D")?,
1111 Duration::from_str("PT240H")?
1112 );
1113 assert_ne!(Duration::from_str("P1M")?, Duration::from_str("P30D")?);
1114 Ok(())
1115 }
1116
1117 #[test]
1118 #[allow(clippy::neg_cmp_op_on_partial_ord)]
1119 fn cmp() -> Result<(), ParseDurationError> {
1120 assert!(Duration::from_str("P1Y1D")? < Duration::from_str("P13MT25H")?);
1121 assert!(YearMonthDuration::from_str("P1Y")? < YearMonthDuration::from_str("P13M")?);
1122 assert!(Duration::from_str("P1Y")? < YearMonthDuration::from_str("P13M")?);
1123 assert!(YearMonthDuration::from_str("P1Y")? < Duration::from_str("P13M")?);
1124 assert!(DayTimeDuration::from_str("P1D")? < DayTimeDuration::from_str("PT25H")?);
1125 assert!(DayTimeDuration::from_str("PT1H")? < DayTimeDuration::from_str("PT61M")?);
1126 assert!(DayTimeDuration::from_str("PT1M")? < DayTimeDuration::from_str("PT61S")?);
1127 assert!(Duration::from_str("PT1H")? < DayTimeDuration::from_str("PT61M")?);
1128 assert!(DayTimeDuration::from_str("PT1H")? < Duration::from_str("PT61M")?);
1129 assert!(YearMonthDuration::from_str("P1M")? < DayTimeDuration::from_str("P40D")?);
1130 assert!(DayTimeDuration::from_str("P25D")? < YearMonthDuration::from_str("P1M")?);
1131 Ok(())
1132 }
1133
1134 #[test]
1135 fn years() -> Result<(), ParseDurationError> {
1136 assert_eq!(Duration::from_str("P20Y15M")?.years(), 21);
1137 assert_eq!(Duration::from_str("-P15M")?.years(), -1);
1138 assert_eq!(Duration::from_str("-P2DT15H")?.years(), 0);
1139 Ok(())
1140 }
1141
1142 #[test]
1143 fn months() -> Result<(), ParseDurationError> {
1144 assert_eq!(Duration::from_str("P20Y15M")?.months(), 3);
1145 assert_eq!(Duration::from_str("-P20Y18M")?.months(), -6);
1146 assert_eq!(Duration::from_str("-P2DT15H0M0S")?.months(), 0);
1147 Ok(())
1148 }
1149
1150 #[test]
1151 fn days() -> Result<(), ParseDurationError> {
1152 assert_eq!(Duration::from_str("P3DT10H")?.days(), 3);
1153 assert_eq!(Duration::from_str("P3DT55H")?.days(), 5);
1154 assert_eq!(Duration::from_str("P3Y5M")?.days(), 0);
1155 Ok(())
1156 }
1157
1158 #[test]
1159 fn hours() -> Result<(), ParseDurationError> {
1160 assert_eq!(Duration::from_str("P3DT10H")?.hours(), 10);
1161 assert_eq!(Duration::from_str("P3DT12H32M12S")?.hours(), 12);
1162 assert_eq!(Duration::from_str("PT123H")?.hours(), 3);
1163 assert_eq!(Duration::from_str("-P3DT10H")?.hours(), -10);
1164 Ok(())
1165 }
1166
1167 #[test]
1168 fn minutes() -> Result<(), ParseDurationError> {
1169 assert_eq!(Duration::from_str("P3DT10H")?.minutes(), 0);
1170 assert_eq!(Duration::from_str("-P5DT12H30M")?.minutes(), -30);
1171 Ok(())
1172 }
1173
1174 #[test]
1175 fn seconds() -> Result<(), Box<dyn Error>> {
1176 assert_eq!(
1177 Duration::from_str("P3DT10H12.5S")?.seconds(),
1178 Decimal::from_str("12.5")?
1179 );
1180 assert_eq!(
1181 Duration::from_str("-PT256S")?.seconds(),
1182 Decimal::from_str("-16.0")?
1183 );
1184 Ok(())
1185 }
1186
1187 #[test]
1188 fn add() -> Result<(), ParseDurationError> {
1189 assert_eq!(
1190 Duration::from_str("P2Y11M")?.checked_add(Duration::from_str("P3Y3M")?),
1191 Some(Duration::from_str("P6Y2M")?)
1192 );
1193 assert_eq!(
1194 Duration::from_str("P2DT12H5M")?.checked_add(Duration::from_str("P5DT12H")?),
1195 Some(Duration::from_str("P8DT5M")?)
1196 );
1197 assert_eq!(
1198 Duration::from_str("P1M2D")?.checked_add(Duration::from_str("-P3D")?),
1199 None
1200 );
1201 assert_eq!(
1202 Duration::from_str("P1M2D")?.checked_add(Duration::from_str("-P2M")?),
1203 None
1204 );
1205 Ok(())
1206 }
1207
1208 #[test]
1209 fn sub() -> Result<(), ParseDurationError> {
1210 assert_eq!(
1211 Duration::from_str("P2Y11M")?.checked_sub(Duration::from_str("P3Y3M")?),
1212 Some(Duration::from_str("-P4M")?)
1213 );
1214 assert_eq!(
1215 Duration::from_str("P2DT12H")?.checked_sub(Duration::from_str("P1DT10H30M")?),
1216 Some(Duration::from_str("P1DT1H30M")?)
1217 );
1218 assert_eq!(
1219 Duration::from_str("P1M2D")?.checked_sub(Duration::from_str("P3D")?),
1220 None
1221 );
1222 assert_eq!(
1223 Duration::from_str("P1M2D")?.checked_sub(Duration::from_str("P2M")?),
1224 None
1225 );
1226 Ok(())
1227 }
1228
1229 #[test]
1230 fn minimally_conformant() -> Result<(), ParseDurationError> {
1231 assert_eq!(Duration::from_str("PT0.001S")?.to_string(), "PT0.001S");
1234 assert_eq!(Duration::from_str("-PT0.001S")?.to_string(), "-PT0.001S");
1235
1236 assert_eq!(
1240 Duration::from_str("P119999MT31622400S")?.to_string(),
1241 "P9999Y11M366D"
1242 );
1243 assert_eq!(
1244 Duration::from_str("-P119999MT31622400S")?.to_string(),
1245 "-P9999Y11M366D"
1246 );
1247 Ok(())
1248 }
1249}