Skip to main content

icu_capi/
datetime.rs

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#[diplomat::bridge]
6#[diplomat::abi_rename = "icu4x_{0}_mv1"]
7pub mod ffi {
8    use alloc::boxed::Box;
9    use icu_calendar::Iso;
10
11    use crate::unstable::calendar::ffi::Calendar;
12    use crate::unstable::date::ffi::{Date, IsoDate};
13    use crate::unstable::errors::ffi::Rfc9557ParseError;
14    use crate::unstable::time::ffi::Time;
15
16    /// An ICU4X DateTime object capable of containing a ISO-8601 date and time.
17    #[diplomat::rust_link(icu::time::DateTime, Struct)]
18    #[diplomat::out]
19    pub struct IsoDateTime {
20        pub date: Box<IsoDate>,
21        pub time: Box<Time>,
22    }
23
24    impl IsoDateTime {
25        /// Creates a new [`IsoDateTime`] from an IXDTF string.
26        #[diplomat::rust_link(icu::time::DateTime::try_from_str, FnInStruct)]
27        #[diplomat::rust_link(icu::time::DateTime::try_from_utf8, FnInStruct, hidden)]
28        #[diplomat::rust_link(icu::time::DateTime::from_str, FnInStruct, hidden)]
29        #[diplomat::attr(all(supports = fallible_constructors, supports = named_constructors), named_constructor)]
30        pub fn from_string(v: &DiplomatStr) -> Result<IsoDateTime, Rfc9557ParseError> {
31            let icu_time::DateTime { date, time } = icu_time::DateTime::try_from_utf8(v, Iso)?;
32            Ok(IsoDateTime {
33                date: Box::new(IsoDate(date)),
34                time: Box::new(Time(time)),
35            })
36        }
37    }
38
39    /// An ICU4X DateTime object capable of containing a date and time for any calendar.
40    #[diplomat::rust_link(icu::time::DateTime, Struct)]
41    #[diplomat::out]
42    pub struct DateTime {
43        pub date: Box<Date>,
44        pub time: Box<Time>,
45    }
46
47    impl DateTime {
48        /// Creates a new [`DateTime`] from an IXDTF string.
49        #[diplomat::rust_link(icu::time::DateTime::try_from_str, FnInStruct)]
50        #[diplomat::rust_link(icu::time::DateTime::try_from_utf8, FnInStruct, hidden)]
51        #[diplomat::rust_link(icu::time::DateTime::from_str, FnInStruct, hidden)]
52        #[diplomat::attr(all(supports = fallible_constructors, supports = named_constructors), named_constructor)]
53        pub fn from_string(
54            v: &DiplomatStr,
55            calendar: &Calendar,
56        ) -> Result<DateTime, Rfc9557ParseError> {
57            let icu_time::DateTime { date, time } =
58                icu_time::DateTime::try_from_utf8(v, calendar.0.clone())?;
59            Ok(DateTime {
60                date: Box::new(Date(date)),
61                time: Box::new(Time(time)),
62            })
63        }
64    }
65}