Skip to content

Commit

Permalink
Merge pull request #914 from CosmWasm/add-timestamp-subtract
Browse files Browse the repository at this point in the history
Add Timestamp::minus_seconds and ::minus_nanos
  • Loading branch information
ethanfrey committed May 3, 2021
2 parents b82b655 + 002e6fe commit 121deaa
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 2 deletions.
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,10 @@ and this project adheres to

## [Unreleased]

### Added

- cosmwasm-std: Add `Timestamp::minus_seconds` and `::minus_nanos`.

## [0.14.0] - 2021-05-03

### Added
Expand Down
44 changes: 42 additions & 2 deletions packages/std/src/timestamp.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,15 +24,23 @@ impl Timestamp {
}

pub const fn plus_seconds(&self, addition: u64) -> Timestamp {
let nanos = Uint64::new(self.0.u64() + addition * 1_000_000_000);
Timestamp(nanos)
self.plus_nanos(addition * 1_000_000_000)
}

pub const fn plus_nanos(&self, addition: u64) -> Timestamp {
let nanos = Uint64::new(self.0.u64() + addition);
Timestamp(nanos)
}

pub const fn minus_seconds(&self, subtrahend: u64) -> Timestamp {
self.minus_nanos(subtrahend * 1_000_000_000)
}

pub const fn minus_nanos(&self, subtrahend: u64) -> Timestamp {
let nanos = Uint64::new(self.0.u64() - subtrahend);
Timestamp(nanos)
}

/// Returns nanoseconds since epoch
pub fn nanos(&self) -> u64 {
self.0.u64()
Expand Down Expand Up @@ -83,6 +91,38 @@ mod tests {
assert_eq!(sum.0.u64(), 123);
}

#[test]
fn timestamp_minus_seconds() {
let earlier = Timestamp::from_seconds(123).minus_seconds(0);
assert_eq!(earlier.0.u64(), 123_000_000_000);
let earlier = Timestamp::from_seconds(123).minus_seconds(3);
assert_eq!(earlier.0.u64(), 120_000_000_000);
let earlier = Timestamp::from_seconds(123).minus_seconds(123);
assert_eq!(earlier.0.u64(), 0);
}

#[test]
#[should_panic(expected = "attempt to subtract with overflow")]
fn timestamp_minus_seconds_panics_on_overflow() {
let _earlier = Timestamp::from_seconds(100).minus_seconds(101);
}

#[test]
fn timestamp_minus_nanos() {
let earlier = Timestamp::from_seconds(123).minus_nanos(0);
assert_eq!(earlier.0.u64(), 123_000_000_000);
let earlier = Timestamp::from_seconds(123).minus_nanos(3);
assert_eq!(earlier.0.u64(), 122_999_999_997);
let earlier = Timestamp::from_seconds(123).minus_nanos(123_000_000_000);
assert_eq!(earlier.0.u64(), 0);
}

#[test]
#[should_panic(expected = "attempt to subtract with overflow")]
fn timestamp_minus_nanos_panics_on_overflow() {
let _earlier = Timestamp::from_nanos(100).minus_nanos(101);
}

#[test]
fn timestamp_nanos() {
let sum = Timestamp::from_nanos(123);
Expand Down

0 comments on commit 121deaa

Please sign in to comment.