Skip to content

Commit

Permalink
feat: Added try_normalize to Timestamp (#796)
Browse files Browse the repository at this point in the history
Co-authored-by: Lucio Franco <luciofranco14@gmail.com>
  • Loading branch information
oliverbrowneprima and LucioFranco committed Feb 13, 2023
1 parent 83382aa commit a21cf6b
Showing 1 changed file with 19 additions and 0 deletions.
19 changes: 19 additions & 0 deletions prost-types/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -234,6 +234,25 @@ impl Timestamp {
// "invalid timestamp: {:?}", self);
}

/// Normalizes the timestamp to a canonical format, returning the original value if it cannot be
/// normalized.
///
/// Normalization is based on [`google::protobuf::util::CreateNormalized`][1].
///
/// [1]: https://github.com/google/protobuf/blob/v3.3.2/src/google/protobuf/util/time_util.cc#L59-L77
pub fn try_normalize(mut self) -> Result<Timestamp, Timestamp> {
let before = self.clone();
self.normalize();
// If the seconds value has changed, and is either i64::MIN or i64::MAX, then the timestamp
// normalization overflowed.
if (self.seconds == i64::MAX || self.seconds == i64::MIN) && self.seconds != before.seconds
{
Err(before)
} else {
Ok(self)
}
}

/// Creates a new `Timestamp` at the start of the provided UTC date.
pub fn date(year: i64, month: u8, day: u8) -> Result<Timestamp, TimestampError> {
Timestamp::date_time_nanos(year, month, day, 0, 0, 0, 0)
Expand Down

0 comments on commit a21cf6b

Please sign in to comment.