Skip to content

Commit

Permalink
Add UnixTime type
Browse files Browse the repository at this point in the history
  • Loading branch information
djc committed Sep 12, 2023
1 parent 0f3121a commit b130ee5
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 1 deletion.
1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ categories = ["network-programming", "data-structures", "cryptography"]
[features]
default = ["alloc"]
alloc = []
std = ["alloc"]

[package.metadata.docs.rs]
all-features = true
Expand Down
36 changes: 35 additions & 1 deletion src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@
//! This crate does not provide any functionality for creating new certificates or keys. However,
//! the [rcgen](https://docs.rs/rcgen) crate can be used to create new certificates and keys.
#![no_std]
#![cfg_attr(not(feature = "std"), no_std)]
#![warn(unreachable_pub, clippy::use_self)]
#![deny(missing_docs)]
#![cfg_attr(docsrs, feature(doc_cfg, doc_auto_cfg))]
Expand All @@ -38,6 +38,9 @@ extern crate alloc;
use alloc::vec::Vec;
use core::fmt;
use core::ops::Deref;
use core::time::Duration;
#[cfg(feature = "std")]
use std::time::SystemTime;

/// A DER-encoded X.509 private key, in one of several formats
///
Expand Down Expand Up @@ -210,6 +213,7 @@ impl TrustAnchor<'_> {
/// Yield a `'static` lifetime of the `TrustAnchor` by allocating owned `Der` variants
#[cfg(feature = "alloc")]
pub fn to_owned(&self) -> TrustAnchor<'static> {
#[cfg(not(feature = "std"))]
use alloc::borrow::ToOwned;
TrustAnchor {
subject: self.subject.as_ref().to_owned().into(),
Expand Down Expand Up @@ -391,6 +395,36 @@ impl Deref for AlgorithmIdentifier {
}
}

/// A timestamp, tracking the number of non-leap seconds since the Unix epoch.
///
/// The Unix epoch is defined January 1, 1970 00:00:00 UTC.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd)]
pub struct UnixTime(u64);

impl UnixTime {
/// The current time, as a `UnixTime`
#[cfg(feature = "std")]
pub fn now() -> Self {
Self::since_unix_epoch(
SystemTime::now()
.duration_since(SystemTime::UNIX_EPOCH)
.unwrap(), // Safe: this code did not exist before 1970.
)
}

/// Convert a `Duration` since the start of 1970 to a `UnixTime`
///
/// The `duration` must be relative to the Unix epoch.
pub fn since_unix_epoch(duration: Duration) -> Self {
Self(duration.as_secs())
}

/// Number of seconds since the Unix epoch
pub fn as_secs(&self) -> u64 {
self.0
}
}

/// DER-encoded data, either owned or borrowed
///
/// This wrapper type is used to represent DER-encoded data in a way that is agnostic to whether
Expand Down

0 comments on commit b130ee5

Please sign in to comment.