diff options
author | Neal H. Walfield <neal@pep.foundation> | 2020-12-14 22:32:47 +0100 |
---|---|---|
committer | Neal H. Walfield <neal@pep.foundation> | 2020-12-14 22:52:43 +0100 |
commit | 360da4f78448dc0b2c2724f5e13a12874604ce3e (patch) | |
tree | 1b29323e07d552c1b8dc8292a073ad482ea75daf /openpgp/src/types | |
parent | 02a3a4851ab7daf3cab1271f962972425a45c441 (diff) |
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.
Diffstat (limited to 'openpgp/src/types')
-rw-r--r-- | openpgp/src/types/timestamp.rs | 20 |
1 files changed, 20 insertions, 0 deletions
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<Duration> { + 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 |