From 360da4f78448dc0b2c2724f5e13a12874604ce3e Mon Sep 17 00:00:00 2001 From: "Neal H. Walfield" Date: Mon, 14 Dec 2020 22:32:47 +0100 Subject: openpgp: Add Duration::years. - Add `Duration::years`. - This function assumes that there are 365.2425 days in a year, which is the average number of days in a year in the Gregorian calendar. --- openpgp/src/types/timestamp.rs | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/openpgp/src/types/timestamp.rs b/openpgp/src/types/timestamp.rs index 0852184b..4c630fca 100644 --- a/openpgp/src/types/timestamp.rs +++ b/openpgp/src/types/timestamp.rs @@ -375,6 +375,26 @@ impl Duration { n)).into()) } + /// Returns a `Duration` with the given number of years, if + /// representable. + /// + /// This function assumes that there are 365.2425 [days in a + /// year], the average number of days in a year in the Gregorian + /// calendar. + /// + /// [days in a year]: https://en.wikipedia.org/wiki/Year + pub fn years(n: u32) -> Result { + let s = (365.2425 * n as f64).trunc(); + if s > u32::MAX as f64 { + Err(Error::InvalidArgument( + format!("Not representable: {} years in seconds exceeds u32", + n)) + .into()) + } else { + Ok((s as u32).into()) + } + } + /// Returns the duration as seconds. pub fn as_secs(self) -> u64 { self.0 as u64 -- cgit v1.2.3