1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667
mod datetime;
use core::convert::TryFrom;
use core::str::FromStr;
use core::*;
use core::time;
use std::convert::TryInto;
use chrono::prelude::*;
use serde::de::{self, Deserialize, Deserializer, Visitor};
use serde::ser::{Serialize, Serializer};
include!(concat!(env!("OUT_DIR"), "/pbtime/google.protobuf.rs"));
////////////////////////////////////////////////////////////////////////////////
/// FROM prost-types/src/lib.rs
/// with impl Name removed until stabilized
////////////////////////////////////////////////////////////////////////////////
const NANOS_PER_SECOND: i32 = 1_000_000_000;
const NANOS_MAX: i32 = NANOS_PER_SECOND - 1;
#[cfg(feature = "std")]
impl std::hash::Hash for Duration {
fn hash<H: core::hash::Hasher>(&self, state: &mut H) {
self.seconds.hash(state);
self.nanos.hash(state);
}
}
impl Duration {
/// Normalizes the duration to a canonical format.
///
/// Based on [`google::protobuf::util::CreateNormalized`][1].
///
/// [1]: https://github.com/google/protobuf/blob/v3.3.2/src/google/protobuf/util/time_util.cc#L79-L100
pub fn normalize(&mut self) {
// Make sure nanos is in the range.
if self.nanos <= -NANOS_PER_SECOND || self.nanos >= NANOS_PER_SECOND {
if let Some(seconds) = self
.seconds
.checked_add((self.nanos / NANOS_PER_SECOND) as i64)
{
self.seconds = seconds;
self.nanos %= NANOS_PER_SECOND;
} else if self.nanos < 0 {
// Negative overflow! Set to the least normal value.
self.seconds = i64::MIN;
self.nanos = -NANOS_MAX;
} else {
// Positive overflow! Set to the greatest normal value.
self.seconds = i64::MAX;
self.nanos = NANOS_MAX;
}
}
// nanos should have the same sign as seconds.
if self.seconds < 0 && self.nanos > 0 {
if let Some(seconds) = self.seconds.checked_add(1) {
self.seconds = seconds;
self.nanos -= NANOS_PER_SECOND;
} else {
// Positive overflow! Set to the greatest normal value.
debug_assert_eq!(self.seconds, i64::MAX);
self.nanos = NANOS_MAX;
}
} else if self.seconds > 0 && self.nanos < 0 {
if let Some(seconds) = self.seconds.checked_sub(1) {
self.seconds = seconds;
self.nanos += NANOS_PER_SECOND;
} else {
// Negative overflow! Set to the least normal value.
debug_assert_eq!(self.seconds, i64::MIN);
self.nanos = -NANOS_MAX;
}
}
// TODO: should this be checked?
// debug_assert!(self.seconds >= -315_576_000_000 && self.seconds <= 315_576_000_000,
// "invalid duration: {:?}", self);
}
}
impl TryFrom<time::Duration> for Duration {
type Error = DurationError;
/// Converts a `std::time::Duration` to a `Duration`, failing if the duration is too large.
fn try_from(duration: time::Duration) -> Result<Duration, DurationError> {
let seconds = i64::try_from(duration.as_secs()).map_err(|_| DurationError::OutOfRange)?;
let nanos = duration.subsec_nanos() as i32;
let mut duration = Duration { seconds, nanos };
duration.normalize();
Ok(duration)
}
}
impl TryFrom<Duration> for time::Duration {
type Error = DurationError;
/// Converts a `Duration` to a `std::time::Duration`, failing if the duration is negative.
fn try_from(mut duration: Duration) -> Result<time::Duration, DurationError> {
duration.normalize();
if duration.seconds >= 0 && duration.nanos >= 0 {
Ok(time::Duration::new(
duration.seconds as u64,
duration.nanos as u32,
))
} else {
Err(DurationError::NegativeDuration(time::Duration::new(
(-duration.seconds) as u64,
(-duration.nanos) as u32,
)))
}
}
}
impl fmt::Display for Duration {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let mut d = self.clone();
d.normalize();
if self.seconds < 0 && self.nanos < 0 {
write!(f, "-")?;
}
write!(f, "{}", d.seconds.abs())?;
// Format subseconds to either nothing, millis, micros, or nanos.
let nanos = d.nanos.abs();
if nanos == 0 {
write!(f, "s")
} else if nanos % 1_000_000 == 0 {
write!(f, ".{:03}s", nanos / 1_000_000)
} else if nanos % 1_000 == 0 {
write!(f, ".{:06}s", nanos / 1_000)
} else {
write!(f, ".{:09}s", nanos)
}
}
}
/// A duration handling error.
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Debug, PartialEq)]
#[non_exhaustive]
pub enum DurationError {
/// Indicates failure to parse a [`Duration`] from a string.
///
/// The [`Duration`] string format is specified in the [Protobuf JSON mapping specification][1].
///
/// [1]: https://developers.google.com/protocol-buffers/docs/proto3#json
ParseFailure,
/// Indicates failure to convert a `prost_types::Duration` to a `std::time::Duration` because
/// the duration is negative. The included `std::time::Duration` matches the magnitude of the
/// original negative `prost_types::Duration`.
NegativeDuration(time::Duration),
/// Indicates failure to convert a `std::time::Duration` to a `prost_types::Duration`.
///
/// Converting a `std::time::Duration` to a `prost_types::Duration` fails if the magnitude
/// exceeds that representable by `prost_types::Duration`.
OutOfRange,
}
impl fmt::Display for DurationError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
DurationError::ParseFailure => write!(f, "failed to parse duration"),
DurationError::NegativeDuration(duration) => {
write!(f, "failed to convert negative duration: {:?}", duration)
}
DurationError::OutOfRange => {
write!(f, "failed to convert duration out of range")
}
}
}
}
#[cfg(feature = "std")]
impl std::error::Error for DurationError {}
impl FromStr for Duration {
type Err = DurationError;
fn from_str(s: &str) -> Result<Duration, DurationError> {
datetime::parse_duration(s).ok_or(DurationError::ParseFailure)
}
}
impl Timestamp {
/// Normalizes the timestamp to a canonical format.
///
/// 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 normalize(&mut self) {
// Make sure nanos is in the range.
if self.nanos <= -NANOS_PER_SECOND || self.nanos >= NANOS_PER_SECOND {
if let Some(seconds) = self
.seconds
.checked_add((self.nanos / NANOS_PER_SECOND) as i64)
{
self.seconds = seconds;
self.nanos %= NANOS_PER_SECOND;
} else if self.nanos < 0 {
// Negative overflow! Set to the earliest normal value.
self.seconds = i64::MIN;
self.nanos = 0;
} else {
// Positive overflow! Set to the latest normal value.
self.seconds = i64::MAX;
self.nanos = 999_999_999;
}
}
// For Timestamp nanos should be in the range [0, 999999999].
if self.nanos < 0 {
if let Some(seconds) = self.seconds.checked_sub(1) {
self.seconds = seconds;
self.nanos += NANOS_PER_SECOND;
} else {
// Negative overflow! Set to the earliest normal value.
debug_assert_eq!(self.seconds, i64::MIN);
self.nanos = 0;
}
}
// TODO: should this be checked?
// debug_assert!(self.seconds >= -62_135_596_800 && self.seconds <= 253_402_300_799,
// "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)
}
/// Creates a new `Timestamp` instance with the provided UTC date and time.
pub fn date_time(
year: i64,
month: u8,
day: u8,
hour: u8,
minute: u8,
second: u8,
) -> Result<Timestamp, TimestampError> {
Timestamp::date_time_nanos(year, month, day, hour, minute, second, 0)
}
/// Creates a new `Timestamp` instance with the provided UTC date and time.
pub fn date_time_nanos(
year: i64,
month: u8,
day: u8,
hour: u8,
minute: u8,
second: u8,
nanos: u32,
) -> Result<Timestamp, TimestampError> {
let date_time = datetime::DateTime {
year,
month,
day,
hour,
minute,
second,
nanos,
};
if date_time.is_valid() {
Ok(Timestamp::from(date_time))
} else {
Err(TimestampError::InvalidDateTime)
}
}
}
/// Implements the unstable/naive version of `Eq`: a basic equality check on the internal fields of the `Timestamp`.
/// This implies that `normalized_ts != non_normalized_ts` even if `normalized_ts == non_normalized_ts.normalized()`.
#[cfg(feature = "std")]
impl Eq for Timestamp {}
#[cfg(feature = "std")]
#[allow(clippy::derived_hash_with_manual_eq)] // Derived logic is correct: comparing the 2 fields for equality
impl std::hash::Hash for Timestamp {
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
self.seconds.hash(state);
self.nanos.hash(state);
}
}
#[cfg(feature = "std")]
impl From<std::time::SystemTime> for Timestamp {
fn from(system_time: std::time::SystemTime) -> Timestamp {
let (seconds, nanos) = match system_time.duration_since(std::time::UNIX_EPOCH) {
Ok(duration) => {
let seconds = i64::try_from(duration.as_secs()).unwrap();
(seconds, duration.subsec_nanos() as i32)
}
Err(error) => {
let duration = error.duration();
let seconds = i64::try_from(duration.as_secs()).unwrap();
let nanos = duration.subsec_nanos() as i32;
if nanos == 0 {
(-seconds, 0)
} else {
(-seconds - 1, 1_000_000_000 - nanos)
}
}
};
Timestamp { seconds, nanos }
}
}
/// A timestamp handling error.
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Debug, PartialEq)]
#[non_exhaustive]
pub enum TimestampError {
/// Indicates that a [`Timestamp`] could not be converted to
/// [`SystemTime`][std::time::SystemTime] because it is out of range.
///
/// The range of times that can be represented by `SystemTime` depends on the platform. All
/// `Timestamp`s are likely representable on 64-bit Unix-like platforms, but other platforms,
/// such as Windows and 32-bit Linux, may not be able to represent the full range of
/// `Timestamp`s.
OutOfSystemRange(Timestamp),
/// An error indicating failure to parse a timestamp in RFC-3339 format.
ParseFailure,
/// Indicates an error when constructing a timestamp due to invalid date or time data.
InvalidDateTime,
}
impl fmt::Display for TimestampError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
TimestampError::OutOfSystemRange(timestamp) => {
write!(
f,
"{} is not representable as a `SystemTime` because it is out of range",
timestamp
)
}
TimestampError::ParseFailure => {
write!(f, "failed to parse RFC-3339 formatted timestamp")
}
TimestampError::InvalidDateTime => {
write!(f, "invalid date or time")
}
}
}
}
#[cfg(feature = "std")]
impl std::error::Error for TimestampError {}
#[cfg(feature = "std")]
impl TryFrom<Timestamp> for std::time::SystemTime {
type Error = TimestampError;
fn try_from(mut timestamp: Timestamp) -> Result<std::time::SystemTime, Self::Error> {
let orig_timestamp = timestamp.clone();
timestamp.normalize();
let system_time = if timestamp.seconds >= 0 {
std::time::UNIX_EPOCH.checked_add(time::Duration::from_secs(timestamp.seconds as u64))
} else {
std::time::UNIX_EPOCH.checked_sub(time::Duration::from_secs(
timestamp
.seconds
.checked_neg()
.ok_or_else(|| TimestampError::OutOfSystemRange(timestamp.clone()))?
as u64,
))
};
let system_time = system_time.and_then(|system_time| {
system_time.checked_add(time::Duration::from_nanos(timestamp.nanos as u64))
});
system_time.ok_or(TimestampError::OutOfSystemRange(orig_timestamp))
}
}
impl FromStr for Timestamp {
type Err = TimestampError;
fn from_str(s: &str) -> Result<Timestamp, TimestampError> {
datetime::parse_timestamp(s).ok_or(TimestampError::ParseFailure)
}
}
impl fmt::Display for Timestamp {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
datetime::DateTime::from(self.clone()).fmt(f)
}
}
////////////////////////////////////////////////////////////////////////////////
/// Converts chrono's `NaiveDateTime` to `Timestamp`..
impl From<NaiveDateTime> for Timestamp {
fn from(dt: NaiveDateTime) -> Self {
Timestamp {
seconds: dt.and_utc().timestamp(),
nanos: dt.and_utc().timestamp_subsec_nanos() as i32,
}
}
}
/// Converts chrono's `DateTime<UTtc>` to `Timestamp`
impl From<DateTime<Utc>> for Timestamp {
fn from(dt: DateTime<Utc>) -> Self {
Timestamp {
seconds: dt.timestamp(),
nanos: dt.timestamp_subsec_nanos() as i32,
}
}
}
/// Converts proto timestamp to chrono's DateTime<Utc>
impl From<Timestamp> for DateTime<Utc> {
fn from(val: Timestamp) -> Self {
let mut value = val;
// A call to `normalize` should capture all out-of-bound sitations hopefully
// ensuring a panic never happens! Ideally this implementation should be
// deprecated in favour of TryFrom but unfortunately having `TryFrom` along with
// `From` causes a conflict.
value.normalize();
DateTime::from_timestamp(value.seconds, value.nanos as u32)
.expect("invalid or out-of-range datetime")
}
}
/// Converts proto duration to chrono's Duration
impl From<Duration> for chrono::Duration {
fn from(val: Duration) -> Self {
let mut value = val;
// A call to `normalize` should capture all out-of-bound sitations hopefully
// ensuring a panic never happens! Ideally this implementation should be
// deprecated in favour of TryFrom but unfortunately having `TryFrom` along with
// `From` causes a conflict.
value.normalize();
let s = chrono::TimeDelta::try_seconds(value.seconds).expect("invalid or out-of-range seconds");
let ns = chrono::Duration::nanoseconds(value.nanos as i64);
s + ns
}
}
/// Converts chrono Duration to proto duration
impl From<chrono::Duration> for Duration {
fn from(val: chrono::Duration) -> Self {
Duration {
seconds: val.num_seconds(),
nanos: (val.num_nanoseconds().unwrap() % 1_000_000_000) as i32,
}
}
}
impl Serialize for Duration {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
let seconds: f64 = self.seconds as f64 + self.nanos as f64 / NANOS_PER_SECOND as f64;
// Generated output always contains 0, 3, 6, or 9 fractional digits, depending on required precision, followed by the suffix "s". Accepted are any fractional digits (also none) as long as they fit into nano-seconds precision and the suffix "s" is required.
// see: https://protobuf.dev/programming-guides/proto3/#json
//
// this code currently *always* serializes with 9 fractional digits.
serializer.serialize_str(&format!("{:.9}s", seconds))
}
}
impl<'de> Deserialize<'de> for Duration {
fn deserialize<D>(deserializer: D) -> Result<Duration, D::Error>
where
D: Deserializer<'de>,
{
struct DurationVisitor;
impl<'de> de::Visitor<'de> for DurationVisitor {
type Value = Duration;
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("A duration ending in 's'")
}
fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
where
E: de::Error,
{
if !value.ends_with('s') {
return Err(de::Error::custom("Duration should end with 's'"));
}
let duration_str = &value[..value.len() - 1]; // Remove 's' from the end
let mut parts = duration_str.split('.'); // Split seconds and fractional seconds
let seconds: i64 = parts
.next()
.ok_or_else(|| de::Error::custom("Missing seconds"))?
.parse()
.map_err(de::Error::custom)?;
let nanos: i32 = match parts.next() {
Some(fraction) => {
let fraction = format!("{:0<9}", fraction); // Pad fraction to nanoseconds
let nanos = fraction.parse().map_err(de::Error::custom)?;
if nanos < 0 || nanos >= NANOS_PER_SECOND as i32 {
return Err(de::Error::custom(format!(
"Fractional nanoseconds out of range: {}",
nanos
)));
}
nanos
}
None => 0,
};
Ok(Duration { seconds, nanos })
}
}
deserializer.deserialize_str(DurationVisitor)
}
}
impl Serialize for Timestamp {
fn serialize<S>(&self, serializer: S) -> Result<<S as Serializer>::Ok, <S as Serializer>::Error>
where
S: Serializer,
{
let mut ts = Timestamp {
seconds: self.seconds,
nanos: self.nanos,
};
ts.normalize();
let dt: DateTime<Utc> = ts.try_into().map_err(serde::ser::Error::custom)?;
serializer.serialize_str(format!("{dt:?}").as_str())
}
}
impl<'de> Deserialize<'de> for Timestamp {
fn deserialize<D>(deserializer: D) -> Result<Self, <D as Deserializer<'de>>::Error>
where
D: Deserializer<'de>,
{
struct TimestampVisitor;
impl<'de> Visitor<'de> for TimestampVisitor {
type Value = Timestamp;
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("Timestamp in RFC3339 format")
}
fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
where
E: de::Error,
{
let utc: DateTime<Utc> = chrono::DateTime::from_str(value).map_err(|err| {
serde::de::Error::custom(format!(
"Failed to parse {value} as datetime: {err:?}"
))
})?;
let ts = Timestamp::from(utc);
Ok(ts)
}
}
deserializer.deserialize_str(TimestampVisitor)
}
}
#[cfg(test)]
mod tests {
use crate::pbtime::*;
use chrono::{DateTime, Utc};
#[test]
fn serialize_duration_check_output() {
// protobuf JSON specification is as follows:
// Generated output always contains 0, 3, 6, or 9 fractional digits, depending on required precision, followed by the suffix "s". Accepted are any fractional digits (also none) as long as they fit into nano-seconds precision and the suffix "s" is required.
// see: https://protobuf.dev/programming-guides/proto3/#json
let duration = Duration {
seconds: 10,
nanos: 300,
};
let json = serde_json::to_string_pretty(&duration).expect("json");
assert_eq!(json, r#""10.000000300s""#);
}
#[test]
fn deserialize_duration_whole_seconds() {
let got: Duration = serde_json::from_str(r#""10s""#).expect("json");
let want = Duration {
seconds: 10,
nanos: 0,
};
assert_eq!(got, want);
}
#[test]
fn serialize_duration() {
let duration = Duration {
seconds: 10,
nanos: 100,
};
let json = serde_json::to_string_pretty(&duration).expect("json");
println!("{json}");
let back: Duration = serde_json::from_str(&json).expect("duration");
assert_eq!(duration, back);
}
#[test]
fn invalid_timestamp_test() {
let ts = Timestamp {
seconds: 10,
nanos: 2000000000,
};
let datetime_utc: DateTime<Utc> = ts.into();
println!("{datetime_utc:?}");
}
#[test]
fn test_duration_conversion_pb_to_chrono() {
let duration = Duration {
seconds: 10,
nanos: 100,
};
let chrono_duration: chrono::Duration = duration.into();
assert_eq!(chrono_duration.num_seconds(), 10);
assert_eq!((chrono_duration - chrono::Duration::try_seconds(10).expect("seconds")).num_nanoseconds(), Some(100));
}
#[test]
fn test_duration_conversion_chrono_to_pb() {
let chrono_duration = chrono::Duration::try_seconds(10).expect("seconds") + chrono::Duration::nanoseconds(100);
let duration: Duration = chrono_duration.into();
assert_eq!(duration.seconds, 10);
assert_eq!(duration.nanos, 100);
}
}