reallyme-buffa 0.1.3

ReallyMe fork: A pure Rust Protocol Buffers implementation with first-class editions support
Documentation
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
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
// Modified by ReallyMe Technologies Limited.
//! Shared formatting and parsing helpers for well-known type JSON forms.
//!
//! These are the proto3-canonical-JSON representations for `Timestamp`,
//! `Duration`, and `FieldMask`. They operate on raw scalars (`(i64, i32)`,
//! `&str`) rather than the WKT structs so they can be shared between
//! `buffa-types`'s typed serde impls and `buffa-descriptor`'s reflective
//! [`DynamicMessage`](https://docs.rs/reallyme-buffa-descriptor) JSON codec without
//! a dependency edge between those crates. Both crates depend on `buffa`.
//!
//! Sharing the implementation is load-bearing: the conformance suite exercises
//! both the typed and reflective JSON paths, and a divergence between them
//! (e.g. one accepting a fractional-second precision the other rejects)
//! would be a user-visible inconsistency.

use crate::alloc::string::String;

// ── String input ────────────────────────────────────────────────────────────

/// Deserialize the JSON string that holds a `Timestamp`, `Duration` or
/// `FieldMask`.
///
/// Unlike `String::deserialize`, this rejects a non-string input without
/// echoing its value in the error.
///
/// # Errors
///
/// Returns the deserializer's `invalid_type` error for any input that is not
/// a string.
pub fn deserialize_string<'de, D: serde::Deserializer<'de>>(d: D) -> Result<String, D::Error> {
    struct V;
    impl<'de> serde::de::Visitor<'de> for V {
        type Value = String;
        fn expecting(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
            f.write_str("a string")
        }
        fn visit_enum<A: serde::de::EnumAccess<'de>>(
            self,
            tagged: A,
        ) -> Result<Self::Value, A::Error> {
            crate::json_helpers::deserialize_tagged(self, tagged)
        }
        fn visit_str<E>(self, v: &str) -> Result<String, E> {
            Ok(String::from(v))
        }
        fn visit_string<E>(self, v: String) -> Result<String, E> {
            Ok(v)
        }
        crate::reject_other_json_kinds!(bool, i64, u64, i128, u128, f64, bytes, byte_buf);
    }
    // `deserialize_any` so a non-string reaches `V`: `deserialize_string`
    // lets the deserializer format the mismatched value itself.
    if d.is_human_readable() {
        d.deserialize_any(V)
    } else {
        d.deserialize_string(V)
    }
}

// ── Bounds ──────────────────────────────────────────────────────────────────

/// Smallest valid `Timestamp.seconds`: `0001-01-01T00:00:00Z`.
pub const MIN_TIMESTAMP_SECS: i64 = -62_135_596_800;
/// Largest valid `Timestamp.seconds`: `9999-12-31T23:59:59Z`.
pub const MAX_TIMESTAMP_SECS: i64 = 253_402_300_799;
/// Largest valid `Duration.seconds` magnitude (10 000 years).
pub const MAX_DURATION_SECS: i64 = 315_576_000_000;

/// Parse a digits-only RFC 3339 component, requiring every byte to be an
/// ASCII digit.
///
/// Integer `from_str` accepts a leading `+` — for the unsigned types too, so
/// `"+1".parse::<u8>()` is `Ok(1)` — which would let a component take a sign
/// the grammar does not allow and parse to a silently wrong value
/// (`"+999-01-01T00:00:00Z"` as year 999). The digit check runs first, so
/// `err` names the offending component either way.
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);
    }
    // Unreachable at every current call site — the widths bound the value
    // below each target type's maximum (4 digits into `i64`, 2 into `u8`,
    // 9 into `i32`) — so this arm is defensive rather than covered by a test.
    s.parse().map_err(|_| err)
}

// ── Timestamp ───────────────────────────────────────────────────────────────

/// Format unix `(seconds, nanos)` as an RFC 3339 timestamp with a `Z` suffix
/// and the minimal fractional-seconds precision (0, 3, 6, or 9 digits).
///
/// # Errors
///
/// Returns an error if the timestamp is outside the proto3 `Timestamp`
/// range (`0001-01-01T00:00:00Z` through `9999-12-31T23:59:59.999999999Z`)
/// or `nanos` is outside `[0, 999_999_999]`.
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)
}

