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

Add From and Into support for SystemTime using references #662

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
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
40 changes: 33 additions & 7 deletions protobuf/src/well_known_types_util/timestamp.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,8 @@ impl Timestamp {
/// # Panics
///
/// This function panics if given `SystemTime` is outside of `Timestamp` range.
impl From<SystemTime> for Timestamp {
fn from(time: SystemTime) -> Self {
impl From<&SystemTime> for Timestamp {
fn from(time: &SystemTime) -> Self {
match time.duration_since(SystemTime::UNIX_EPOCH) {
Ok(since_epoch) => Timestamp {
seconds: since_epoch.as_secs() as i64,
Expand All @@ -44,6 +44,17 @@ impl From<SystemTime> for Timestamp {
}
}

/// Convert from [`Timestamp`].
///
/// # Panics
///
/// This function panics if given `SystemTime` is outside of `Timestamp` range.
impl From<SystemTime> for Timestamp {
fn from(time: SystemTime) -> Self {
Self::from(&time)
}
}

/// Convert into [`SystemTime`].
///
/// The conversion could be lossy if `SystemTime` precision is smaller than nanoseconds.
Expand All @@ -53,20 +64,35 @@ impl From<SystemTime> for Timestamp {
/// This function panics:
/// * if given `Timestamp` is outside of `SystemTime` range
/// * if `Timestamp` is malformed
impl Into<SystemTime> for Timestamp {
fn into(self) -> SystemTime {
if self.seconds >= 0 {
impl From<&Timestamp> for SystemTime {
fn from(time: &Timestamp) -> SystemTime {
if time.seconds >= 0 {
let duration =
Duration::from_secs(self.seconds as u64) + Duration::from_nanos(self.nanos as u64);
Duration::from_secs(time.seconds as u64) + Duration::from_nanos(time.nanos as u64);
SystemTime::UNIX_EPOCH + duration
} else {
let duration =
Duration::from_secs(-self.seconds as u64) - Duration::from_nanos(self.nanos as u64);
Duration::from_secs(-time.seconds as u64) - Duration::from_nanos(time.nanos as u64);
SystemTime::UNIX_EPOCH - duration
}
}
}

/// Convert into [`SystemTime`].
///
/// The conversion could be lossy if `SystemTime` precision is smaller than nanoseconds.
///
/// # Panics
///
/// This function panics:
/// * if given `Timestamp` is outside of `SystemTime` range
/// * if `Timestamp` is malformed
impl From<Timestamp> for SystemTime {
fn from(time: Timestamp) -> SystemTime {
SystemTime::from(&time)
}
}

#[cfg(test)]
mod test {
use std::time::Duration;
Expand Down