Skip to content

Commit

Permalink
Tendermint: Added unix_timestamp and unix_timestamp_nanos method …
Browse files Browse the repository at this point in the history
…in Time struct. (#1176)

* Convert Time into unix timestamp

* Update .changelog/unreleased/improvements/1175-unix-timestamp-conversion.md

Co-authored-by: Thane Thomson <connect@thanethomson.com>
  • Loading branch information
scalalang2 and thanethomson authored Nov 7, 2022
1 parent 3c28657 commit d102af4
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
- `[tendermint]` Added `Time` methods `unix_timestamp` and `unix_timestamp_nanos`.
([#1175](https://github.com/informalsystems/tendermint-rs/issues/1175))
23 changes: 23 additions & 0 deletions tendermint/src/time.rs
Original file line number Diff line number Diff line change
Expand Up @@ -118,6 +118,16 @@ impl Time {
timestamp::to_rfc3339_nanos(self.0.assume_utc())
}

/// Return a Unix timestamp in seconds.
pub fn unix_timestamp(&self) -> i64 {
self.0.assume_utc().unix_timestamp()
}

/// Return a Unix timestamp in nanoseconds.
pub fn unix_timestamp_nanos(&self) -> i128 {
self.0.assume_utc().unix_timestamp_nanos()
}

/// Computes `self + duration`, returning `None` if an overflow occurred.
pub fn checked_add(self, duration: Duration) -> Option<Self> {
let duration = duration.try_into().ok()?;
Expand Down Expand Up @@ -278,6 +288,19 @@ mod tests {
prop_assert_eq!(time, decoded_time);
}

#[test]
fn conversion_unix_timestamp_is_safe(
stamp in prop_oneof![
pbt::time::arb_protobuf_safe_rfc3339_timestamp(),
particular_rfc3339_timestamps(),
]
) {
let time: Time = stamp.parse().unwrap();
let timestamp = time.unix_timestamp();
let parsed = Time::from_unix_timestamp(timestamp, 0).unwrap();
prop_assert_eq!(timestamp, parsed.unix_timestamp());
}

#[test]
fn conversion_from_datetime_succeeds_for_4_digit_ce_years(
datetime in prop_oneof![
Expand Down

0 comments on commit d102af4

Please sign in to comment.