Add method to create Asn1Time from time_t value

This is mostly just a rework of the earlier work done by @illegalprime
in his PR #673 and credit should go to him.
This commit is contained in:
Brian Olsen 2019-10-10 18:33:47 +02:00
parent 14a6a98ebf
commit 80e0dd03ba
No known key found for this signature in database
GPG Key ID: 029DD8E8B95882E8
2 changed files with 18 additions and 1 deletions

View File

@ -43,6 +43,7 @@ extern "C" {
pub fn ASN1_TIME_diff(pday: *mut c_int, psec: *mut c_int, from: *const ASN1_TIME, to: *const ASN1_TIME) -> c_int; pub fn ASN1_TIME_diff(pday: *mut c_int, psec: *mut c_int, from: *const ASN1_TIME, to: *const ASN1_TIME) -> c_int;
pub fn ASN1_TIME_free(tm: *mut ASN1_TIME); pub fn ASN1_TIME_free(tm: *mut ASN1_TIME);
pub fn ASN1_TIME_print(b: *mut BIO, tm: *const ASN1_TIME) -> c_int; pub fn ASN1_TIME_print(b: *mut BIO, tm: *const ASN1_TIME) -> c_int;
pub fn ASN1_TIME_set(from: *mut ASN1_TIME, to: time_t) -> *mut ASN1_TIME;
pub fn ASN1_INTEGER_free(x: *mut ASN1_INTEGER); pub fn ASN1_INTEGER_free(x: *mut ASN1_INTEGER);
pub fn ASN1_INTEGER_get(dest: *const ASN1_INTEGER) -> c_long; pub fn ASN1_INTEGER_get(dest: *const ASN1_INTEGER) -> c_long;

View File

@ -26,7 +26,7 @@
//! ``` //! ```
use ffi; use ffi;
use foreign_types::{ForeignType, ForeignTypeRef}; use foreign_types::{ForeignType, ForeignTypeRef};
use libc::{c_char, c_int, c_long}; use libc::{c_char, c_int, c_long, time_t};
#[cfg(ossl102)] #[cfg(ossl102)]
use std::cmp::Ordering; use std::cmp::Ordering;
use std::ffi::CString; use std::ffi::CString;
@ -237,6 +237,16 @@ impl Asn1Time {
Asn1Time::from_period(days as c_long * 60 * 60 * 24) Asn1Time::from_period(days as c_long * 60 * 60 * 24)
} }
/// Creates a new time from the specified `time_t` value
pub fn from_unix(time: time_t) -> Result<Asn1Time, ErrorStack> {
ffi::init();
unsafe {
let handle = cvt_p(ffi::ASN1_TIME_set(ptr::null_mut(), time))?;
Ok(Asn1Time::from_ptr(handle))
}
}
/// Creates a new time corresponding to the specified ASN1 time string. /// Creates a new time corresponding to the specified ASN1 time string.
/// ///
/// This corresponds to [`ASN1_TIME_set_string`]. /// This corresponds to [`ASN1_TIME_set_string`].
@ -542,6 +552,12 @@ mod tests {
Asn1Time::from_str_x509("99991231235959Z").unwrap(); Asn1Time::from_str_x509("99991231235959Z").unwrap();
} }
#[test]
fn time_from_unix() {
let t = Asn1Time::from_unix(0).unwrap();
assert_eq!("Jan 1 00:00:00 1970 GMT", t.to_string());
}
#[test] #[test]
#[cfg(ossl102)] #[cfg(ossl102)]
fn time_eq() { fn time_eq() {