Skip to content

Commit

Permalink
Implement CandidType for std::time::Duration (#133)
Browse files Browse the repository at this point in the history
  • Loading branch information
osa1 authored Nov 5, 2020
1 parent 03773cc commit a6a413d
Showing 1 changed file with 45 additions and 0 deletions.
45 changes: 45 additions & 0 deletions rust/candid/src/types/impls.rs
Original file line number Diff line number Diff line change
Expand Up @@ -300,6 +300,39 @@ impl CandidType for std::time::SystemTime {
}
}

impl CandidType for std::time::Duration {
fn id() -> TypeId {
TypeId::of::<std::time::Duration>()
}

fn _ty() -> Type {
Type::Record(vec![
Field {
id: Label::Named("secs".to_owned()),
ty: u64::ty(),
},
Field {
id: Label::Named("nanos".to_owned()),
ty: u32::ty(),
},
])
}

fn idl_serialize<S>(&self, serializer: S) -> Result<(), S::Error>
where
S: Serializer,
{
let secs: u64 = self.as_secs();
let nanos: u32 = self.subsec_nanos();

let mut ser = serializer.serialize_struct()?;
ser.serialize_element(&secs)?;
ser.serialize_element(&nanos)?;

Ok(())
}
}

#[test]
fn test_systemtime() {
use crate::{Decode, Encode};
Expand All @@ -309,3 +342,15 @@ fn test_systemtime() {
let decoded = Decode!(&encoded, std::time::SystemTime).unwrap();
assert_eq!(now, decoded);
}

#[test]
fn test_duration() {
use crate::{Decode, Encode};
use std::time::{Duration, SystemTime};

let now = SystemTime::now();
let duration = now.duration_since(SystemTime::UNIX_EPOCH).unwrap();
let encoded = Encode!(&duration).unwrap();
let decoded = Decode!(&encoded, Duration).unwrap();
assert_eq!(duration, decoded);
}

0 comments on commit a6a413d

Please sign in to comment.