use crate::alloc::string::String;
pub const MIN_TIMESTAMP_SECS: i64 = -62_135_596_800;
pub const MAX_TIMESTAMP_SECS: i64 = 253_402_300_799;
pub const MAX_DURATION_SECS: i64 = 315_576_000_000;
fn parse_component<T: core::str::FromStr>(s: &str, err: &'static str) -> Result<T, &'static str> {
if s.is_empty() || !s.bytes().all(|b| b.is_ascii_digit()) {
return Err(err);
}
s.parse().map_err(|_| err)
}
pub fn fmt_timestamp(secs: i64, nanos: i32) -> Result<String, &'static str> {
let mut output = String::new();
write_timestamp(&mut output, secs, nanos).map_err(TemporalFormatError::static_reason)?;
Ok(output)
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
pub enum TemporalFormatError {
#[error("Timestamp nanos out of range")]
TimestampNanos,
#[error("Timestamp seconds out of range")]
TimestampSeconds,
#[error("Timestamp year out of range")]
TimestampYear,
#[error("invalid Duration")]
Duration,
#[error("temporal writer rejected output")]
Write,
}
impl TemporalFormatError {
fn static_reason(self) -> &'static str {
match self {
Self::TimestampNanos => "Timestamp nanos out of range",
Self::TimestampSeconds => "Timestamp seconds out of range",
Self::TimestampYear => "Timestamp year out of range",
Self::Duration => "invalid Duration",
Self::Write => "temporal writer rejected output",
}
}
}
pub fn write_timestamp(
output: &mut impl core::fmt::Write,
secs: i64,
nanos: i32,
) -> Result<(), TemporalFormatError> {
if !(0..1_000_000_000).contains(&nanos) {
return Err(TemporalFormatError::TimestampNanos);
}
if !(MIN_TIMESTAMP_SECS..=MAX_TIMESTAMP_SECS).contains(&secs) {
return Err(TemporalFormatError::TimestampSeconds);
}
let (tod, day) = {
let r = secs % 86_400;
if r >= 0 {
(r, secs / 86_400)
} else {
(r + 86_400, secs / 86_400 - 1)
}
};
let (y, mo, d) = days_to_date(day);
if !(1..=9999).contains(&y) {
return Err(TemporalFormatError::TimestampYear);
}
let h = tod / 3600;
let mi = (tod % 3600) / 60;
let s = tod % 60;
write!(output, "{y:04}-{mo:02}-{d:02}T{h:02}:{mi:02}:{s:02}")
.map_err(|_| TemporalFormatError::Write)?;
write_fraction(output, nanos.unsigned_abs())?;
output
.write_char('Z')
.map_err(|_| TemporalFormatError::Write)
}
fn write_fraction(
output: &mut impl core::fmt::Write,
nanos: u32,
) -> Result<(), TemporalFormatError> {
if nanos == 0 {
return Ok(());
}
if nanos % 1_000_000 == 0 {
write!(output, ".{:03}", nanos / 1_000_000)
} else if nanos % 1_000 == 0 {
write!(output, ".{:06}", nanos / 1_000)
} else {
write!(output, ".{nanos:09}")
}
.map_err(|_| TemporalFormatError::Write)
}
pub fn parse_timestamp(s: &str) -> Result<(i64, i32), &'static str> {
if !s.is_ascii() {
return Err("non-ASCII in timestamp");
}
let (dt, tz_offset) = if let Some(rest) = s.strip_suffix('Z') {
(rest, 0i64)
} else {
let len = s.len();
if len < 6 {
return Err("timestamp too short");
}
let sign: i64 = match s.as_bytes()[len - 6] {
b'+' => -1,
b'-' => 1,
_ => return Err("missing or malformed timezone"),
};
if s.as_bytes()[len - 3] != b':' {
return Err("malformed timezone offset");
}
let oh: i64 = parse_component(&s[len - 5..len - 3], "bad offset hours")?;
let om: i64 = parse_component(&s[len - 2..], "bad offset minutes")?;
if !(0..=23).contains(&oh) || !(0..=59).contains(&om) {
return Err("offset out of range");
}
(&s[..len - 6], sign * (oh * 3600 + om * 60))
};
let t = dt.find('T').ok_or("missing 'T' separator")?;
let (date, time) = (&dt[..t], &dt[t + 1..]);
if date.len() != 10 || time.len() < 8 {
return Err("malformed date or time");
}
let date_b = date.as_bytes();
let time_b = time.as_bytes();
if date_b[4] != b'-' || date_b[7] != b'-' || time_b[2] != b':' || time_b[5] != b':' {
return Err("malformed separators");
}
let year: i64 = parse_component(&date[0..4], "bad year")?;
let month: u8 = parse_component(&date[5..7], "bad month")?;
let day: u8 = parse_component(&date[8..10], "bad day")?;
let hour: i64 = parse_component(&time[0..2], "bad hour")?;
let min: i64 = parse_component(&time[3..5], "bad minute")?;
let sec: i64 = parse_component(&time[6..8], "bad second")?;
if !(0..=23).contains(&hour) || !(0..=59).contains(&min) || !(0..=59).contains(&sec) {
return Err("time component out of range");
}
let nanos = if time.len() > 8 {
if time.as_bytes()[8] != b'.' {
return Err("malformed fractional seconds");
}
let frac = &time[9..];
if frac.len() > 9 {
return Err("bad fractional seconds");
}
let n: i32 = parse_component(frac, "bad fractional seconds")?;
n * 10_i32.pow(9 - frac.len() as u32)
} else {
0
};
if !(1..=9999).contains(&year) {
return Err("Timestamp year out of range");
}
let days = date_to_days(year, month, day).ok_or("invalid date")?;
let unix = days * 86_400 + hour * 3600 + min * 60 + sec + tz_offset;
if !(MIN_TIMESTAMP_SECS..=MAX_TIMESTAMP_SECS).contains(&unix) {
return Err("Timestamp out of range after applying offset");
}
Ok((unix, nanos))
}
pub fn fmt_duration(secs: i64, nanos: i32) -> Result<String, &'static str> {
validate_duration(secs, nanos)?;
let mut output = String::new();
write_duration(&mut output, secs, nanos).map_err(TemporalFormatError::static_reason)?;
Ok(output)
}
pub fn write_duration(
output: &mut impl core::fmt::Write,
secs: i64,
nanos: i32,
) -> Result<(), TemporalFormatError> {
validate_duration(secs, nanos).map_err(|_| TemporalFormatError::Duration)?;
if secs < 0 || (secs == 0 && nanos < 0) {
output
.write_char('-')
.map_err(|_| TemporalFormatError::Write)?;
}
write!(output, "{}", secs.unsigned_abs()).map_err(|_| TemporalFormatError::Write)?;
write_fraction(output, nanos.unsigned_abs())?;
output
.write_char('s')
.map_err(|_| TemporalFormatError::Write)
}
pub fn parse_duration(s: &str) -> Result<(i64, i32), &'static str> {
let body = s.strip_suffix('s').ok_or("missing 's' suffix")?;
let negative = body.starts_with('-');
let body = if negative {
body.strip_prefix('-').ok_or("malformed sign")?
} else {
body
};
if body.starts_with(['-', '+']) {
return Err("malformed sign");
}
let (sec_str, nano_str) = match body.find('.') {
Some(dot) => {
let fraction = &body[dot + 1..];
if fraction.is_empty() {
return Err("bad fractional seconds");
}
(&body[..dot], fraction)
}
None => (body, ""),
};
let abs_secs: i64 = sec_str.parse().map_err(|_| "bad seconds")?;
let abs_nanos: i32 = if nano_str.is_empty() {
0
} else {
if nano_str.len() > 9 {
return Err("bad fractional seconds");
}
let n: i32 = parse_component(nano_str, "bad fractional seconds")?;
n * 10_i32.pow(9 - nano_str.len() as u32)
};
let (secs, nanos) = if negative {
(-abs_secs, -abs_nanos)
} else {
(abs_secs, abs_nanos)
};
validate_duration(secs, nanos)?;
Ok((secs, nanos))
}
pub fn validate_duration(secs: i64, nanos: i32) -> Result<(), &'static str> {
if !(-999_999_999..=999_999_999).contains(&nanos) {
return Err("Duration nanos out of range");
}
if !(-MAX_DURATION_SECS..=MAX_DURATION_SECS).contains(&secs) {
return Err("Duration seconds out of range");
}
if (secs > 0 && nanos < 0) || (secs < 0 && nanos > 0) {
return Err("Duration seconds and nanos have opposite signs");
}
Ok(())
}
#[must_use]
pub fn snake_to_camel(path: &str) -> String {
let mut out = String::with_capacity(path.len());
let mut capitalize_next = false;
for ch in path.chars() {
if ch == '_' {
capitalize_next = true;
} else if capitalize_next {
out.extend(ch.to_uppercase());
capitalize_next = false;
} else {
out.push(ch);
}
}
out
}
#[must_use]
pub fn camel_to_snake(path: &str) -> String {
let mut out = String::with_capacity(path.len() + 4);
for ch in path.chars() {
if ch.is_uppercase() {
out.push('_');
out.extend(ch.to_lowercase());
} else {
out.push(ch);
}
}
out
}
#[must_use]
pub fn field_mask_path_round_trips(path: &str) -> bool {
if path == "*" {
return true;
}
path.split('.').all(|component| {
let bytes = component.as_bytes();
let Some(first) = bytes.first() else {
return false;
};
(first.is_ascii_lowercase() || *first == b'_')
&& bytes.iter().enumerate().all(|(i, b)| {
b.is_ascii_lowercase()
|| b.is_ascii_digit()
|| (*b == b'_' && bytes.get(i + 1).is_some_and(u8::is_ascii_lowercase))
})
})
}
#[must_use]
pub fn days_to_date(z: i64) -> (i64, u8, u8) {
let (era, doe) = match z.checked_add(719_468) {
Some(z) => (z.div_euclid(146_097), z.rem_euclid(146_097)),
None => {
let era = z.div_euclid(146_097);
let doe = z.rem_euclid(146_097) + 719_468;
(era + doe / 146_097, doe % 146_097)
}
};
let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
let y = yoe + era * 400;
let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
let mp = (5 * doy + 2) / 153;
let d = (doy - (153 * mp + 2) / 5 + 1) as u8;
let m = if mp < 10 { mp + 3 } else { mp - 9 } as u8;
(if m <= 2 { y + 1 } else { y }, m, d)
}
#[must_use]
pub fn date_to_days(y: i64, m: u8, d: u8) -> Option<i64> {
if !(1..=12).contains(&m) || d == 0 || u32::from(d) > days_in_month(y, u32::from(m)) {
return None;
}
let y = if m <= 2 { y.checked_sub(1)? } else { y };
let era = y.div_euclid(400);
let yoe = y.rem_euclid(400);
let mp = if m > 2 { m - 3 } else { m + 9 } as i64;
let doy = (153 * mp + 2) / 5 + i64::from(d) - 1;
let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
i64::try_from(i128::from(era) * 146_097 + i128::from(doe) - 719_468).ok()
}
fn days_in_month(year: i64, month: u32) -> u32 {
match month {
1 | 3 | 5 | 7 | 8 | 10 | 12 => 31,
4 | 6 | 9 | 11 => 30,
2 => {
if year % 4 == 0 && (year % 100 != 0 || year % 400 == 0) {
29
} else {
28
}
}
_ => 0,
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn civil_calendar_extreme_days_round_trip() {
let cases = [
(i64::MIN, (-25_252_734_927_764_585, 6, 7)),
(i64::MIN + 1, (-25_252_734_927_764_585, 6, 8)),
(i64::MAX - 1, (25_252_734_927_768_524, 7, 26)),
(i64::MAX, (25_252_734_927_768_524, 7, 27)),
];
for (days, date) in cases {
assert_eq!(days_to_date(days), date, "days: {days}");
assert_eq!(date_to_days(date.0, date.1, date.2), Some(days));
}
for days in [i64::MAX - 719_468, i64::MAX - 719_467] {
let (year, month, day) = days_to_date(days);
assert_eq!(date_to_days(year, month, day), Some(days));
}
}
#[test]
fn civil_calendar_rejects_days_outside_i64_range() {
assert_eq!(date_to_days(-25_252_734_927_764_585, 6, 6), None);
assert_eq!(date_to_days(25_252_734_927_768_524, 7, 28), None);
for year in [i64::MIN, i64::MAX] {
for month in 1..=12 {
assert_eq!(date_to_days(year, month, 1), None);
}
}
}
#[test]
fn civil_calendar_round_trip() {
let cases = [
(-719_469, (0, 2, 29)),
(-719_468, (0, 3, 1)),
(-719_162, (1, 1, 1)),
(-1, (1969, 12, 31)),
(0, (1970, 1, 1)),
(11_016, (2000, 2, 29)),
(2_932_896, (9999, 12, 31)),
];
for (days, date) in cases {
assert_eq!(days_to_date(days), date, "days: {days}");
assert_eq!(date_to_days(date.0, date.1, date.2), Some(days));
}
}
#[test]
fn civil_calendar_rejects_invalid_dates() {
for (year, month, day) in [
(2024, 0, 1),
(2024, 13, 1),
(2024, 1, 0),
(2024, 4, 31),
(1900, 2, 29),
(2023, 2, 29),
(2024, 2, 30),
(i64::MIN, 2, 30),
(i64::MAX, 2, 29),
] {
assert_eq!(date_to_days(year, month, day), None);
}
}
#[test]
fn timestamp_round_trip() {
let cases = [
(0, 0, "1970-01-01T00:00:00Z"),
(1, 0, "1970-01-01T00:00:01Z"),
(-1, 0, "1969-12-31T23:59:59Z"),
(0, 500_000_000, "1970-01-01T00:00:00.500Z"),
(0, 1, "1970-01-01T00:00:00.000000001Z"),
(1_609_459_200, 0, "2021-01-01T00:00:00Z"),
(
MAX_TIMESTAMP_SECS,
999_999_999,
"9999-12-31T23:59:59.999999999Z",
),
(MIN_TIMESTAMP_SECS, 0, "0001-01-01T00:00:00Z"),
];
for (secs, nanos, expected) in cases {
assert_eq!(fmt_timestamp(secs, nanos).unwrap(), expected);
assert_eq!(parse_timestamp(expected).unwrap(), (secs, nanos));
}
}
#[test]
fn timestamp_rejects_invalid() {
assert!(parse_timestamp("0000-01-01T00:00:00Z").is_err()); assert!(parse_timestamp("2021-02-30T00:00:00Z").is_err()); assert!(parse_timestamp("2021-01-01t00:00:00Z").is_err()); assert!(parse_timestamp("2021-01-01T00:00:00z").is_err()); assert!(parse_timestamp("2021-01-01T00:00:60Z").is_err()); assert!(parse_timestamp("2021-13-01T00:00:00Z").is_err()); assert!(parse_timestamp("ñotrfc3339").is_err()); assert!(fmt_timestamp(MAX_TIMESTAMP_SECS + 1, 0).is_err());
assert!(fmt_timestamp(0, -1).is_err());
}
#[test]
fn timestamp_rejects_non_digit_components() {
let cases = [
("+999-01-01T00:00:00Z", "bad year"),
("2021-+1-01T00:00:00Z", "bad month"),
("2021-01-+1T00:00:00Z", "bad day"),
("2021-01-01T+1:00:00Z", "bad hour"),
("2021-01-01T00:+1:00Z", "bad minute"),
("2021-01-01T00:00:+1Z", "bad second"),
("2021-01-01T00:00:00++1:00", "bad offset hours"),
("2021-01-01T00:00:00+01:+1", "bad offset minutes"),
("2021-01-01T00:00:00.+1Z", "bad fractional seconds"),
("2021-01-01T00:00:00.Z", "bad fractional seconds"),
];
for (input, expected) in cases {
assert_eq!(parse_timestamp(input), Err(expected), "{input}");
}
assert_eq!(parse_timestamp("1970-01-01T05:00:00+05:00"), Ok((0, 0)));
assert_eq!(
parse_timestamp("1970-01-01T00:00:00-23:59"),
Ok((86_340, 0))
);
}
#[test]
fn duration_round_trip() {
let cases = [
(0, 0, "0s"),
(1, 500_000_000, "1.500s"),
(-1, -500_000_000, "-1.500s"),
(0, -1, "-0.000000001s"),
(MAX_DURATION_SECS, 999_999_999, "315576000000.999999999s"),
];
for (secs, nanos, expected) in cases {
assert_eq!(fmt_duration(secs, nanos).unwrap(), expected);
assert_eq!(parse_duration(expected).unwrap(), (secs, nanos));
}
}
#[test]
fn duration_rejects_invalid() {
assert!(fmt_duration(MAX_DURATION_SECS + 1, 0).is_err());
assert!(fmt_duration(1, -1).is_err()); assert!(fmt_duration(0, 1_000_000_000).is_err()); assert!(parse_duration("--5s").is_err()); assert!(parse_duration("1.s").is_err()); assert!(parse_duration("-1.s").is_err()); assert!(parse_duration("1.5").is_err()); assert!(parse_duration("1.5e9s").is_err()); assert_eq!(parse_duration("1.0s"), Ok((1, 0)));
}
#[test]
fn snake_to_camel_preserves_conversion_edges() {
for (path, expected) in [
("", ""),
("plain", "plain"),
("*", "*"),
("foo_bar_baz", "fooBarBaz"),
("_foo", "Foo"),
("foo_", "foo"),
("foo__bar", "fooBar"),
("foo_3_bar", "foo3Bar"),
(".", "."),
("..", ".."),
(".foo_bar.", ".fooBar."),
("foo_.bar_baz", "foo.barBaz"),
("_._foo", ".Foo"),
("foo_.._bar", "foo..Bar"),
("café_au_lait", "caféAuLait"),
("foo_ß._é", "fooSS.É"),
("İ_σ", "İΣ"),
("😀_foo.日_本", "😀Foo.日本"),
] {
assert_eq!(snake_to_camel(path), expected, "path: {path:?}");
}
}
#[test]
fn camel_to_snake_preserves_conversion_edges() {
for (path, expected) in [
("", ""),
("plain", "plain"),
("*", "*"),
("fooBarBaz", "foo_bar_baz"),
("Foo", "_foo"),
("URLValue", "_u_r_l_value"),
("fooBar3", "foo_bar3"),
("_fooBar", "_foo_bar"),
("foo_bar", "foo_bar"),
(".", "."),
("..", ".."),
(".FooBar.", "._foo_bar."),
("Foo..Bar", "_foo.._bar"),
("caféAuLait", "café_au_lait"),
("İstanbul.Σ", "_i\u{307}stanbul._σ"),
("😀Foo.日本", "😀_foo.日本"),
] {
assert_eq!(camel_to_snake(path), expected, "path: {path:?}");
}
}
#[test]
fn field_mask_nested_paths_round_trip() {
for path in [
"a.b.c.d",
"user.profile.display_name",
"_user._profile._display_name",
"foo1.bar2.baz3_qux4",
] {
assert!(field_mask_path_round_trips(path), "path: {path:?}");
assert_eq!(camel_to_snake(&snake_to_camel(path)), path);
}
}
#[test]
fn field_mask_path_identifier_and_underscore_rules() {
for path in ["a", "a0", "_a", "_a0", "a_b", "a0_b1", "_a._b", "*"] {
assert!(field_mask_path_round_trips(path), "path: {path:?}");
}
for path in [
"_", "__a", "_0", "a_", "a__b", "a_0", "a_.b", "a._", "0a", "a.0b", "a.*", "*.a",
"a\0b", "a\nb", "café", "日本", "a.É", "a_é", "a_😀",
] {
assert!(!field_mask_path_round_trips(path), "path: {path:?}");
}
let long_path = "_a0.b_c1.".repeat(128) + "d_e2";
assert!(field_mask_path_round_trips(&long_path));
assert!(!field_mask_path_round_trips(&(long_path + "_")));
}
#[test]
fn field_mask_validation_matches_conversion_round_trip() {
fn check_paths(path: &mut String, remaining: u8) {
let identifiers = path.split('.').all(|component| {
let mut chars = component.chars();
matches!(chars.next(), Some('a'..='z' | '_'))
&& chars.all(|ch| matches!(ch, 'a'..='z' | '0'..='9' | '_'))
});
let expected =
path == "*" || (identifiers && camel_to_snake(&snake_to_camel(path)) == *path);
assert_eq!(
field_mask_path_round_trips(path),
expected,
"path: {path:?}"
);
if remaining > 0 {
for ch in ['a', 'z', '0', '9', '_', '.', 'A', '*', 'é', '\0'] {
path.push(ch);
check_paths(path, remaining - 1);
path.pop();
}
}
}
check_paths(&mut String::new(), 5);
}
#[test]
fn field_mask_round_trip() {
assert_eq!(snake_to_camel("foo_bar"), "fooBar");
assert_eq!(camel_to_snake("fooBar"), "foo_bar");
assert_eq!(snake_to_camel("user.first_name"), "user.firstName");
assert_eq!(snake_to_camel("_foo"), "Foo");
assert_eq!(camel_to_snake("Foo"), "_foo");
assert_eq!(snake_to_camel("foo._bar"), "foo.Bar");
assert_eq!(camel_to_snake("foo.Bar"), "foo._bar");
assert!(field_mask_path_round_trips("_foo"));
assert!(field_mask_path_round_trips("foo._bar"));
assert!(field_mask_path_round_trips("foo_bar"));
assert!(field_mask_path_round_trips("user.first_name"));
assert!(field_mask_path_round_trips("*"));
assert!(!field_mask_path_round_trips(""));
assert!(!field_mask_path_round_trips("foo."));
assert!(!field_mask_path_round_trips(".foo"));
assert!(!field_mask_path_round_trips("foo..bar"));
assert!(!field_mask_path_round_trips("foo__bar"));
assert!(!field_mask_path_round_trips("foo_3_bar"));
assert!(!field_mask_path_round_trips("fooBar"));
assert!(!field_mask_path_round_trips("foo bar"));
assert!(!field_mask_path_round_trips("foo-bar"));
assert!(!field_mask_path_round_trips("foo/bar"));
assert!(!field_mask_path_round_trips("3d"));
assert!(field_mask_path_round_trips("foo3_bar"));
assert!(field_mask_path_round_trips("_foo.bar1"));
}
}