Skip to content

Commit

Permalink
Support instant conversion prost timestamps in both directions
Browse files Browse the repository at this point in the history
  • Loading branch information
ashlineldridge committed Nov 10, 2024
1 parent b2da1cf commit 0112215
Showing 1 changed file with 13 additions and 4 deletions.
17 changes: 13 additions & 4 deletions src/instant.rs
Original file line number Diff line number Diff line change
Expand Up @@ -255,9 +255,9 @@ impl fmt::Debug for Instant {
}

#[cfg(feature = "prost")]
impl Into<prost_types::Timestamp> for Instant {
fn into(self) -> prost_types::Timestamp {
let dur = Duration::from_nanos(self.0);
impl From<Instant> for prost_types::Timestamp {
fn from(value: Instant) -> Self {
let dur = Duration::from_nanos(value.0);
let secs = if dur.as_secs() > i64::MAX as u64 {
i64::MAX
} else {
Expand All @@ -268,13 +268,22 @@ impl Into<prost_types::Timestamp> for Instant {
} else {
dur.subsec_nanos() as i32
};
prost_types::Timestamp {
Self {
seconds: secs,
nanos: nsecs,
}
}
}

#[cfg(feature = "prost")]
impl From<prost_types::Timestamp> for Instant {
fn from(value: prost_types::Timestamp) -> Self {
const NANOS_PER_SEC: u64 = 1_000_000_000;
let nsecs = value.seconds as u64 * NANOS_PER_SEC + value.nanos as u64;
Self(nsecs)
}
}

#[cfg(test)]
mod tests {
use once_cell::sync::Lazy;
Expand Down

0 comments on commit 0112215

Please sign in to comment.