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

feat(wkt): Support jiff From conversions for Duration and Timestamp #1154

Closed
wants to merge 3 commits into from
Closed
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
28 changes: 28 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 3 additions & 1 deletion src/wkt/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -25,11 +25,13 @@ version = "0.1.1"

[features]
chrono = ["dep:chrono"]
jiff = ["dep:jiff"]
time = []

[dependencies]
bytes = { version = "1.10.0", features = ["serde"] }
chrono = { version = "0.4.39", optional = true }
jiff = { version = "0.2.0", default-features = false, features = ["std"], optional = true }
serde = { version = "1.0.217", features = ["serde_derive"] }
serde_json = "1"
serde_with = { version = "3.12.0", default-features = false, features = ["base64", "macros", "std"] }
Expand All @@ -39,4 +41,4 @@ time = { version = "0.3.36", features = ["formatting", "parsing"] }
[dev-dependencies]
bytes = { version = "1.10.0", features = ["serde"] }
test-case = "3.3.1"
wkt = { path = ".", package = "google-cloud-wkt", features = ["chrono", "time"] }
wkt = { path = ".", package = "google-cloud-wkt", features = ["chrono", "jiff", "time"] }
54 changes: 54 additions & 0 deletions src/wkt/src/duration.rs
Original file line number Diff line number Diff line change
Expand Up @@ -302,6 +302,28 @@ impl std::convert::From<Duration> for chrono::Duration {
}
}

/// Converts from [jiff::SignedDuration] to [Duration].
///
/// This conversion may fail if the [jiff::SignedDuration] value is out of range.
#[cfg(feature = "jiff")]
impl std::convert::TryFrom<jiff::SignedDuration> for Duration {
type Error = DurationError;

fn try_from(value: jiff::SignedDuration) -> Result<Self, Self::Error> {
Self::new(value.as_secs(), value.subsec_nanos())
}
}

/// Converts from [Duration] to [jiff::SignedDuration].
#[cfg(feature = "jiff")]
impl std::convert::From<Duration> for jiff::SignedDuration {
fn from(value: Duration) -> Self {
// Safety: The range of jiff::SignedDuration is larger than Duration,
// so this will not overflow.
Self::new(value.seconds, value.nanos)
}
}

/// Implement [`serde`](::serde) serialization for [Duration].
impl serde::ser::Serialize for Duration {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
Expand Down Expand Up @@ -544,4 +566,36 @@ mod test {
let got = Duration::try_from(value);
assert_eq!(got, Err(DurationError::OutOfRange()));
}

#[test_case(jiff::SignedDuration::default(), Duration::default() ; "default")]
#[test_case(jiff::SignedDuration::ZERO, Duration::new(0, 0).unwrap() ; "zero")]
#[test_case(jiff::SignedDuration::from_secs(10_000 * SECONDS_IN_YEAR), Duration::new(10_000 * SECONDS_IN_YEAR, 0).unwrap() ; "exactly 10,000 years")]
#[test_case(jiff::SignedDuration::from_secs(-10_000 * SECONDS_IN_YEAR), Duration::new(-10_000 * SECONDS_IN_YEAR, 0).unwrap() ; "exactly negative 10,000 years")]
#[test_case(jiff::SignedDuration::new(-5, -500_000), Duration::new(-5, -500_000).unwrap() ; "negative seconds and nanos")]
#[test_case(jiff::SignedDuration::new(5, 500_000), Duration::new(5, 500_000).unwrap() ; "positive seconds and nanos")]
fn from_jiff_time_in_range(value: jiff::SignedDuration, want: Duration) -> Result {
let got = Duration::try_from(value)?;
assert_eq!(got, want);
Ok(())
}

#[test_case(Duration::default(), jiff::SignedDuration::default() ; "default")]
#[test_case(Duration::new(0, 0).unwrap(), jiff::SignedDuration::ZERO ; "zero")]
#[test_case(Duration::new(10_000 * SECONDS_IN_YEAR , 0).unwrap(), jiff::SignedDuration::from_secs(10_000 * SECONDS_IN_YEAR) ; "exactly 10,000 years")]
#[test_case(Duration::new(-10_000 * SECONDS_IN_YEAR , 0).unwrap(), jiff::SignedDuration::from_secs(-10_000 * SECONDS_IN_YEAR) ; "exactly negative 10,000 years")]
#[test_case(Duration::new(-5, -500_000).unwrap(), jiff::SignedDuration::new(-5, -500_000) ; "negative seconds and nanos")]
#[test_case(Duration::new(5, 500_000).unwrap(), jiff::SignedDuration::new(5, 500_000) ; "positive seconds and nanos")]
fn to_jiff_time_in_range(value: Duration, want: jiff::SignedDuration) -> Result {
let got = jiff::SignedDuration::from(value);
assert_eq!(got, want);
Ok(())
}

#[test_case(jiff::SignedDuration::new(10_001 * SECONDS_IN_YEAR, 0) ; "above the range")]
#[test_case(jiff::SignedDuration::new(-10_001 * SECONDS_IN_YEAR, 0) ; "below the range")]
fn from_jiff_time_out_of_range(value: jiff::SignedDuration) -> Result {
let got = Duration::try_from(value);
assert_eq!(got, Err(DurationError::OutOfRange()));
Ok(())
}
}
87 changes: 87 additions & 0 deletions src/wkt/src/timestamp.rs
Original file line number Diff line number Diff line change
Expand Up @@ -298,8 +298,41 @@ impl TryFrom<Timestamp> for chrono::DateTime<chrono::Utc> {
}
}

