Skip to content
Open
Show file tree
Hide file tree
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
2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,6 @@ readme = "README.md"
[workspace.dependencies]
base64 = "0.22"
bytes = "1.0"
chrono = { version = "0.4", default-features = false, features = ["alloc"] }
heck = "0.5"
itertools = "0.14"
pbjson = { path = "pbjson", version = "0.9" }
Expand All @@ -33,3 +32,4 @@ rand = "0.9"
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
tempfile = "3.1"
time = { version = "0.3", default-features = false, features = ["formatting", "parsing", "macros"] }
2 changes: 1 addition & 1 deletion pbjson-test/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,8 @@ use-integers-for-enums = []
preserve-proto-field-names = []

[dev-dependencies]
chrono.workspace = true
serde_json.workspace = true
time.workspace = true

[build-dependencies]
prost-build.workspace = true
Expand Down
18 changes: 7 additions & 11 deletions pbjson-test/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -62,8 +62,7 @@ mod tests {

use super::*;
use crate::test::syntax3::kitchen_sink::MixedCase;
use chrono::TimeZone;
use pbjson_types::{Duration, Timestamp};
use pbjson_types::Duration;
use test::syntax3::*;

/// A struct holding the expected json-encoded representation of a test step.
Expand Down Expand Up @@ -579,15 +578,12 @@ mod tests {
decoded.optional_string = None;
verify_decode(&decoded, "{}");

let date = chrono::Utc
.with_ymd_and_hms(2072, 3, 1, 5, 2, 5)
.unwrap()
.checked_add_signed(chrono::Duration::milliseconds(30))
.unwrap();
decoded.timestamp = Some(Timestamp {
seconds: date.timestamp(),
nanos: date.timestamp_subsec_nanos() as i32,
});
let date = time::OffsetDateTime::parse(
"2072-03-01T05:02:05.030+00:00",
&time::format_description::well_known::Rfc3339,
)
.unwrap();
decoded.timestamp = Some(date.into());

verify(&decoded, r#"{"timestamp":"2072-03-01T05:02:05.030+00:00"}"#);

Expand Down
2 changes: 1 addition & 1 deletion pbjson-types/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,10 @@ exclude = ["protos/*"]

[dependencies] # In alphabetical order
bytes.workspace = true
chrono.workspace = true
pbjson.workspace = true
prost.workspace = true
serde.workspace = true
time.workspace = true

[dev-dependencies]
serde_json.workspace = true
Expand Down
9 changes: 9 additions & 0 deletions pbjson-types/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,15 @@
//! __Note: Coverage of all types is currently incomplete,
//! some may have non-compliant implementations__
//!
//! [`Timestamp`] converts to and from [`time::OffsetDateTime`]:
//!
//! ```
//! let timestamp = pbjson_types::Timestamp::from(time::OffsetDateTime::UNIX_EPOCH);
//! let datetime = time::OffsetDateTime::try_from(timestamp)?;
//! assert_eq!(datetime, time::OffsetDateTime::UNIX_EPOCH);
//! # Ok::<(), &'static str>(())
//! ```
//!
//! [1]: https://docs.rs/serde/1.0.130/serde/trait.Serialize.html
//! [2]: https://docs.rs/serde/1.0.130/serde/trait.Deserialize.html
//! [3]: https://developers.google.com/protocol-buffers/docs/proto3#json
Expand Down
160 changes: 131 additions & 29 deletions pbjson-types/src/timestamp.rs
Original file line number Diff line number Diff line change
@@ -1,28 +1,30 @@
use crate::Timestamp;
use chrono::{DateTime, Utc};
use std::fmt::Write;

use serde::Serialize;
use serde::de::Visitor;
use time::{OffsetDateTime, format_description::well_known::Rfc3339};

impl TryFrom<Timestamp> for DateTime<Utc> {
impl TryFrom<Timestamp> for OffsetDateTime {
type Error = &'static str;
fn try_from(value: Timestamp) -> Result<Self, Self::Error> {
let Timestamp { seconds, nanos } = value;

Self::from_timestamp(
seconds,
nanos
.try_into()
.map_err(|_| "out of range integral type conversion attempted")?,
)
.ok_or("invalid or out-of-range datetime")
if !(-62_135_596_800..=253_402_300_799).contains(&seconds)
|| !(0..1_000_000_000).contains(&nanos)
{
return Err("invalid or out-of-range datetime");
}
Self::from_unix_timestamp_nanos(i128::from(seconds) * 1_000_000_000 + i128::from(nanos))
.map_err(|_| "invalid or out-of-range datetime")
}
}

impl From<DateTime<Utc>> for Timestamp {
fn from(value: DateTime<Utc>) -> Self {
impl From<OffsetDateTime> for Timestamp {
fn from(value: OffsetDateTime) -> Self {
Self {
seconds: value.timestamp(),
nanos: value.timestamp_subsec_nanos() as i32,
seconds: value.unix_timestamp(),
nanos: value.nanosecond() as i32,
}
}
}
Expand All @@ -32,8 +34,26 @@ impl Serialize for Timestamp {
where
S: serde::Serializer,
{
let t: DateTime<Utc> = (*self).try_into().map_err(serde::ser::Error::custom)?;
serializer.serialize_str(t.to_rfc3339().as_str())
let t: OffsetDateTime = (*self).try_into().map_err(serde::ser::Error::custom)?;
let mut encoded = t
.format(time::macros::format_description!(
"[year]-[month]-[day]T[hour]:[minute]:[second]"
))
.map_err(serde::ser::Error::custom)?;
// Preserve the existing UTC suffix and 0/3/6/9 fractional-digit output.
let nanos = t.nanosecond();
if nanos != 0 {
let (fraction, width) = if nanos.is_multiple_of(1_000_000) {
(nanos / 1_000_000, 3)
} else if nanos.is_multiple_of(1_000) {
(nanos / 1_000, 6)
} else {
(nanos, 9)
};
write!(encoded, ".{fraction:0width$}").map_err(serde::ser::Error::custom)?;
}
encoded.push_str("+00:00");
serializer.serialize_str(&encoded)
}
}

Expand All @@ -50,9 +70,10 @@ impl<'de> Visitor<'de> for TimestampVisitor {
where
E: serde::de::Error,
{
let d = DateTime::parse_from_rfc3339(s).map_err(serde::de::Error::custom)?;
let d: DateTime<Utc> = d.into();
Ok(d.into())
let d = OffsetDateTime::parse(s, &Rfc3339).map_err(serde::de::Error::custom)?;
let timestamp = Timestamp::from(d);
OffsetDateTime::try_from(timestamp).map_err(serde::de::Error::custom)?;
Ok(timestamp)
}
}

Expand All @@ -68,29 +89,110 @@ impl<'de> serde::Deserialize<'de> for Timestamp {
#[cfg(test)]
mod tests {
use super::*;
use chrono::{FixedOffset, TimeZone};
use serde::Deserialize;
use serde::de::value::{BorrowedStrDeserializer, Error};

#[test]
fn test_date() {
let datetime = FixedOffset::east_opt(5 * 3600)
.expect("time zone offset should be valid")
.with_ymd_and_hms(2016, 11, 8, 21, 7, 9)
.unwrap();
let encoded = datetime.to_rfc3339();
let datetime = OffsetDateTime::parse("2016-11-08T21:07:09+05:00", &Rfc3339).unwrap();
let encoded = datetime.format(&Rfc3339).unwrap();
assert_eq!(&encoded, "2016-11-08T21:07:09+05:00");

let utc: DateTime<Utc> = datetime.into();
let utc_encoded = utc.to_rfc3339();
assert_eq!(&utc_encoded, "2016-11-08T16:07:09+00:00");
let utc = datetime.to_offset(time::UtcOffset::UTC);
let utc_encoded = "2016-11-08T16:07:09+00:00";

let deserializer = BorrowedStrDeserializer::<'_, Error>::new(&encoded);
let a: Timestamp = Timestamp::deserialize(deserializer).unwrap();
assert_eq!(a.seconds, utc.timestamp());
assert_eq!(a.nanos, utc.timestamp_subsec_nanos() as i32);
assert_eq!(a.seconds, utc.unix_timestamp());
assert_eq!(a.nanos, utc.nanosecond() as i32);

let encoded = serde_json::to_string(&a).unwrap();
assert_eq!(encoded, format!("\"{}\"", utc_encoded));
}

#[test]
fn timestamp_boundaries_and_fractional_precision() {
for (seconds, nanos, encoded) in [
(-62_135_596_800, 0, "0001-01-01T00:00:00+00:00"),
(-1, 0, "1969-12-31T23:59:59+00:00"),
(-1, 1, "1969-12-31T23:59:59.000000001+00:00"),
(-1, 999_999_999, "1969-12-31T23:59:59.999999999+00:00"),
(0, 0, "1970-01-01T00:00:00+00:00"),
(0, 30_000_000, "1970-01-01T00:00:00.030+00:00"),
(0, 30_000, "1970-01-01T00:00:00.000030+00:00"),
(
253_402_300_799,
999_999_999,
"9999-12-31T23:59:59.999999999+00:00",
),
] {
let timestamp = Timestamp { seconds, nanos };
let native = OffsetDateTime::try_from(timestamp).unwrap();
assert_eq!(Timestamp::from(native), timestamp);
let json = serde_json::to_string(&timestamp).unwrap();
assert_eq!(json, format!("\"{encoded}\""));
assert_eq!(serde_json::from_str::<Timestamp>(&json).unwrap(), timestamp);
}
}

#[test]
fn invalid_timestamp_fields_are_rejected() {
for timestamp in [
Timestamp {
seconds: -62_135_596_801,
nanos: 999_999_999,
},
Timestamp {
seconds: 253_402_300_800,
nanos: 0,
},
Timestamp {
seconds: i64::MIN,
nanos: 0,
},
Timestamp {
seconds: i64::MAX,
nanos: 0,
},
Timestamp {
seconds: 0,
nanos: -1,
},
Timestamp {
seconds: 0,
nanos: 1_000_000_000,
},
] {
assert!(OffsetDateTime::try_from(timestamp).is_err());
assert!(serde_json::to_string(&timestamp).is_err());
}
for encoded in [
"0000-12-31T23:59:59Z",
"0001-01-01T00:00:00+01:00",
"9999-12-31T23:59:59-01:00",
"2024-02-30T00:00:00Z",
] {
assert!(serde_json::from_str::<Timestamp>(&format!("\"{encoded}\"")).is_err());
}
}

#[test]
fn offsets_before_the_epoch_keep_nonnegative_nanos() {
let expected = Timestamp {
seconds: -1,
nanos: 123_456_789,
};
for encoded in [
"1969-12-31T23:59:59.123456789Z",
"1970-01-01T00:59:59.123456789+01:00",
"1969-12-31T18:59:59.123456789-05:00",
] {
let timestamp = serde_json::from_str::<Timestamp>(&format!("\"{encoded}\"")).unwrap();
assert_eq!(timestamp, expected);
assert_eq!(
Timestamp::from(OffsetDateTime::parse(encoded, &Rfc3339).unwrap()),
expected
);
}
}
}