/// A protobuf temporal validation or formatting failure.
#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
pub enum TemporalFormatError {
    /// Nanoseconds are outside the Timestamp range.
    #[error("Timestamp nanos out of range")]
    TimestampNanos,
    /// Seconds are outside the Timestamp range.
    #[error("Timestamp seconds out of range")]
    TimestampSeconds,
    /// The calendar year is outside 0001 through 9999.
    #[error("Timestamp year out of range")]
    TimestampYear,
    /// Duration signs or magnitudes are invalid.
    #[error("invalid Duration")]
    Duration,
    /// The destination writer rejected the output.
    #[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",
        }
    }
}

/// Write a canonical UTC timestamp directly into caller-owned storage.
/// At most thirty ASCII bytes are written; no intermediate String is allocated.
/// # Errors
/// Returns a typed validation error or reports failure of the destination writer.
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.is_multiple_of(1_000_000) {
        write!(output, ".{:03}", nanos / 1_000_000)
    } else if nanos.is_multiple_of(1_000) {
        write!(output, ".{:06}", nanos / 1_000)
    } else {
        write!(output, ".{nanos:09}")
    }
    .map_err(|_| TemporalFormatError::Write)
}

/// Parse an RFC 3339 timestamp into unix `(seconds, nanos)`.
///
/// Accepts an uppercase `Z` suffix and `+HH:MM` / `-HH:MM` UTC offsets.
/// Rejects lowercase `t`/`z` (the proto3 JSON spec requires uppercase) and
/// anything outside the proto3 `Timestamp` range. Every component is
/// digits-only, so a signed one — `"+999-01-01T00:00:00Z"` — is rejected
/// even though integer `from_str` would accept it.
///
/// # Errors
///
/// Returns an error describing the first malformed component.
pub fn parse_timestamp(s: &str) -> Result<(i64, i32), &'static str> {
    // RFC 3339 timestamps are pure ASCII. Reject non-ASCII early so byte
    // slices below stay on char boundaries.
    if !s.is_ascii() {
        return Err("non-ASCII in timestamp");
    }
    // Proto3 JSON spec requires uppercase 'Z' suffix (not lowercase).
    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))
    };

    // Proto3 JSON spec requires uppercase 'T' separator (not lowercase).
    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")?;
    // Proto3 Timestamp uses unix epoch seconds, which has no leap-second
    // representation, so reject second 60.
    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;
    // The offset can push a boundary timestamp past the valid range
    // (`"9999-12-31T23:59:59-23:59"` has year 9999 but the UTC equivalent
    // is year 10000).
    if !(MIN_TIMESTAMP_SECS..=MAX_TIMESTAMP_SECS).contains(&unix) {
        return Err("Timestamp out of range after applying offset");
    }
    Ok((unix, nanos))
}

// ── Duration ────────────────────────────────────────────────────────────────

/// Format `(seconds, nanos)` as a `"3.5s"`-style decimal seconds string with
/// the minimal fractional precision.
///
/// # Errors
///
/// Returns an error if `(seconds, nanos)` violate the `Duration` invariants:
/// magnitude bounds, or `seconds` and `nanos` having opposite signs.
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)
}

/// Write a canonical Duration directly into caller-owned storage.
/// At most twenty-four ASCII bytes are written; no intermediate String is allocated.
/// # Errors
/// Returns a typed validation error or reports failure of the destination writer.
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)
}

/// Parse a `"3.5s"`-style decimal seconds string into `(seconds, nanos)`.
///
/// # Errors
///
/// Returns an error on a malformed string or a value outside the `Duration`
/// range. If a decimal point is present, it must be followed by 1–9 digits.
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
    };
    // Reject residual sign after stripping: "--5s" would otherwise parse as
    // -5 via i64::parse and the double negation would yield +5 silently.
    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))
}

/// Validate the proto3 `Duration` invariants: `|seconds| ≤ 315 576 000 000`,
/// `|nanos| ≤ 999 999 999`, and `seconds` and `nanos` have the same sign or
/// one of them is zero.
///
/// # Errors
///
/// Returns an error naming the violated invariant.
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(())
}

