Skip to content

Commit ee30600

Browse files
authored
x509-cert: impl FromStr for x509-cert::time::Time (#1961)
1 parent 657ef97 commit ee30600

File tree

1 file changed

+43
-1
lines changed

1 file changed

+43
-1
lines changed

x509-cert/src/time.rs

Lines changed: 43 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
//! X.501 time types as defined in RFC 5280
22
3-
use core::{fmt, marker::PhantomData, time::Duration};
3+
use core::{fmt, marker::PhantomData, str::FromStr, time::Duration};
44
use der::asn1::{GeneralizedTime, UtcTime};
55
use der::{Choice, DateTime, DecodeValue, Encode, Header, Length, Reader, Sequence, ValueOrd};
66

@@ -105,6 +105,24 @@ impl From<GeneralizedTime> for Time {
105105
}
106106
}
107107

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+
108126
#[cfg(feature = "std")]
109127
impl From<Time> for SystemTime {
110128
fn from(time: Time) -> SystemTime {
@@ -221,3 +239,27 @@ impl<P: Profile> ::der::EncodeValue for Validity<P> {
221239
}
222240

223241
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

Comments
 (0)