Skip to main content

gadk_platform/
go_time.rs

1// Copyright 2026 Chris Olson
2// Portions derived from ADK-Go (https://github.com/google/adk-go), Copyright 2026 Google LLC.
3//
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at
7//
8//     http://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15
16//! Time parsing and formatting shared by the gadk crates: RFC 3339 parsing
17//! ([`go_parse_rfc3339`]) and formatting ([`go_format_rfc3339_nano`]), a signed nanosecond
18//! duration ([`GoDuration`]), duration-string parsing ([`go_parse_duration`]) and formatting
19//! ([`go_format_duration`]).
20
21use std::fmt;
22
23use chrono::{DateTime, NaiveDate, TimeDelta, TimeZone, Timelike, Utc};
24
25/// A duration as signed nanoseconds.
26#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
27pub struct GoDuration(pub i64);
28
29impl GoDuration {
30    /// One nanosecond.
31    pub const NANOSECOND: GoDuration = GoDuration(1);
32    /// One microsecond.
33    pub const MICROSECOND: GoDuration = GoDuration(1_000);
34    /// One millisecond.
35    pub const MILLISECOND: GoDuration = GoDuration(1_000_000);
36    /// One second.
37    pub const SECOND: GoDuration = GoDuration(1_000_000_000);
38    /// One minute.
39    pub const MINUTE: GoDuration = GoDuration(60 * 1_000_000_000);
40    /// One hour.
41    pub const HOUR: GoDuration = GoDuration(3600 * 1_000_000_000);
42
43    /// `s` seconds, saturating at the `i64` range.
44    pub const fn from_secs(s: i64) -> GoDuration {
45        GoDuration(s.saturating_mul(1_000_000_000))
46    }
47
48    /// `None` for a negative duration.
49    pub fn to_std(self) -> Option<std::time::Duration> {
50        u64::try_from(self.0)
51            .ok()
52            .map(std::time::Duration::from_nanos)
53    }
54
55    /// Saturates at `i64::MAX` nanoseconds.
56    pub fn from_std(d: std::time::Duration) -> GoDuration {
57        GoDuration(i64::try_from(d.as_nanos()).unwrap_or(i64::MAX))
58    }
59}
60
61/// Displays as [`go_format_duration`] (e.g. `1m30s`).
62impl fmt::Display for GoDuration {
63    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
64        f.write_str(&go_format_duration(*self))
65    }
66}
67
68/// Parses a duration string: a possibly signed sequence of decimal numbers, each with an
69/// optional fraction and a unit suffix (`ns`, `us`/`µs`/`μs`, `ms`, `s`, `m`, `h`), such as
70/// `"300ms"`, `"-1.5h"` or `"2h45m"`. `Err` is the message, e.g. `invalid duration "x"`,
71/// `missing unit in duration "1"`, `unknown unit "d" in duration "1d"`.
72pub fn go_parse_duration(s: &str) -> Result<GoDuration, String> {
73    parse_duration_bytes(s.as_bytes())
74}
75
76const LIMIT: u64 = 1 << 63;
77
78/// The error message for a malformed duration: `{message} "<quoted input>"`.
79fn duration_error(message: &str, orig: &[u8]) -> String {
80    format!("{message} {}", time_quote(orig))
81}
82
83/// Parses a duration over bytes (which need not be UTF-8).
84fn parse_duration_bytes(orig: &[u8]) -> Result<GoDuration, String> {
85    let invalid = || duration_error("invalid duration", orig);
86    let mut s = orig;
87    let mut neg = false;
88    if let Some(&c) = s.first()
89        && (c == b'-' || c == b'+')
90    {
91        neg = c == b'-';
92        s = &s[1..];
93    }
94    if s == b"0" {
95        return Ok(GoDuration(0));
96    }
97    if s.is_empty() {
98        return Err(invalid());
99    }
100    let mut d: u64 = 0;
101    while let Some(&first) = s.first() {
102        if !(first == b'.' || first.is_ascii_digit()) {
103            return Err(invalid());
104        }
105        // Consume `[0-9]*`.
106        let before = s.len();
107        let mut v: u64 = 0;
108        while let Some(&c) = s.first() {
109            if !c.is_ascii_digit() {
110                break;
111            }
112            if v > LIMIT / 10 {
113                return Err(invalid());
114            }
115            v = v * 10 + u64::from(c - b'0');
116            if v > LIMIT {
117                return Err(invalid());
118            }
119            s = &s[1..];
120        }
121        let pre = before != s.len();
122        // Consume `(\.[0-9]*)?`.
123        let mut f: u64 = 0;
124        let mut scale: f64 = 1.0;
125        let mut post = false;
126        if s.first() == Some(&b'.') {
127            s = &s[1..];
128            let before = s.len();
129            let mut overflow = false;
130            while let Some(&c) = s.first() {
131                if !c.is_ascii_digit() {
132                    break;
133                }
134                s = &s[1..];
135                if overflow {
136                    continue;
137                }
138                if f > (LIMIT - 1) / 10 {
139                    overflow = true;
140                    continue;
141                }
142                let y = f * 10 + u64::from(c - b'0');
143                if y > LIMIT {
144                    overflow = true;
145                    continue;
146                }
147                f = y;
148                scale *= 10.0;
149            }
150            post = before != s.len();
151        }
152        if !pre && !post {
153            // No digits (e.g. ".s" or "-.s").
154            return Err(invalid());
155        }
156        // Consume the unit.
157        let i = s
158            .iter()
159            .position(|&c| c == b'.' || c.is_ascii_digit())
160            .unwrap_or(s.len());
161        if i == 0 {
162            return Err(duration_error("missing unit in duration", orig));
163        }
164        let (u, rest) = s.split_at(i);
165        s = rest;
166        let unit: u64 = match u {
167            b"ns" => 1,
168            // "us", "µs" (U+00B5 micro sign), "μs" (U+03BC Greek mu).
169            b"us" | b"\xc2\xb5s" | b"\xce\xbcs" => 1_000,
170            b"ms" => 1_000_000,
171            b"s" => 1_000_000_000,
172            b"m" => 60 * 1_000_000_000,
173            b"h" => 3600 * 1_000_000_000,
174            _ => {
175                let message = format!("unknown unit {} in duration", time_quote(u));
176                return Err(duration_error(&message, orig));
177            }
178        };
179        if v > LIMIT / unit {
180            return Err(invalid());
181        }
182        v *= unit;
183        if f > 0 {
184            // `v += (f as f64 * (unit / scale)) as u64`, a truncating conversion;
185            // the addend is at most 3.6e12 (ns per hour), so neither cast loses range.
186            #[allow(
187                clippy::cast_precision_loss,
188                clippy::cast_possible_truncation,
189                clippy::cast_sign_loss
190            )]
191            let frac = (f as f64 * (unit as f64 / scale)) as u64;
192            v += frac;
193            if v > LIMIT {
194                return Err(invalid());
195            }
196        }
197        // The u64 addition wraps: both terms are at most 2^63, so only 2^63 + 2^63 wraps,
198        // to 0, which then passes the check (`"9223372036854775808ns"` parses twice as 0).
199        d = d.wrapping_add(v);
200        if d > LIMIT {
201            return Err(invalid());
202        }
203    }
204    if neg {
205        // Negation wraps 2^63 to `i64::MIN`.
206        return Ok(GoDuration(0i64.wrapping_sub_unsigned(d)));
207    }
208    i64::try_from(d).map(GoDuration).map_err(|_| invalid())
209}
210
211/// Quotes `s` in double quotes, `"` and `\` backslash-escaped, and every byte of a control
212/// character or a non-ASCII character written as `\xNN` (an invalid byte is one character of
213/// width 1; an encoded U+FFFD is three bytes).
214fn time_quote(s: &[u8]) -> String {
215    let mut out = String::with_capacity(s.len() + 2);
216    out.push('"');
217    let mut i = 0;
218    while i < s.len() {
219        let (c, width) = decode_rune(&s[i..]);
220        if !(' '..'\u{80}').contains(&c) {
221            for b in &s[i..i + width] {
222                out.push_str(&format!("\\x{b:02x}"));
223            }
224        } else {
225            if c == '"' || c == '\\' {
226                out.push('\\');
227            }
228            out.push(c);
229        }
230        i += width;
231    }
232    out.push('"');
233    out
234}
235
236/// The first character of `s` and its byte width; an invalid byte is U+FFFD of width 1. `s`
237/// must not be empty.
238fn decode_rune(s: &[u8]) -> (char, usize) {
239    let valid = s
240        .utf8_chunks()
241        .next()
242        .map(|chunk| chunk.valid())
243        .unwrap_or_default();
244    match valid.chars().next() {
245        Some(c) => (c, c.len_utf8()),
246        None => (char::REPLACEMENT_CHARACTER, 1),
247    }
248}
249
250/// Formats a duration: `"0s"`; under one second the largest of ns, µs and ms that keeps an
251/// integer part (`"1.5µs"`, `"500ms"`); from one second up `[Nh][Nm]S[.fff]s` with hours and
252/// minutes written once a larger unit is present (`"1m0s"`, `"1h0m0s"`); a leading `-` for a
253/// negative duration.
254pub fn go_format_duration(d: GoDuration) -> String {
255    let mut u = d.0.unsigned_abs();
256    let mut out = String::new();
257    if u < 1_000_000_000 {
258        let (unit, prec) = match u {
259            0 => return "0s".to_string(),
260            1..1_000 => ("ns", 0),
261            1_000..1_000_000 => ("µs", 3),
262            _ => ("ms", 6),
263        };
264        let frac = fmt_frac(&mut u, prec);
265        out.push_str(&format!("{u}{frac}{unit}"));
266    } else {
267        let frac = fmt_frac(&mut u, 9);
268        let secs = u % 60;
269        u /= 60;
270        if u > 0 {
271            let mins = u % 60;
272            u /= 60;
273            if u > 0 {
274                out.push_str(&format!("{u}h"));
275            }
276            out.push_str(&format!("{mins}m"));
277        }
278        out.push_str(&format!("{secs}{frac}s"));
279    }
280    if d.0 < 0 {
281        out.insert(0, '-');
282    }
283    out
284}
285
286/// Divides `v` by `10^prec` and returns the fraction as `.ddd` with trailing zeros dropped
287/// (empty, without the point, when the fraction is zero).
288fn fmt_frac(v: &mut u64, prec: u32) -> String {
289    let p = 10u64.pow(prec);
290    let frac = *v % p;
291    *v /= p;
292    if frac == 0 {
293        return String::new();
294    }
295    let digits = format!("{frac:0width$}", width = prec as usize);
296    format!(".{}", digits.trim_end_matches('0'))
297}
298
299/// Parses an RFC 3339 timestamp (`YYYY-MM-DDThh:mm:ss`, optional fraction, then `Z` or an
300/// offset), reduced to the instant.
301/// The accepted forms are:
302/// - exactly four year digits and two month and day digits, with the day checked against the
303///   month (leap years included);
304/// - a one- or two-digit hour (0-23), and two-digit minutes and seconds (0-59, so a leap
305///   second fails);
306/// - an optional fraction after '.' or ',' (digits past the ninth are dropped);
307/// - 'Z', or ±hh:mm with hh ≤ 24 and mm ≤ 60. 'T' and 'Z' are case-sensitive, and nothing may
308///   follow the zone.
309pub fn go_parse_rfc3339(s: &str) -> Option<DateTime<Utc>> {
310    let s = s.as_bytes();
311    let digits = |at: usize, n: usize| -> Option<u32> {
312        s.get(at..at + n)?.iter().try_fold(0u32, |acc, &b| {
313            b.is_ascii_digit().then(|| acc * 10 + u32::from(b - b'0'))
314        })
315    };
316    let literal = |at: usize, want: u8| (s.get(at) == Some(&want)).then_some(());
317
318    let year = digits(0, 4)?;
319    literal(4, b'-')?;
320    let month = digits(5, 2)?;
321    literal(7, b'-')?;
322    let day = digits(8, 2)?;
323    literal(10, b'T')?;
324    let hour_len = if s.get(12).is_some_and(u8::is_ascii_digit) {
325        2
326    } else {
327        1
328    };
329    let hour = digits(11, hour_len)?;
330    let mut i = 11 + hour_len;
331    literal(i, b':')?;
332    let min = digits(i + 1, 2)?;
333    literal(i + 3, b':')?;
334    let sec = digits(i + 4, 2)?;
335    i += 6;
336
337    let mut nanos = 0u32;
338    if matches!(s.get(i), Some(b'.' | b',')) && s.get(i + 1).is_some_and(u8::is_ascii_digit) {
339        let start = i + 1;
340        let mut end = start;
341        while s.get(end).is_some_and(u8::is_ascii_digit) {
342            end += 1;
343        }
344        let used = &s[start..end.min(start + 9)];
345        nanos = used
346            .iter()
347            .fold(0, |acc, &b| acc * 10 + u32::from(b - b'0'));
348        for _ in used.len()..9 {
349            nanos *= 10;
350        }
351        i = end;
352    }
353
354    let offset = match s.get(i) {
355        Some(b'Z') => {
356            i += 1;
357            0
358        }
359        Some(&sign @ (b'+' | b'-')) => {
360            literal(i + 3, b':')?;
361            let hh = digits(i + 1, 2)?;
362            let mm = digits(i + 4, 2)?;
363            if hh > 24 || mm > 60 {
364                return None;
365            }
366            i += 6;
367            let off = i64::from(hh * 3600 + mm * 60);
368            if sign == b'-' { -off } else { off }
369        }
370        _ => return None,
371    };
372    if i != s.len() || !(1..=12).contains(&month) || hour > 23 || min > 59 || sec > 59 {
373        return None;
374    }
375    let date = NaiveDate::from_ymd_opt(i32::try_from(year).ok()?, month, day)?;
376    let at = date.and_hms_nano_opt(hour, min, sec, nanos)?.and_utc();
377    at.checked_sub_signed(TimeDelta::try_seconds(offset)?)
378}
379
380/// Formats `t` as RFC 3339 with up to nanosecond precision, in its own
381/// zone: the fraction's trailing zeros trimmed (the fraction dropped when zero), `Z` for a zero
382/// offset, `±hh:mm` otherwise. Callers that marshal to JSON must check for themselves that the
383/// year is within 0..=9999.
384pub fn go_format_rfc3339_nano<Tz: TimeZone>(t: &DateTime<Tz>) -> String {
385    let t = t.fixed_offset();
386    let mut s = t.format("%Y-%m-%dT%H:%M:%S").to_string();
387    let nanos = t.nanosecond() % 1_000_000_000;
388    if nanos != 0 {
389        let frac = format!("{nanos:09}");
390        s.push('.');
391        s.push_str(frac.trim_end_matches('0'));
392    }
393    if t.offset().local_minus_utc() == 0 {
394        s.push('Z');
395    } else {
396        s.push_str(&t.format("%:z").to_string());
397    }
398    s
399}
400
401#[cfg(test)]
402#[allow(clippy::unwrap_used)]
403mod tests {
404    use chrono::FixedOffset;
405
406    use super::*;
407
408    /// The rows of Go `TestParseDurationErrors` (time_test.go) whose input is not valid UTF-8,
409    /// which `go_parse_duration(&str)` cannot receive: the byte-level parser and Go's
410    /// `time.quote` give Go's full error text.
411    #[test]
412    fn parse_duration_errors_on_non_utf8_input() {
413        let cases: &[(&[u8], &str)] = &[
414            (b"\x85\x85", r#"invalid duration "\x85\x85""#),
415            (b"\xffff", r#"invalid duration "\xffff""#),
416            (
417                b"hello \xffff world",
418                r#"invalid duration "hello \xffff world""#,
419            ),
420            (b"1\xff", r#"unknown unit "\xff" in duration "1\xff""#),
421        ];
422        for (input, want) in cases {
423            assert_eq!(parse_duration_bytes(input).unwrap_err(), *want, "{input:?}");
424        }
425    }
426
427    /// Go `time.RFC3339Nano`: trimmed fraction, `Z` for UTC, `±hh:mm` otherwise.
428    #[test]
429    fn go_format_rfc3339_nano_matches_go() {
430        let utc = FixedOffset::east_opt(0).unwrap();
431        let cst = FixedOffset::west_opt(6 * 3600).unwrap();
432        let at = |o: FixedOffset, ns: u32| {
433            o.with_ymd_and_hms(2026, 1, 2, 3, 4, 5)
434                .unwrap()
435                .with_nanosecond(ns)
436                .unwrap()
437        };
438        assert_eq!(go_format_rfc3339_nano(&at(utc, 0)), "2026-01-02T03:04:05Z");
439        assert_eq!(
440            go_format_rfc3339_nano(&at(cst, 256_916_000)),
441            "2026-01-02T03:04:05.256916-06:00"
442        );
443        assert_eq!(
444            go_format_rfc3339_nano(&at(utc, 1)),
445            "2026-01-02T03:04:05.000000001Z"
446        );
447        let t = Utc.with_ymd_and_hms(2026, 7, 17, 10, 0, 0).unwrap();
448        assert_eq!(
449            go_format_rfc3339_nano(&(t + TimeDelta::microseconds(1500))),
450            "2026-07-17T10:00:00.0015Z"
451        );
452    }
453
454    /// Every row's expectation is what Go's `time.Parse(time.RFC3339, input)` returned
455    /// (go1.27, module go 1.26), as a UTC instant; `None` is a parse error (the zero time).
456    #[test]
457    fn go_parse_rfc3339_matches_go_time_parse() {
458        let cases: &[(&str, Option<&str>)] = &[
459            ("2999-01-01T00:00:00Z", Some("2999-01-01T00:00:00Z")),
460            ("2999-01-01t00:00:00Z", None),
461            ("2999-01-01T00:00:00z", None),
462            ("2999-01-01 00:00:00Z", None),
463            ("2016-12-31T23:59:60Z", None),
464            (
465                "2999-01-01T00:00:00.123+05:30",
466                Some("2998-12-31T18:30:00.123Z"),
467            ),
468            ("2999-01-01T00:00:00,5Z", Some("2999-01-01T00:00:00.5Z")),
469            ("2999-01-01T24:00:00Z", None),
470            ("2999-01-01T00:00:00+24:00", Some("2998-12-31T00:00:00Z")),
471            ("2999-02-29T00:00:00Z", None),
472            ("2000-02-29T00:00:00Z", Some("2000-02-29T00:00:00Z")),
473            (
474                "2999-01-01T00:00:00.123456789123Z",
475                Some("2999-01-01T00:00:00.123456789Z"),
476            ),
477            ("2999-01-01T00:00:00+05:60", Some("2998-12-31T18:00:00Z")),
478            ("2999-01-01T00:00:00+25:00", None),
479            ("2999-01-01T00:00:00.Z", None),
480            ("2999-01-01T00:00:00", None),
481            ("0000-01-01T00:00:00Z", Some("0000-01-01T00:00:00Z")),
482            ("2999-01-01T00:00:00-01:30", Some("2999-01-01T01:30:00Z")),
483            ("2999-1-01T00:00:00Z", None),
484            ("2999-01-01T0:00:00Z", Some("2999-01-01T00:00:00Z")),
485            ("2999-01-01T00:00:00+0530", None),
486            ("2999-01-01T00:00:00 Z", None),
487            ("2999-01-01T00:00:00Z ", None),
488            ("+2999-01-01T00:00:00Z", None),
489            ("2999-01-01T00:00:00.5", None),
490            (
491                "2999-01-01T00:00:00.000000001Z",
492                Some("2999-01-01T00:00:00.000000001Z"),
493            ),
494            ("", None),
495            ("not-a-time", None),
496        ];
497        for (input, want) in cases {
498            let want = want.map(|w| DateTime::parse_from_rfc3339(w).unwrap().with_timezone(&Utc));
499            assert_eq!(go_parse_rfc3339(input), want, "go_parse_rfc3339({input:?})");
500        }
501    }
502}