Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Export functions for creating Timepoint/Duration #1201

Merged
merged 5 commits into from
Jan 17, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 16 additions & 10 deletions soroban-sdk/src/num.rs
Original file line number Diff line number Diff line change
Expand Up @@ -459,15 +459,19 @@ pub struct Timepoint {
impl_num_wrapping_val_type!(Timepoint, TimepointVal, TimepointSmall);

impl Timepoint {
fn from_u64(env: &Env, u: u64) -> Timepoint {
let val = TimepointVal::try_from_val(env, &u).unwrap_optimized();
/// Create a Timepoint from a unix time in seconds, the time in seconds
/// since January 1, 1970 UTC.
pub fn from_unix(env: &Env, seconds: u64) -> Timepoint {
let val = TimepointVal::try_from_val(env, &seconds).unwrap_optimized();
Timepoint {
env: env.clone(),
val,
}
}

fn to_u64(&self) -> u64 {
/// Returns the Timepoint as unix time in seconds, the time in seconds since
/// January 1, 1970 UTC.
pub fn to_unix(&self) -> u64 {
u64::try_from_val(self.env(), &self.to_val_type()).unwrap_optimized()
}
}
Expand All @@ -482,15 +486,17 @@ pub struct Duration {
impl_num_wrapping_val_type!(Duration, DurationVal, DurationSmall);

impl Duration {
fn from_u64(env: &Env, u: u64) -> Duration {
let val = DurationVal::try_from_val(env, &u).unwrap_optimized();
/// Create a Duration from seconds.
pub fn from_seconds(env: &Env, seconds: u64) -> Duration {
let val = DurationVal::try_from_val(env, &seconds).unwrap_optimized();
Duration {
env: env.clone(),
val,
}
}

fn to_u64(&self) -> u64 {
/// Returns the Duration as seconds.
pub fn to_seconds(&self) -> u64 {
u64::try_from_val(self.env(), &self.to_val_type()).unwrap_optimized()
}
}
Expand Down Expand Up @@ -575,17 +581,17 @@ mod test {
fn test_timepoint_roundtrip() {
let env = Env::default();

let tp = Timepoint::from_u64(&env, 123);
let u = tp.to_u64();
let tp = Timepoint::from_unix(&env, 123);
let u = tp.to_unix();
assert_eq!(u, 123);
}

#[test]
fn test_duration_roundtrip() {
let env = Env::default();

let tp = Duration::from_u64(&env, 123);
let u = tp.to_u64();
let tp = Duration::from_seconds(&env, 123);
let u = tp.to_seconds();
assert_eq!(u, 123);
}

Expand Down