Yiming Jing | 3690302 | 2021-07-16 12:51:10 -0700 | [diff] [blame] | 1 | // Copyright 2015-2016 Brian Smith. |
| 2 | // |
| 3 | // Permission to use, copy, modify, and/or distribute this software for any |
| 4 | // purpose with or without fee is hereby granted, provided that the above |
| 5 | // copyright notice and this permission notice appear in all copies. |
| 6 | // |
| 7 | // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHORS DISCLAIM ALL WARRANTIES |
| 8 | // WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF |
| 9 | // MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR |
| 10 | // ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES |
| 11 | // WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN |
| 12 | // ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF |
| 13 | // OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. |
| 14 | |
| 15 | //! Conversions into the library's time type. |
| 16 | |
| 17 | /// The time type. |
| 18 | /// |
| 19 | /// Internally this is merely a UNIX timestamp: a count of non-leap |
| 20 | /// seconds since the start of 1970. This type exists to assist |
| 21 | /// unit-of-measure correctness. |
| 22 | #[derive(Debug, Clone, Copy, PartialEq, PartialOrd)] |
| 23 | pub struct Time(u64); |
| 24 | |
| 25 | impl Time { |
| 26 | /// Create a `webpki::Time` from a unix timestamp. |
| 27 | /// |
| 28 | /// It is usually better to use the less error-prone |
| 29 | /// `webpki::Time::try_from(time: std::time::SystemTime)` instead when |
| 30 | /// `std::time::SystemTime` is available (when `#![no_std]` isn't being |
| 31 | /// used). |
| 32 | #[allow(clippy::must_use_candidate)] |
| 33 | pub fn from_seconds_since_unix_epoch(secs: u64) -> Self { |
| 34 | Self(secs) |
| 35 | } |
| 36 | } |
| 37 | |
| 38 | #[cfg(feature = "std")] |
| 39 | impl core::convert::TryFrom<std::time::SystemTime> for Time { |
| 40 | type Error = std::time::SystemTimeError; |
| 41 | |
| 42 | /// Create a `webpki::Time` from a `std::time::SystemTime`. |
| 43 | /// |
| 44 | /// # Example: |
| 45 | /// |
| 46 | /// Construct a `webpki::Time` from the current system time: |
| 47 | /// |
| 48 | /// ``` |
| 49 | /// # extern crate ring; |
| 50 | /// # extern crate webpki; |
| 51 | /// # |
| 52 | /// #![cfg(feature = "std")] |
| 53 | /// use std::{convert::TryFrom, time::{SystemTime, SystemTimeError}}; |
| 54 | /// |
| 55 | /// # fn foo() -> Result<(), SystemTimeError> { |
| 56 | /// let time = webpki::Time::try_from(SystemTime::now())?; |
| 57 | /// # Ok(()) |
| 58 | /// # } |
| 59 | /// ``` |
| 60 | fn try_from(value: std::time::SystemTime) -> Result<Self, Self::Error> { |
| 61 | value |
| 62 | .duration_since(std::time::UNIX_EPOCH) |
| 63 | .map(|d| Self::from_seconds_since_unix_epoch(d.as_secs())) |
| 64 | } |
| 65 | } |