// ── FieldMask ───────────────────────────────────────────────────────────────

/// Convert a snake_case field-mask path to lowerCamelCase, handling dotted
/// sub-paths.
///
/// Does **not** validate round-trip safety — pair with a
/// `field_mask_path_round_trips` check before serializing per the spec.
#[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
}

/// Convert a lowerCamelCase field-mask path to snake_case, handling dotted
/// sub-paths.
///
/// A leading uppercase letter produces a leading underscore (`Foo` → `_foo`),
/// the inverse of [`snake_to_camel`] on a field named `_foo`; `_` is a legal
/// first character in a proto field name.
#[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
}

/// Whether a snake_case `FieldMask` path is valid in proto3 JSON.
///
/// Every dotted component must be an ASCII identifier of the form
/// `[a-z_][a-z0-9_]*` (C++ accepts only `[0-9a-zA-Z.]` in the JSON form;
/// protobuf-go requires each snake-cased component to be a valid proto
/// name), and every underscore must be followed by a lowercase letter. The
/// second rule is the condition under which
/// `camel_to_snake(snake_to_camel(p)) == p`: it rejects a double underscore
/// (`foo__bar`), a digit after an underscore (`foo_3_bar`) and a trailing
/// underscore (`foo_`). Uppercase (`fooBar`), whitespace, `-`, `/` and other
/// non-identifier characters fail the first rule.
///
/// The exact path `*` is accepted as a deliberate divergence from both
/// references, which reject it: AIP-161 uses it as the full-mask wildcard
/// and it was accepted before the character check existed.
///
/// The name predates the character check and is kept for compatibility.
/// The check reads the path once and does not allocate.
#[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))
            })
    })
}

// ── Civil calendar ──────────────────────────────────────────────────────────
//
// Howard Hinnant's algorithms — see <http://howardhinnant.github.io/date_algorithms.html>.
// These convert between days-since-epoch (1970-01-01) and (year, month, day)
// civil dates without a calendar table or branching on month lengths.

/// Convert days-since-unix-epoch to a proleptic Gregorian `(year, month, day)`.
#[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 => {
            // Add the epoch offset to the bounded remainder instead.
            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)
}

/// Convert a proleptic Gregorian `(year, month, day)` to days-since-unix-epoch.
///
/// Returns `None` if the date is invalid (out-of-range month, or day exceeding
/// the Gregorian month length including the leap-year rule for February),
/// or if the day count cannot be represented as an `i64`.
#[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()
}

/// Days in `month` of `year` (1-indexed month). Validates the Gregorian
/// leap-year rule.
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()); // year 0
        assert!(parse_timestamp("2021-02-30T00:00:00Z").is_err()); // Feb 30
        assert!(parse_timestamp("2021-01-01t00:00:00Z").is_err()); // lowercase t
        assert!(parse_timestamp("2021-01-01T00:00:00z").is_err()); // lowercase z
        assert!(parse_timestamp("2021-01-01T00:00:60Z").is_err()); // leap second
        assert!(parse_timestamp("2021-13-01T00:00:00Z").is_err()); // month 13
        assert!(parse_timestamp("ñotrfc3339").is_err()); // non-ASCII
        assert!(fmt_timestamp(MAX_TIMESTAMP_SECS + 1, 0).is_err());
        assert!(fmt_timestamp(0, -1).is_err());
    }

    #[test]
    fn timestamp_rejects_non_digit_components() {
        // Integer `from_str` accepts a leading '+' for both signed and
        // unsigned types, so a component handed straight to `parse` would
        // take a sign RFC 3339 does not allow. The error names the component.
        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}");
        }
        // The digit check is a subset filter over the grammar, not a new
        // restriction: a numeric offset still parses.
        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()); // opposite signs
        assert!(fmt_duration(0, 1_000_000_000).is_err()); // nanos overflow
        assert!(parse_duration("--5s").is_err()); // double sign
        assert!(parse_duration("1.s").is_err()); // empty fraction
        assert!(parse_duration("-1.s").is_err()); // empty negative fraction
        assert!(parse_duration("1.5").is_err()); // no suffix
        assert!(parse_duration("1.5e9s").is_err()); // exponent
        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"));
    }
}