|
1 | 1 | //! X.501 time types as defined in RFC 5280
|
2 | 2 |
|
3 |
| -use core::{fmt, marker::PhantomData, time::Duration}; |
| 3 | +use core::{fmt, marker::PhantomData, str::FromStr, time::Duration}; |
4 | 4 | use der::asn1::{GeneralizedTime, UtcTime};
|
5 | 5 | use der::{Choice, DateTime, DecodeValue, Encode, Header, Length, Reader, Sequence, ValueOrd};
|
6 | 6 |
|
@@ -105,6 +105,24 @@ impl From<GeneralizedTime> for Time {
|
105 | 105 | }
|
106 | 106 | }
|
107 | 107 |
|
| 108 | +impl From<DateTime> for Time { |
| 109 | + fn from(time: DateTime) -> Time { |
| 110 | + UtcTime::from_date_time(time) |
| 111 | + .map(Self::UtcTime) |
| 112 | + .unwrap_or_else(|_e| Self::GeneralTime(GeneralizedTime::from_date_time(time))) |
| 113 | + } |
| 114 | +} |
| 115 | + |
| 116 | +impl FromStr for Time { |
| 117 | + type Err = der::Error; |
| 118 | + |
| 119 | + fn from_str(input: &str) -> der::Result<Self> { |
| 120 | + let datetime = DateTime::from_str(input)?; |
| 121 | + |
| 122 | + Ok(Self::from(datetime)) |
| 123 | + } |
| 124 | +} |
| 125 | + |
108 | 126 | #[cfg(feature = "std")]
|
109 | 127 | impl From<Time> for SystemTime {
|
110 | 128 | fn from(time: Time) -> SystemTime {
|
@@ -221,3 +239,27 @@ impl<P: Profile> ::der::EncodeValue for Validity<P> {
|
221 | 239 | }
|
222 | 240 |
|
223 | 241 | impl<P: Profile> Sequence<'_> for Validity<P> {}
|
| 242 | + |
| 243 | +#[cfg(test)] |
| 244 | +mod tests { |
| 245 | + use super::*; |
| 246 | + |
| 247 | + #[test] |
| 248 | + fn parse_time() { |
| 249 | + let time = Time::from_str("1970-01-01T00:00:00Z").expect("parse date from string"); |
| 250 | + assert!(matches!(time, Time::UtcTime(_))); |
| 251 | + assert_eq!(alloc::format!("{}", time), "1970-01-01T00:00:00Z"); |
| 252 | + |
| 253 | + let time = Time::from_str("2020-01-01T00:00:00Z").expect("parse date from string"); |
| 254 | + assert!(matches!(time, Time::UtcTime(_))); |
| 255 | + assert_eq!(alloc::format!("{}", time), "2020-01-01T00:00:00Z"); |
| 256 | + |
| 257 | + let time = Time::from_str("2049-12-31T23:59:59Z").expect("parse date from string"); |
| 258 | + assert!(matches!(time, Time::UtcTime(_))); |
| 259 | + assert_eq!(alloc::format!("{}", time), "2049-12-31T23:59:59Z"); |
| 260 | + |
| 261 | + let time = Time::from_str("2050-01-01T00:00:00Z").expect("parse date from string"); |
| 262 | + assert!(matches!(time, Time::GeneralTime(_))); |
| 263 | + assert_eq!(alloc::format!("{}", time), "2050-01-01T00:00:00Z"); |
| 264 | + } |
| 265 | +} |
0 commit comments