/// Converts from [jiff::Timestamp] to [Timestamp].
///
/// This conversion may fail if the [jiff::Timestamp] value is out of range.
#[cfg(feature = "jiff")]
impl TryFrom<jiff::Timestamp> for Timestamp {
type Error = TimestampError;

fn try_from(value: jiff::Timestamp) -> std::result::Result<Self, Self::Error> {
let ns = value.subsec_nanosecond();

// Jiff nanosecond component is negative before the Unix epoch.
if ns < 0 {
Timestamp::new(value.as_second() - 1, ns + 1_000_000_000)
} else {
Timestamp::new(value.as_second(), ns)
}
}
}

/// Converts from [Timestamp] to [jiff::Timestamp].
///
/// This conversion may fail if the [Timestamp] value is out of range.
#[cfg(feature = "jiff")]
impl TryFrom<Timestamp> for jiff::Timestamp {
type Error = jiff::Error;

fn try_from(value: Timestamp) -> std::result::Result<Self, Self::Error> {
jiff::Timestamp::new(value.seconds, value.nanos)
}
}

#[cfg(test)]
mod test {
use std::str::FromStr;

use super::*;
use serde_json::json;
use test_case::test_case;
Expand Down Expand Up @@ -391,4 +424,58 @@ mod test {
assert!(msg.contains("RFC 3339"), "message={}", msg);
Ok(())
}

#[test_case(jiff::Timestamp::default(), Timestamp::default() ; "default")]
#[test_case(jiff::Timestamp::new(0, 0).unwrap(), Timestamp::new(0, 0).unwrap() ; "zero")]
#[test_case(jiff::Timestamp::MAX, Timestamp::new(253402207200, Timestamp::MAX_NANOS).unwrap() ; "maximum")]
#[test_case(jiff::Timestamp::from_str("0001-01-01T00:00:00Z").unwrap(), Timestamp::new(Timestamp::MIN_SECONDS, Timestamp::MIN_NANOS).unwrap() ; "minimum")]
#[test_case(jiff::Timestamp::new(-4, -500_000_000).unwrap(), Timestamp::new(-5, 500_000_000).unwrap() ; "negative seconds and nanos")]
#[test_case(jiff::Timestamp::new(5, 500_000_000).unwrap(), Timestamp::new(5, 500_000_000).unwrap() ; "positive seconds and nanos")]
fn from_jiff_time_in_range(value: jiff::Timestamp, want: Timestamp) -> Result {
let got = Timestamp::try_from(value)?;
assert_eq!(got, want);

// Assert that both timestamps represent the same duration since (or before) the Epoch.
assert_eq!(
((got.seconds as i128) * Timestamp::NS as i128) + got.nanos as i128,
value.as_duration().as_nanos()
);
Ok(())
}

#[test_case(Timestamp::default(), jiff::Timestamp::default() ; "default")]
#[test_case(Timestamp::new(0, 0).unwrap(), jiff::Timestamp::new(0, 0).unwrap() ; "zero")]
#[test_case(Timestamp::new(253402207200, Timestamp::MAX_NANOS).unwrap(), jiff::Timestamp::MAX ; "maximum")]
#[test_case(Timestamp::new(Timestamp::MIN_SECONDS, Timestamp::MIN_NANOS).unwrap(), jiff::Timestamp::from_str("0001-01-01T00:00:00Z").unwrap() ; "minimum")]
#[test_case(Timestamp::new(-5, 500_000_000).unwrap(), jiff::Timestamp::new(-4, -500_000_000).unwrap() ; "negative seconds and nanos")]
#[test_case(Timestamp::new(5, 500_000_000).unwrap(), jiff::Timestamp::new(5, 500_000_000).unwrap() ; "positive seconds and nanos")]
fn to_jiff_time_in_range(value: Timestamp, want: jiff::Timestamp) -> Result {
let got = jiff::Timestamp::try_from(value.clone())?;
assert_eq!(got, want);

// Assert that both timestamps represent the same duration since (or before) the Epoch.
assert_eq!(
((value.seconds as i128) * Timestamp::NS as i128) + value.nanos as i128,
got.as_duration().as_nanos()
);
Ok(())
}

// Jiff timestamps support years in BCE.
#[test_case(jiff::Timestamp::from_str("-000001-01-01T00:00:01Z").unwrap() ; "below the range")]
fn from_jiff_time_out_of_range(value: jiff::Timestamp) -> Result {
let got = Timestamp::try_from(value);
assert_eq!(got, Err(TimestampError::OutOfRange()));
Ok(())
}

// Jiff timestamps are slightly constrained in range, in order to allow
// valid civil times across all timezones, so the maximum possible value
// is a few hours shorter.
#[test_case(Timestamp::new(253402207201, 0).unwrap() ; "above the range")]
fn to_jiff_time_out_of_range(value: Timestamp) -> Result {
let got = jiff::Timestamp::try_from(value);
matches!(got, Err(_));
Ok(())
}
}