Skip to main content

basecamp_sdk/
types.rs

1//! The scalar types the model's shapes are built from.
2
3use std::fmt;
4use std::str::FromStr;
5
6use serde::{Deserialize, Deserializer, Serialize, Serializer};
7
8use crate::error::Error;
9
10/// An instant Basecamp reports, ISO 8601 with its offset, held in UTC: a [`jiff::Timestamp`],
11/// which reads RFC 3339 with any offset and writes it with `Z`.
12pub type DateTime = jiff::Timestamp;
13
14/// A calendar date without a time zone, as Basecamp writes `due_on` and `starts_on`.
15#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
16pub struct Date(pub jiff::civil::Date);
17
18impl Date {
19    /// A date from its parts, or `None` when they do not make one.
20    pub fn new(year: i32, month: u32, day: u32) -> Option<Date> {
21        let year = i16::try_from(year).ok()?;
22        let month = i8::try_from(month).ok()?;
23        let day = i8::try_from(day).ok()?;
24        jiff::civil::Date::new(year, month, day).ok().map(Date)
25    }
26
27    /// Reads `YYYY-MM-DD`.
28    pub fn parse(source: &str) -> Result<Date, Error> {
29        source
30            .parse()
31            .map_err(|error| Error::usage(format!("invalid date {source:?}: {error}")))
32    }
33}
34
35/// 1970-01-01, as it was when the date was chrono's: jiff's own default is year zero.
36impl Default for Date {
37    fn default() -> Date {
38        Date(jiff::civil::date(1970, 1, 1))
39    }
40}
41
42impl From<jiff::civil::Date> for Date {
43    fn from(date: jiff::civil::Date) -> Date {
44        Date(date)
45    }
46}
47
48impl From<Date> for jiff::civil::Date {
49    fn from(date: Date) -> jiff::civil::Date {
50        date.0
51    }
52}
53
54/// `YYYY-MM-DD`, through the same `%Y-%m-%d` that [`FromStr`] reads, so every date prints as
55/// something it reads back. jiff's own `Display` writes a year before 0 with six digits
56/// (`-000001`), which `%Y` does not read.
57impl fmt::Display for Date {
58    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
59        fmt::Display::fmt(&self.0.strftime("%Y-%m-%d"), f)
60    }
61}
62
63/// `YYYY-MM-DD` and nothing else. jiff's own `civil::Date` parser is wider — it takes
64/// `20240115`, and a full datetime whose time it drops — so a date is read with `strptime`.
65impl FromStr for Date {
66    type Err = jiff::Error;
67
68    fn from_str(source: &str) -> Result<Date, jiff::Error> {
69        jiff::civil::Date::strptime("%Y-%m-%d", source).map(Date)
70    }
71}
72
73impl Serialize for Date {
74    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
75        serializer.serialize_str(&self.to_string())
76    }
77}
78
79impl<'de> Deserialize<'de> for Date {
80    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Date, D::Error> {
81        let text = String::deserialize(deserializer)?;
82        text.parse().map_err(serde::de::Error::custom)
83    }
84}
85
86/// How a write addresses a date member: `Option<DateChange>` is the tri-state — `None`
87/// leaves the date alone, [`DateChange::Clear`] removes it, [`DateChange::On`] sets it.
88///
89/// On the wire a clear is `""`, which BC3 casts to nil, never `null` (SPEC §18). It is the
90/// type of every request member the spec marks `x-basecamp-clearable`.
91#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
92pub enum DateChange {
93    /// Remove the date.
94    Clear,
95    /// Set the date.
96    On(Date),
97}
98
99impl From<Date> for DateChange {
100    fn from(date: Date) -> DateChange {
101        DateChange::On(date)
102    }
103}
104
105impl Serialize for DateChange {
106    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
107        match self {
108            DateChange::Clear => serializer.serialize_str(""),
109            DateChange::On(date) => date.serialize(serializer),
110        }
111    }
112}
113
114impl<'de> Deserialize<'de> for DateChange {
115    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<DateChange, D::Error> {
116        let text = String::deserialize(deserializer)?;
117        if text.is_empty() {
118            Ok(DateChange::Clear)
119        } else {
120            text.parse()
121                .map(DateChange::On)
122                .map_err(serde::de::Error::custom)
123        }
124    }
125}
126
127/// A moment Basecamp writes either as a bare date (`2016-06-01`, an all-day entry) or as a
128/// full timestamp, and which the SDK round-trips verbatim rather than re-rendering.
129#[derive(Debug, Clone, PartialEq, Eq, Hash, Default, Serialize, Deserialize)]
130#[serde(transparent)]
131pub struct FlexibleTime(pub String);
132
133impl FlexibleTime {
134    /// The value as the API wrote it.
135    pub fn as_str(&self) -> &str {
136        &self.0
137    }
138
139    /// The value read as a date, when it is one.
140    pub fn date(&self) -> Option<Date> {
141        self.0.parse().ok()
142    }
143
144    /// The value read as an instant, when it is one.
145    pub fn datetime(&self) -> Option<DateTime> {
146        self.0.parse().ok()
147    }
148}
149
150impl From<&str> for FlexibleTime {
151    fn from(value: &str) -> FlexibleTime {
152        FlexibleTime(value.to_string())
153    }
154}
155
156impl From<String> for FlexibleTime {
157    fn from(value: String) -> FlexibleTime {
158        FlexibleTime(value)
159    }
160}
161
162impl fmt::Display for FlexibleTime {
163    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
164        f.write_str(&self.0)
165    }
166}
167
168/// Reads a nullable pixel dimension the API may spell as a float (`1024.0`), per SPEC §10.
169pub(crate) mod flex_int {
170    use serde::{Deserialize, Deserializer};
171
172    /// How far from an integer a number may sit and still read as it: the API computes some
173    /// dimensions in floating point and serves `752.0000000000001`. Go's `types.FlexIntTolerance`.
174    const TOLERANCE: f64 = 1e-6;
175
176    /// `null` is `None`; an integer, or a float within `TOLERANCE` of one, is the integer.
177    pub(crate) fn deserialize<'de, D: Deserializer<'de>>(
178        deserializer: D,
179    ) -> Result<Option<i32>, D::Error> {
180        match Option::<serde_json::Value>::deserialize(deserializer)? {
181            None | Some(serde_json::Value::Null) => Ok(None),
182            Some(serde_json::Value::Number(number)) => {
183                if let Some(value) = number.as_i64() {
184                    i32::try_from(value)
185                        .map(Some)
186                        .map_err(|_| serde::de::Error::custom("dimension out of range"))
187                } else if let Some(value) = number.as_f64() {
188                    let rounded = value.round();
189                    if (value - rounded).abs() > TOLERANCE {
190                        Err(serde::de::Error::custom("dimension is not integral"))
191                    } else if (f64::from(i32::MIN)..=f64::from(i32::MAX)).contains(&rounded) {
192                        #[allow(clippy::cast_possible_truncation)]
193                        Ok(Some(rounded as i32))
194                    } else {
195                        Err(serde::de::Error::custom("dimension out of range"))
196                    }
197                } else {
198                    Err(serde::de::Error::custom("dimension is not a number"))
199                }
200            }
201            Some(other) => Err(serde::de::Error::custom(format!(
202                "dimension is not a number: {other}"
203            ))),
204        }
205    }
206}
207
208/// Reads a 64-bit id the API may spell as a string. A string that is not a number — the
209/// `"basecamp"` system actor's id — reads as `0`, as Go's `FlexibleInt64` and Kotlin's
210/// `FlexibleLongSerializer` read it; a numeric string past 64 bits is still an error.
211///
212/// "Is a number" is Go's `strconv.ParseInt(s, 10, 64)` and nothing looser — see `parse_int`
213/// below for the grammar, for which refusal Go turns into `0` and which it raises, and for
214/// why the two cannot be told apart without walking the string the way Go walks it.
215pub(crate) mod flexible_i64 {
216    use serde::{Deserialize, Deserializer};
217
218    #[derive(Deserialize)]
219    #[serde(untagged)]
220    enum Flexible {
221        Number(i64),
222        Text(String),
223    }
224
225    /// An integer, a string holding one, or `0` for a non-numeric sentinel.
226    pub(crate) fn deserialize<'de, D: Deserializer<'de>>(deserializer: D) -> Result<i64, D::Error> {
227        match Flexible::deserialize(deserializer)? {
228            Flexible::Number(value) => Ok(value),
229            Flexible::Text(text) => from_text(&text).map_err(serde::de::Error::custom),
230        }
231    }
232
233    /// The string path of `FlexibleInt64` (`go/pkg/types/flexible_int64.go:34`): the two
234    /// error kinds `strconv.ParseInt` distinguishes, and what Go does with each — a syntax
235    /// error becomes `0` (`:46`), a range error is raised (`:43`).
236    fn from_text(text: &str) -> Result<i64, String> {
237        match parse_int(text) {
238            Ok(value) => Ok(value),
239            Err(Refusal::Syntax) => Ok(0),
240            Err(Refusal::Range) => Err(format!("integer id {text:?} does not fit 64 bits")),
241        }
242    }
243
244    /// Which way `strconv.ParseInt` refused. Keeping them apart is the whole point: Go
245    /// answers `0` to one and an error to the other, and no single "is this a number?"
246    /// predicate can tell them apart, because *which refusal comes first* depends on
247    /// where in the string each disqualifying byte sits.
248    enum Refusal {
249        Syntax,
250        Range,
251    }
252
253    /// `strconv.ParseInt(s, 10, 64)`, scan order included.
254    ///
255    /// It takes one optional ASCII sign, then one or more ASCII digits, and nothing else:
256    /// no whitespace (Go trims none, so `" 7"` is a syntax error and reads `0`), a leading
257    /// `+` accepted, `_` never a separator at base 10 (only base 0 allows it), and ASCII
258    /// digits alone, so a fullwidth `7` is not a digit.
259    ///
260    /// The subtlety worth the hand-rolled loop: `ParseUint` checks the magnitude *inside*
261    /// the scan and returns `ErrRange` the moment the accumulator would overflow `u64`,
262    /// before it ever looks at the rest of the string. So the first disqualifying byte
263    /// wins, and `"18446744073709551616x"` is a **range** error — Go raises it — while
264    /// `"18446744073709551615x"` is a **syntax** error and reads `0`. Testing the whole
265    /// string for well-formedness first gets that pair backwards.
266    ///
267    /// Note that this is *not* the rule the global-id parser applies to the person id in
268    /// `gid://bc3/Person/<id>`. That one walks the bytes and refuses anything outside
269    /// `0..=9` *before* it parses (`go/pkg/basecamp/mentions.go:252-256`), so it rejects a
270    /// leading `+` that this one accepts. Both live in this crate: `parse_global_id` in
271    /// [`crate::mentions`] carries that digit walk, and it is *correct* to, because the
272    /// reference has that shape at that site. The same shape was wrong here only because
273    /// the Go line governing this site has no pre-walk. Two sites, two rules, deliberately:
274    /// do not hoist either into the other, in either direction.
275    fn parse_int(text: &str) -> Result<i64, Refusal> {
276        let (negative, digits) = match text.as_bytes() {
277            [] => return Err(Refusal::Syntax),
278            [b'+', rest @ ..] => (false, rest),
279            [b'-', rest @ ..] => (true, rest),
280            whole => (false, whole),
281        };
282        // Unobservable through this consumer — an empty digit run accumulates 0 and a
283        // syntax refusal reads 0, so no test here can pin it — but it is Go's behaviour
284        // and it matters the moment `parse_int` is read by anything where the two differ.
285        if digits.is_empty() {
286            return Err(Refusal::Syntax);
287        }
288
289        // `ParseUint`'s loop, byte for byte.
290        let mut magnitude: u64 = 0;
291        for byte in digits {
292            if !byte.is_ascii_digit() {
293                return Err(Refusal::Syntax);
294            }
295            magnitude = magnitude
296                .checked_mul(10)
297                .and_then(|shifted| shifted.checked_add(u64::from(byte - b'0')))
298                .ok_or(Refusal::Range)?;
299        }
300
301        // `ParseInt`'s own bound, applied to what `ParseUint` returned.
302        if negative {
303            if magnitude > i64::MIN.unsigned_abs() {
304                return Err(Refusal::Range);
305            }
306            Ok(i64::try_from(magnitude).map_or(i64::MIN, |value| -value))
307        } else {
308            i64::try_from(magnitude).map_err(|_| Refusal::Range)
309        }
310    }
311
312    /// [`deserialize`], with `null` as `None`. The generator emits it for an optional
313    /// flexible id; the model has none today.
314    #[allow(dead_code)]
315    pub(crate) fn deserialize_optional<'de, D: Deserializer<'de>>(
316        deserializer: D,
317    ) -> Result<Option<i64>, D::Error> {
318        match Option::<Flexible>::deserialize(deserializer)? {
319            None => Ok(None),
320            Some(Flexible::Number(value)) => Ok(Some(value)),
321            Some(Flexible::Text(text)) => {
322                from_text(&text).map(Some).map_err(serde::de::Error::custom)
323            }
324        }
325    }
326}
327
328/// Reads a list of people the way the reference does. Go decodes `[]generated.Person`, and
329/// `encoding/json` leaves a `null` element as the zero `Person` — id `0`, empty name — rather
330/// than failing the read, so a merge-safe write that reads the list back sends `0` for it. The
331/// generator emits this for every member whose element type is a person (a struct with a
332/// required flexible id); a plain-`int64` person type in Go keeps the strict list.
333///
334/// Only the element is lenient. A `null` *list* is `None` as before, an element that is not an
335/// object still fails, and so does an element whose id is an explicit `null`.
336pub(crate) mod person_list {
337    use serde::{Deserialize, Deserializer};
338
339    /// A required list of people.
340    #[allow(dead_code)]
341    pub(crate) fn deserialize<'de, D, T>(deserializer: D) -> Result<Vec<T>, D::Error>
342    where
343        D: Deserializer<'de>,
344        T: Deserialize<'de> + Default,
345    {
346        Ok(zero_nulls(Vec::<Option<T>>::deserialize(deserializer)?))
347    }
348
349    /// An optional (or nullable) list of people: `null` is `None`.
350    pub(crate) fn deserialize_optional<'de, D, T>(
351        deserializer: D,
352    ) -> Result<Option<Vec<T>>, D::Error>
353    where
354        D: Deserializer<'de>,
355        T: Deserialize<'de> + Default,
356    {
357        Ok(Option::<Vec<Option<T>>>::deserialize(deserializer)?.map(zero_nulls))
358    }
359
360    fn zero_nulls<T: Default>(elements: Vec<Option<T>>) -> Vec<T> {
361        elements
362            .into_iter()
363            .map(Option::unwrap_or_default)
364            .collect()
365    }
366}
367
368/// A string that must not end up in logs — a person's name or email address. It prints as
369/// `[REDACTED]`; call [`SensitiveString::expose`] to read it.
370#[derive(Clone, PartialEq, Eq, Hash, Default, Serialize, Deserialize)]
371#[serde(transparent)]
372pub struct SensitiveString(String);
373
374impl SensitiveString {
375    /// Wraps a value.
376    pub fn new(value: impl Into<String>) -> SensitiveString {
377        SensitiveString(value.into())
378    }
379
380    /// The value itself.
381    pub fn expose(&self) -> &str {
382        &self.0
383    }
384
385    /// The value itself, owned.
386    pub fn into_inner(self) -> String {
387        self.0
388    }
389
390    /// Whether there is anything to redact.
391    pub fn is_empty(&self) -> bool {
392        self.0.is_empty()
393    }
394}
395
396impl From<String> for SensitiveString {
397    fn from(value: String) -> SensitiveString {
398        SensitiveString(value)
399    }
400}
401
402impl From<&str> for SensitiveString {
403    fn from(value: &str) -> SensitiveString {
404        SensitiveString(value.to_string())
405    }
406}
407
408impl fmt::Debug for SensitiveString {
409    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
410        if self.0.is_empty() {
411            f.write_str("\"\"")
412        } else {
413            f.write_str("[REDACTED]")
414        }
415    }
416}
417
418impl fmt::Display for SensitiveString {
419    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
420        if self.0.is_empty() {
421            Ok(())
422        } else {
423            f.write_str("[REDACTED]")
424        }
425    }
426}
427
428/// A download URL that needs the SDK's credentials to answer (`x-basecamp-auth-routable-url`):
429/// it is fetched through [`AccountClient::download_url`](crate::AccountClient::download_url),
430/// the two-hop flow of SPEC §14, never with a bare GET.
431#[derive(Debug, Clone, PartialEq, Eq, Hash, Default, Serialize, Deserialize)]
432#[serde(transparent)]
433pub struct AuthRoutableUrl(pub String);
434
435impl AuthRoutableUrl {
436    /// The URL as the API wrote it.
437    pub fn as_str(&self) -> &str {
438        &self.0
439    }
440}
441
442impl fmt::Display for AuthRoutableUrl {
443    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
444        f.write_str(&self.0)
445    }
446}
447
448impl From<&str> for AuthRoutableUrl {
449    fn from(value: &str) -> AuthRoutableUrl {
450        AuthRoutableUrl(value.to_string())
451    }
452}
453
454#[cfg(test)]
455mod tests {
456    use super::*;
457
458    /// A date is `YYYY-MM-DD`, read as chrono read it: jiff's wider `civil::Date` parser
459    /// would take the compact form, and a datetime whose time it then drops.
460    #[test]
461    fn a_date_is_year_month_day_and_nothing_wider() {
462        assert_eq!(Date::new(2026, 3, 4), Date::parse("2026-03-04").ok());
463        assert_eq!("2026-03-04", Date::parse("2026-3-4").unwrap().to_string());
464        for source in [
465            "",
466            "20260304",
467            "2026-03-04T00:00:00",
468            "2026-03-04T00:00:00Z",
469            "2026-02-30",
470            "2026-03-04 ",
471        ] {
472            assert!(Date::parse(source).is_err(), "{source:?}");
473            assert!(
474                serde_json::from_value::<Date>(serde_json::json!(source)).is_err(),
475                "{source:?}"
476            );
477        }
478        assert_eq!(None, Date::new(2026, 2, 30));
479        assert_eq!(None, Date::new(2026, 3, 300));
480        assert_eq!("1970-01-01", Date::default().to_string());
481    }
482
483    /// Every date prints as something `Date::parse` and serde read back, the calendar's ends
484    /// and the years before 0 included.
485    #[test]
486    fn every_date_reads_back_what_it_prints() {
487        for (year, month, day) in [
488            (-9999, 1, 1),
489            (-1, 1, 1),
490            (0, 1, 1),
491            (99, 12, 31),
492            (2026, 3, 4),
493            (9999, 12, 31),
494        ] {
495            let date = Date::new(year, month, day).unwrap();
496            assert_eq!(date, Date::parse(&date.to_string()).unwrap(), "{date}");
497            let json = serde_json::to_string(&date).unwrap();
498            assert_eq!(date, serde_json::from_str::<Date>(&json).unwrap(), "{json}");
499        }
500    }
501
502    /// Instants read with any offset and write back in UTC, with the fraction only when
503    /// there is one, as they did when the type was chrono's.
504    #[test]
505    fn an_instant_reads_any_offset_and_writes_utc() {
506        let read = |source: &str| serde_json::from_value::<DateTime>(serde_json::json!(source));
507        let moment = read("2024-01-15T10:30:00.123-06:00").unwrap();
508        assert_eq!(
509            "\"2024-01-15T16:30:00.123Z\"",
510            serde_json::to_string(&moment).unwrap()
511        );
512        assert_eq!(
513            "\"2024-01-15T10:30:00Z\"",
514            serde_json::to_string(&read("2024-01-15T10:30:00.000Z").unwrap()).unwrap()
515        );
516        assert!(read("2024-01-15T10:30:00").is_err(), "no offset");
517        assert!(read("2024-01-15").is_err(), "a date is not an instant");
518        assert_eq!(
519            FlexibleTime::from("2024-01-15T10:30:00.123-06:00").datetime(),
520            Some(moment)
521        );
522        assert_eq!(FlexibleTime::from("2016-06-01").datetime(), None);
523        assert_eq!(
524            FlexibleTime::from("2016-06-01").date(),
525            Date::new(2016, 6, 1)
526        );
527    }
528
529    #[derive(Deserialize)]
530    struct Dimensions {
531        #[serde(default, deserialize_with = "flex_int::deserialize")]
532        width: Option<i32>,
533    }
534
535    #[derive(Deserialize)]
536    struct Identified {
537        #[serde(deserialize_with = "flexible_i64::deserialize")]
538        id: i64,
539    }
540
541    /// The shape the generator emits for an *optional* flexible id, attribute for
542    /// attribute. The model has no such field today, so this frame is the only thing
543    /// holding `deserialize_optional` to the same rule as its required sibling.
544    #[derive(Deserialize)]
545    struct OptionallyIdentified {
546        #[serde(default, deserialize_with = "flexible_i64::deserialize_optional")]
547        id: Option<i64>,
548    }
549
550    #[test]
551    fn dates_round_trip_through_json() {
552        let date: Date = serde_json::from_str("\"2026-03-04\"").unwrap();
553        assert_eq!(date, Date::new(2026, 3, 4).unwrap());
554        assert_eq!(serde_json::to_string(&date).unwrap(), "\"2026-03-04\"");
555    }
556
557    #[test]
558    fn date_changes_spell_a_clear_as_empty_and_round_trip_through_json() {
559        let set = DateChange::On(Date::new(2026, 3, 4).unwrap());
560        assert_eq!(serde_json::to_string(&set).unwrap(), "\"2026-03-04\"");
561        assert_eq!(serde_json::to_string(&DateChange::Clear).unwrap(), "\"\"");
562        assert_eq!(
563            serde_json::from_str::<DateChange>("\"2026-03-04\"").unwrap(),
564            set
565        );
566        assert_eq!(
567            serde_json::from_str::<DateChange>("\"\"").unwrap(),
568            DateChange::Clear
569        );
570        assert!(serde_json::from_str::<DateChange>("null").is_err());
571        assert!(serde_json::from_str::<DateChange>("\"tomorrow\"").is_err());
572    }
573
574    #[test]
575    fn dimensions_read_null_integers_and_integral_floats() {
576        assert_eq!(
577            serde_json::from_str::<Dimensions>(r#"{"width": null}"#)
578                .unwrap()
579                .width,
580            None
581        );
582        assert_eq!(
583            serde_json::from_str::<Dimensions>("{}").unwrap().width,
584            None
585        );
586        assert_eq!(
587            serde_json::from_str::<Dimensions>(r#"{"width": 1024}"#)
588                .unwrap()
589                .width,
590            Some(1024)
591        );
592        assert_eq!(
593            serde_json::from_str::<Dimensions>(r#"{"width": 1024.0}"#)
594                .unwrap()
595                .width,
596            Some(1024)
597        );
598        assert!(serde_json::from_str::<Dimensions>(r#"{"width": 2.5}"#).is_err());
599        assert_eq!(
600            serde_json::from_str::<Dimensions>(r#"{"width": 2147483647.0}"#)
601                .unwrap()
602                .width,
603            Some(i32::MAX)
604        );
605        assert!(serde_json::from_str::<Dimensions>(r#"{"width": 2147483648.0}"#).is_err());
606    }
607
608    /// Sentry BC-MCP-K/M: the API served `752.0000000000001` and `496.00000000000006`.
609    /// Floating-point noise reads as the integer; a real fraction or overflow is refused.
610    #[test]
611    fn dimensions_round_float_noise_and_refuse_real_fractions() {
612        for (input, expected) in [
613            ("752.0000000000001", 752),
614            ("496.00000000000006", 496),
615            ("751.9999999999999", 752),
616            ("-752.0000000000001", -752),
617            ("752.0000009", 752),
618            ("2147483647.0000002", i32::MAX),
619            ("-2147483648.0000002", i32::MIN),
620        ] {
621            let json = format!(r#"{{"width": {input}}}"#);
622            assert_eq!(
623                serde_json::from_str::<Dimensions>(&json).unwrap().width,
624                Some(expected),
625                "{input}"
626            );
627        }
628        for input in [
629            "752.5",
630            "752.001",
631            "752.0000011",
632            "0.5",
633            "2147483647.5",
634            "2147483647.9999998",
635            "9007199254740993",
636        ] {
637            let json = format!(r#"{{"width": {input}}}"#);
638            assert!(
639                serde_json::from_str::<Dimensions>(&json).is_err(),
640                "{input}"
641            );
642        }
643    }
644
645    #[test]
646    fn ids_keep_sixty_four_bits_and_read_strings() {
647        assert_eq!(
648            serde_json::from_str::<Identified>(r#"{"id": 9007199254740993}"#)
649                .unwrap()
650                .id,
651            9_007_199_254_740_993
652        );
653        assert_eq!(
654            serde_json::from_str::<Identified>(r#"{"id": "42"}"#)
655                .unwrap()
656                .id,
657            42
658        );
659        assert_eq!(
660            serde_json::from_str::<Identified>(r#"{"id": "basecamp"}"#)
661                .unwrap()
662                .id,
663            0
664        );
665        assert!(serde_json::from_str::<Identified>(r#"{"id": "99999999999999999999"}"#).is_err());
666        assert_eq!(
667            serde_json::from_str::<Identified>(r#"{"id": "basecamp"}"#)
668                .unwrap()
669                .id,
670            0
671        );
672        assert!(serde_json::from_str::<Identified>(r#"{"id": "99999999999999999999"}"#).is_err());
673    }
674
675    // -----------------------------------------------------------------------------
676    // Parity with Go's `types.FlexibleInt64` (`go/pkg/types/flexible_int64.go`).
677    //
678    // Every expectation below was recorded from the Go reference itself — not from this
679    // implementation, and not from `strconv.ParseInt`'s documentation. A linked probe
680    // unmarshalled `{"id": <case>, "name": "x"}` into `go/pkg/generated.Person`, whose
681    // `Id` is `types.FlexibleInt64`, over the whole corpus, and each row pins that run's
682    // verdict: `Some(n)` accepted with value n, `None` rejected.
683    //
684    // The probe was proved live before it was trusted, on both of the paths it measures:
685    // a mutation of the string path in `flexible_int64.go` moved 33 rows, a mutation of
686    // the number path moved 6, and reverting each restored every one byte for byte.
687    // `generated::types::Person::id` in this crate is the same field through the
688    // deserializer under test.
689    //
690    // The rule those rows turned out to encode, for a reader who wants it in a sentence:
691    // the string path is `strconv.ParseInt(s, 10, 64)`, whose syntax errors read as `0`
692    // and whose range errors are raised, deciding between the two by whichever
693    // disqualifying byte the left-to-right scan reaches first; the number path is
694    // `json.Number.Int64()`, the same parse over the literal's own text. The rows are the
695    // evidence; this sentence is only a summary of them.
696    // -----------------------------------------------------------------------------
697
698    /// Runs one slice of the corpus through the deserializer under test. `None` means the
699    /// decode must fail; `Some(n)` that it must succeed with exactly `n`. Reports every
700    /// divergent row at once, so a regression names all of its casualties.
701    ///
702    /// Every row is read through *both* frames the generator can emit — the required id
703    /// and the optional one. Go's own optional frame, a `*types.FlexibleInt64` field,
704    /// returns the required frame's verdict on every row but one: a literal `null`, which
705    /// it takes as absent. So the two frames share one set of expectations, with `null` as
706    /// the single exception, and the optional arm cannot drift away from the rule while
707    /// the required arm still follows it.
708    fn check_against_go(rows: &[(&str, Option<i64>)]) {
709        let divergences: Vec<String> = rows
710            .iter()
711            .flat_map(|(raw, expected)| {
712                let body = format!("{{\"id\": {raw}}}");
713                let required = serde_json::from_str::<Identified>(&body)
714                    .ok()
715                    .map(|identified| identified.id);
716                let optional = serde_json::from_str::<OptionallyIdentified>(&body)
717                    .ok()
718                    .map(|identified| identified.id);
719                // `null` is the one row where the optional frame legitimately parts
720                // company with the required one: absent, not a zero and not an error.
721                let optional_expected = if *raw == "null" {
722                    Some(None)
723                } else {
724                    expected.map(Some)
725                };
726                [
727                    (required != *expected).then(|| {
728                        format!("  id: {raw} — Go reads {expected:?}, this crate {required:?}")
729                    }),
730                    (optional != optional_expected).then(|| {
731                        format!(
732                            "  id: {raw} (optional field) — Go reads {optional_expected:?}, \
733                             this crate {optional:?}"
734                        )
735                    }),
736                ]
737            })
738            .flatten()
739            .collect();
740        assert!(
741            divergences.is_empty(),
742            "{} of {} rows diverge from Go:\n{}",
743            divergences.len(),
744            rows.len(),
745            divergences.join("\n")
746        );
747    }
748
749    #[test]
750    fn go_parity_bare_json_numbers() {
751        // The JSON-number path: Go reads the literal with `json.Number.Int64()`,
752        // which is `ParseInt` over the literal text, so `7.0` and `1e2` are errors, not 7 and 100.
753        check_against_go(&[
754            ("7", Some(7)),                           // number 7
755            ("-7", Some(-7)),                         // number -7
756            ("0", Some(0)),                           // number 0
757            ("7.0", None),                            // number 7.0
758            ("-7.0", None),                           // number -7.0
759            ("7.5", None),                            // number 7.5
760            ("0.7", None),                            // number 0.7
761            ("1e2", None),                            // number 1e2
762            ("1E2", None),                            // number 1E2
763            ("1e+2", None),                           // number 1e+2
764            ("1e-2", None),                           // number 1e-2
765            ("7e0", None),                            // number 7e0
766            ("1e400", None),                          // number 1e400
767            ("-1e400", None),                         // number -1e400
768            ("9223372036854775807", Some(i64::MAX)),  // number 9223372036854775807
769            ("9223372036854775808", None),            // number 9223372036854775808
770            ("-9223372036854775808", Some(i64::MIN)), // number -9223372036854775808
771            ("-9223372036854775809", None),           // number -9223372036854775809
772            ("18446744073709551615", None),           // number 18446744073709551615
773            ("18446744073709551616", None),           // number 18446744073709551616
774            ("12345678901234567890", None),           // number 12345678901234567890
775            ("-12345678901234567890", None),          // number -12345678901234567890
776            ("9223372036854775807.0", None),          // number 9223372036854775807.0
777            ("0e0", None),                            // number 0e0
778            ("-0.0", None),                           // number -0.0
779            ("-0e0", None),                           // number -0e0
780            ("-0.000", None),                         // number -0.000
781            ("0.0", None),                            // number 0.0
782            ("-0.0e0", None),                         // number -0.0e0
783        ]);
784    }
785
786    #[test]
787    fn go_parity_non_string_json_values() {
788        // Neither side coerces a non-scalar or a boolean.
789        check_against_go(&[
790            ("true", None),      // literal true
791            ("false", None),     // literal false
792            ("null", None),      // literal null
793            ("[]", None),        // empty array
794            ("[7]", None),       // array [7]
795            ("[\"7\"]", None),   // array ["7"]
796            ("{}", None),        // empty object
797            ("{\"a\":1}", None), // object {"a":1}
798        ]);
799    }
800
801    #[test]
802    fn go_parity_numeric_strings_and_leading_zeros() {
803        check_against_go(&[
804            ("\"7\"", Some(7)),                           // string '7'
805            ("\"-7\"", Some(-7)),                         // string '-7'
806            ("\"+7\"", Some(7)),                          // string '+7'
807            ("\"0\"", Some(0)),                           // string '0'
808            ("\"-0\"", Some(0)),                          // string '-0'
809            ("\"+0\"", Some(0)),                          // string '+0'
810            ("\"00\"", Some(0)),                          // string '00'
811            ("\"007\"", Some(7)),                         // string '007'
812            ("\"-007\"", Some(-7)),                       // string '-007'
813            ("\"+007\"", Some(7)),                        // string '+007'
814            ("\"000000000000000000000000007\"", Some(7)), // string '000000000000000000000000007'
815            ("\"1234567890\"", Some(1_234_567_890)),      // string '1234567890'
816        ]);
817    }
818
819    #[test]
820    fn go_parity_ascii_whitespace_is_never_trimmed() {
821        // `ParseInt` trims nothing, so any surrounding byte is a syntax error and reads 0.
822        check_against_go(&[
823            ("\" 7\"", Some(0)),              // leading space
824            ("\"7 \"", Some(0)),              // trailing space
825            ("\" 7 \"", Some(0)),             // surrounding space
826            ("\"\\t7\"", Some(0)),            // leading tab
827            ("\"7\\t\"", Some(0)),            // trailing tab
828            ("\"\\t7\\t\"", Some(0)),         // surrounding tab
829            ("\"\\n7\"", Some(0)),            // leading LF
830            ("\"7\\n\"", Some(0)),            // trailing LF
831            ("\"\\n7\\n\"", Some(0)),         // surrounding LF
832            ("\"\\r7\"", Some(0)),            // leading CR
833            ("\"7\\r\"", Some(0)),            // trailing CR
834            ("\"\\r7\\r\"", Some(0)),         // surrounding CR
835            ("\"\\u000b7\"", Some(0)),        // leading VT
836            ("\"7\\u000b\"", Some(0)),        // trailing VT
837            ("\"\\u000b7\\u000b\"", Some(0)), // surrounding VT
838            ("\"\\f7\"", Some(0)),            // leading FF
839            ("\"7\\f\"", Some(0)),            // trailing FF
840            ("\"\\f7\\f\"", Some(0)),         // surrounding FF
841            ("\"7 7\"", Some(0)),             // interior space
842            ("\" -7\"", Some(0)),             // space before sign
843            ("\"- 7\"", Some(0)),             // space after sign
844            ("\"+ 7\"", Some(0)),             // space after plus
845            ("\" \"", Some(0)),               // whitespace only space
846            ("\"\\t\"", Some(0)),             // whitespace only tab
847            ("\"\\n\"", Some(0)),             // whitespace only LF
848        ]);
849    }
850
851    #[test]
852    fn go_parity_unicode_whitespace_is_never_trimmed() {
853        // Nor does it know Unicode whitespace — `str::trim` would have eaten these.
854        check_against_go(&[
855            ("\"\\u00a07\"", Some(0)), // leading NBSP
856            ("\"7\\u00a0\"", Some(0)), // trailing NBSP
857            ("\"\\u20077\"", Some(0)), // leading FIGURE SPACE
858            ("\"7\\u2007\"", Some(0)), // trailing FIGURE SPACE
859            ("\"\\u30007\"", Some(0)), // leading IDEOGRAPHIC SPACE
860            ("\"7\\u3000\"", Some(0)), // trailing IDEOGRAPHIC SPACE
861            ("\"\\ufeff7\"", Some(0)), // leading ZWNBSP/BOM
862            ("\"7\\ufeff\"", Some(0)), // trailing ZWNBSP/BOM
863            ("\"\\u20287\"", Some(0)), // leading LINE SEPARATOR
864            ("\"7\\u2028\"", Some(0)), // trailing LINE SEPARATOR
865            ("\"\\u00857\"", Some(0)), // leading NEL
866            ("\"7\\u0085\"", Some(0)), // trailing NEL
867            ("\"\\u20097\"", Some(0)), // leading THIN SPACE
868            ("\"7\\u2009\"", Some(0)), // trailing THIN SPACE
869            ("\"\\u200b7\"", Some(0)), // leading ZERO WIDTH SPACE
870            ("\"7\\u200b\"", Some(0)), // trailing ZERO WIDTH SPACE
871        ]);
872    }
873
874    #[test]
875    fn go_parity_signs() {
876        // `ParseInt` takes exactly one leading `+` or `-`.
877        check_against_go(&[
878            ("\"+\"", Some(0)),        // string '+'
879            ("\"-\"", Some(0)),        // string '-'
880            ("\"++7\"", Some(0)),      // string '++7'
881            ("\"--7\"", Some(0)),      // string '--7'
882            ("\"+-7\"", Some(0)),      // string '+-7'
883            ("\"-+7\"", Some(0)),      // string '-+7'
884            ("\"7+\"", Some(0)),       // string '7+'
885            ("\"7-\"", Some(0)),       // string '7-'
886            ("\"-7-\"", Some(0)),      // string '-7-'
887            ("\"+7+\"", Some(0)),      // string '+7+'
888            ("\"-+\"", Some(0)),       // string '-+'
889            ("\"++\"", Some(0)),       // string '++'
890            ("\"7-7\"", Some(0)),      // string '7-7'
891            ("\"\\u00b17\"", Some(0)), // string '±7'
892        ]);
893    }
894
895    #[test]
896    fn go_parity_empty_string() {
897        check_against_go(&[
898            ("\"\"", Some(0)), // empty string
899        ]);
900    }
901
902    #[test]
903    fn go_parity_underscores_are_not_digit_separators() {
904        // `_` is a digit separator only for base 0; at base 10 it is a syntax error.
905        check_against_go(&[
906            ("\"1_0\"", Some(0)),   // string '1_0'
907            ("\"_7\"", Some(0)),    // string '_7'
908            ("\"7_\"", Some(0)),    // string '7_'
909            ("\"1_000\"", Some(0)), // string '1_000'
910            ("\"+1_0\"", Some(0)),  // string '+1_0'
911            ("\"-1_0\"", Some(0)),  // string '-1_0'
912            ("\"__7\"", Some(0)),   // string '__7'
913        ]);
914    }
915
916    #[test]
917    fn go_parity_sixty_four_bit_bounds() {
918        // A well-formed number past the bound is the one string error Go raises;
919        // a malformed one of any size is still just 0.
920        check_against_go(&[
921            ("\"9223372036854775807\"", Some(i64::MAX)), // string '9223372036854775807'
922            ("\"9223372036854775808\"", None),           // string '9223372036854775808'
923            ("\"9223372036854775806\"", Some(9_223_372_036_854_775_806)), // string '9223372036854775806'
924            ("\"+9223372036854775807\"", Some(i64::MAX)), // string '+9223372036854775807'
925            ("\"+9223372036854775808\"", None),           // string '+9223372036854775808'
926            ("\"-9223372036854775808\"", Some(i64::MIN)), // string '-9223372036854775808'
927            ("\"-9223372036854775809\"", None),           // string '-9223372036854775809'
928            ("\"-9223372036854775807\"", Some(-9_223_372_036_854_775_807)), // string '-9223372036854775807'
929            ("\"0009223372036854775807\"", Some(i64::MAX)), // string '0009223372036854775807'
930            ("\"0009223372036854775808\"", None),           // string '0009223372036854775808'
931            ("\"18446744073709551615\"", None),             // string '18446744073709551615'
932            ("\"18446744073709551616\"", None),             // string '18446744073709551616'
933            ("\"99999999999999999999999999999999\"", None), // string '99999999999999999999999999999999'
934            ("\"-99999999999999999999999999999999\"", None), // string '-99999999999999999999999999999999'
935            ("\"9223372036854775808 \"", Some(0)),           // string '9223372036854775808 '
936            ("\" 9223372036854775808\"", Some(0)),           // string ' 9223372036854775808'
937            ("\"-0000000000000000000009223372036854775809\"", None), // string '-0000000000000000000009223372036854775809'
938        ]);
939    }
940
941    #[test]
942    fn go_parity_base_prefixes_are_not_recognized() {
943        // Base 10 is fixed, so `0x`/`0o`/`0b` are ordinary syntax errors.
944        check_against_go(&[
945            ("\"0x10\"", Some(0)),  // string '0x10'
946            ("\"0X10\"", Some(0)),  // string '0X10'
947            ("\"0o17\"", Some(0)),  // string '0o17'
948            ("\"0O17\"", Some(0)),  // string '0O17'
949            ("\"0b101\"", Some(0)), // string '0b101'
950            ("\"0B101\"", Some(0)), // string '0B101'
951            ("\"0xg\"", Some(0)),   // string '0xg'
952            ("\"#7\"", Some(0)),    // string '#7'
953            ("\"07\"", Some(7)),    // string '07'
954            // TEN, not eight. Base is never detected from the literal: Ruby's `Integer()`
955            // read this one as 8, which is not a refusal against an acceptance but two
956            // different PEOPLE from one wire value (card 35).
957            ("\"010\"", Some(10)),  // string '010'
958            ("\"0x7\"", Some(0)),   // string '0x7'
959            ("\"-0x10\"", Some(0)), // string '-0x10'
960            ("\"8#7\"", Some(0)),   // string '8#7'
961            ("\"1e2\"", Some(0)),   // string '1e2'
962            ("\"7e2\"", Some(0)),   // string '7e2'
963            ("\"0d7\"", Some(0)),   // string '0d7'
964        ]);
965    }
966
967    #[test]
968    fn go_parity_non_ascii_digits_are_not_digits() {
969        // Go's digit test is ASCII-only, and so is `i64::from_str` — `char::is_numeric` is not.
970        check_against_go(&[
971            ("\"\\uff17\"", Some(0)),        // string '7'
972            ("\"\\uff17\\uff17\"", Some(0)), // string '77'
973            ("\"\\u0667\"", Some(0)),        // string '٧'
974            ("\"\\u096d\"", Some(0)),        // string '७'
975            ("\"7\\u0667\"", Some(0)),       // string '7٧'
976            ("\"\\u06677\"", Some(0)),       // string '٧7'
977            ("\"\\u2467\"", Some(0)),        // string '⑧'
978            ("\"\\u2166\"", Some(0)),        // string 'Ⅶ'
979            ("\"\\u00bd\"", Some(0)),        // string '½'
980            ("\"\\u2077\"", Some(0)),        // string '⁷'
981            ("\"\\u00b2\"", Some(0)),        // string '²'
982            ("\"\\u0660\"", Some(0)),        // string '٠'
983        ]);
984    }
985
986    #[test]
987    fn go_parity_non_numeric_sentinels() {
988        // "basecamp" is the one the API actually sends.
989        check_against_go(&[
990            ("\"basecamp\"", Some(0)),  // string 'basecamp'
991            ("\"abc\"", Some(0)),       // string 'abc'
992            ("\"7abc\"", Some(0)),      // string '7abc'
993            ("\"abc7\"", Some(0)),      // string 'abc7'
994            ("\"7.0\"", Some(0)),       // string '7.0'
995            ("\"-7.0\"", Some(0)),      // string '-7.0'
996            ("\"7,0\"", Some(0)),       // string '7,0'
997            ("\"7.\"", Some(0)),        // string '7.'
998            ("\".7\"", Some(0)),        // string '.7'
999            ("\"NaN\"", Some(0)),       // string 'NaN'
1000            ("\"nan\"", Some(0)),       // string 'nan'
1001            ("\"Inf\"", Some(0)),       // string 'Inf'
1002            ("\"+Inf\"", Some(0)),      // string '+Inf'
1003            ("\"-Inf\"", Some(0)),      // string '-Inf'
1004            ("\"infinity\"", Some(0)),  // string 'infinity'
1005            ("\"null\"", Some(0)),      // string 'null'
1006            ("\"true\"", Some(0)),      // string 'true'
1007            ("\"false\"", Some(0)),     // string 'false'
1008            ("\"[7]\"", Some(0)),       // string '[7]'
1009            ("\"{}\"", Some(0)),        // string '{}'
1010            ("\"7\\u00007\"", Some(0)), // string '7\x007'
1011            ("\"\\u00007\"", Some(0)),  // string '\x007'
1012            ("\"7\\u0000\"", Some(0)),  // string '7\x00'
1013            ("\"7 7 7\"", Some(0)),     // string '7 7 7'
1014            ("\"'7'\"", Some(0)),       // string "'7'"
1015            ("\"\\\"7\\\"\"", Some(0)), // string '"7"'
1016            ("\"seven\"", Some(0)),     // string 'seven'
1017        ]);
1018    }
1019
1020    #[test]
1021    fn go_parity_which_refusal_comes_first() {
1022        // `ParseUint` checks the magnitude inside the scan, so an overflowing digit
1023        // ends the parse before a later non-digit is seen: the first disqualifying byte
1024        // wins. That makes the boundary u64::MAX, not i64::MAX, and it is why junk after
1025        // an oversized prefix is RAISED while the same junk after a merely large one
1026        // reads 0. Junk before the digits is a syntax error wherever it sits.
1027        check_against_go(&[
1028            ("\"18446744073709551615x\"", Some(0)), // string '18446744073709551615x'
1029            ("\"9223372036854775808x\"", Some(0)),  // string '9223372036854775808x'
1030            ("\"9223372036854775807x\"", Some(0)),  // string '9223372036854775807x'
1031            ("\"-9223372036854775809x\"", Some(0)), // string '-9223372036854775809x'
1032            ("\"000018446744073709551615x\"", Some(0)), // string '000018446744073709551615x'
1033            ("\"18446744073709551616x\"", None),    // string '18446744073709551616x'
1034            ("\"18446744073709551616 \"", None),    // string '18446744073709551616 '
1035            ("\"18446744073709551616.0\"", None),   // string '18446744073709551616.0'
1036            ("\"18446744073709551616\\n\"", None),  // string '18446744073709551616\n'
1037            ("\"18446744073709551616\\t\"", None),  // string '18446744073709551616\t'
1038            ("\"18446744073709551616\\u0000\"", None), // string '18446744073709551616\x00'
1039            ("\"18446744073709551616\\u00a0\"", None), // string '18446744073709551616\xa0'
1040            ("\"18446744073709551616_0\"", None),   // string '18446744073709551616_0'
1041            ("\"18446744073709551616abc\"", None),  // string '18446744073709551616abc'
1042            ("\"-18446744073709551616x\"", None),   // string '-18446744073709551616x'
1043            ("\"+18446744073709551616x\"", None),   // string '+18446744073709551616x'
1044            ("\"000018446744073709551616x\"", None), // string '000018446744073709551616x'
1045            ("\"184467440737095516161234x\"", None), // string '184467440737095516161234x'
1046            ("\"99999999999999999999_\"", None),    // string '99999999999999999999_'
1047            ("\"1844674407370955161612345678901234567890x\"", None), // string '1844674407370955161612345678901234567890x'
1048            ("\"x18446744073709551616\"", Some(0)), // string 'x18446744073709551616'
1049            ("\" 18446744073709551616\"", Some(0)), // string ' 18446744073709551616'
1050            ("\"+x18446744073709551616\"", Some(0)), // string '+x18446744073709551616'
1051            ("\"-18446744073709551616\"", None),    // string '-18446744073709551616'
1052            ("\"+18446744073709551616\"", None),    // string '+18446744073709551616'
1053            (
1054                "\"9999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999z\"",
1055                None,
1056            ), // 100 nines then a letter
1057            (
1058                "\"9999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999\"",
1059                None,
1060            ), // 100 nines
1061            (
1062                "\"0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000007\"",
1063                Some(7),
1064            ), // 300 leading zeros then 7
1065            (
1066                "\"0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000007z\"",
1067                Some(0),
1068            ), // 300 leading zeros then 7 then junk
1069        ]);
1070    }
1071
1072    #[test]
1073    fn go_parity_the_i64_min_boundary_in_several_spellings() {
1074        // The two subtlest lines in `parse_int` — the negative-magnitude comparison
1075        // and the fallback that turns 2^63 into i64::MIN — were each pinned by exactly one
1076        // row, so an edit to that row could have hidden a mutation. These are the same two
1077        // magnitudes spelled several ways.
1078        check_against_go(&[
1079            ("\"-09223372036854775808\"", Some(i64::MIN)), // string '-09223372036854775808'
1080            ("\"-009223372036854775808\"", Some(i64::MIN)), // string '-009223372036854775808'
1081            (
1082                "\"-00000000000000000000009223372036854775808\"",
1083                Some(i64::MIN),
1084            ), // string '-00000000000000000000009223372036854775808'
1085            ("\"+09223372036854775807\"", Some(i64::MAX)), // string '+09223372036854775807'
1086            ("\"+009223372036854775807\"", Some(i64::MAX)), // string '+009223372036854775807'
1087            (
1088                "\"-09223372036854775807\"",
1089                Some(-9_223_372_036_854_775_807),
1090            ), // string '-09223372036854775807'
1091            ("\"-009223372036854775809\"", None),          // string '-009223372036854775809'
1092            ("\"+09223372036854775808\"", None),           // string '+09223372036854775808'
1093            ("\"+009223372036854775808\"", None),          // string '+009223372036854775808'
1094            ("\"-0000000000000000000000000000000000000001\"", Some(-1)), // string '-0000000000000000000000000000000000000001'
1095            ("\"+0000000000000000000000000000000000000001\"", Some(1)), // string '+0000000000000000000000000000000000000001'
1096        ]);
1097    }
1098
1099    /// A bare JSON `-0` is the one corpus row this crate still refuses where Go accepts
1100    /// it. Go parses the literal's own text — `ParseInt("-0", 10, 64)` is 0 — while
1101    /// `serde_json` has already turned that literal into the float `-0.0` by the time the
1102    /// deserializer sees it, and the text is gone. Reading the float back as 0 would also
1103    /// accept `-0.0`, `-0e0`, `-0.000` and `-0.0e0`, which Go rejects (rows above), and a
1104    /// fallback keyed on the value rather than the sign would take `0.0` and `0e0` too:
1105    /// six new divergences in the accepting direction to close one in the refusing
1106    /// direction. So the divergence stays, pinned here so it cannot change unnoticed.
1107    #[test]
1108    fn a_bare_negative_zero_is_a_known_residual_divergence() {
1109        // Go accepts this and reads 0; this crate rejects it.
1110        assert!(serde_json::from_str::<Identified>(r#"{"id": -0}"#).is_err());
1111    }
1112
1113    /// The other residual, and it is not this function's to fix: a lone surrogate escape
1114    /// inside the id string. Go's `encoding/json` folds it to U+FFFD, so `ParseInt` sees a
1115    /// syntax error and the id reads 0; `serde_json` refuses the *document*, so the
1116    /// deserializer is never reached. The proof that the layer is the parser and not the
1117    /// rule is that a plain `String` field fails on the same input. It is the refusing
1118    /// direction, and closing it would mean changing JSON parsers.
1119    #[test]
1120    fn a_lone_surrogate_is_refused_by_the_json_parser_not_by_this_rule() {
1121        assert!(serde_json::from_str::<String>(r#""\ud800""#).is_err());
1122        assert!(serde_json::from_str::<Identified>(r#"{"id": "\ud800"}"#).is_err());
1123    }
1124
1125    /// An optional flexible id that is absent reads as absent, not as `0` — the same as
1126    /// Go's `*types.FlexibleInt64`, which stays nil for a missing key and for `null`.
1127    #[test]
1128    fn an_absent_optional_flexible_id_is_none() {
1129        assert_eq!(
1130            serde_json::from_str::<OptionallyIdentified>("{}")
1131                .ok()
1132                .map(|identified| identified.id),
1133            Some(None)
1134        );
1135        assert_eq!(
1136            serde_json::from_str::<OptionallyIdentified>(r#"{"id": null}"#)
1137                .ok()
1138                .map(|identified| identified.id),
1139            Some(None)
1140        );
1141    }
1142
1143    /// The corpus runs through `Identified`. The field that actually ships is
1144    /// `generated::types::Person::id`, annotated with the same `deserialize_with`; these
1145    /// rows hold the two frames together.
1146    #[test]
1147    fn the_shipped_person_id_reads_what_the_corpus_pins() {
1148        for (raw, expected) in [
1149            ("7", Some(7_i64)),
1150            ("\" 7\"", Some(0)),
1151            ("\"+7\"", Some(7)),
1152            ("\"basecamp\"", Some(0)),
1153            ("\"9223372036854775808\"", None),
1154            // The pair that only a left-to-right scan gets right, on the shipped field.
1155            ("\"18446744073709551615x\"", Some(0)),
1156            ("\"18446744073709551616x\"", None),
1157        ] {
1158            let read = serde_json::from_str::<crate::generated::types::Person>(&format!(
1159                "{{\"id\": {raw}, \"name\": \"x\"}}"
1160            ))
1161            .ok()
1162            .map(|person| person.id);
1163            assert_eq!(read, expected, "id: {raw}");
1164        }
1165    }
1166
1167    #[test]
1168    fn flexible_times_read_both_shapes() {
1169        assert_eq!(
1170            FlexibleTime::from("2016-06-01").date(),
1171            Date::new(2016, 6, 1)
1172        );
1173        assert!(FlexibleTime::from("2016-06-01").datetime().is_none());
1174        assert!(
1175            FlexibleTime::from("2016-06-01T10:00:00Z")
1176                .datetime()
1177                .is_some()
1178        );
1179    }
1180
1181    #[test]
1182    fn sensitive_strings_hide_their_value() {
1183        let secret = SensitiveString::new("jane@example.com");
1184        assert_eq!(format!("{secret:?}"), "[REDACTED]");
1185        assert_eq!(secret.to_string(), "[REDACTED]");
1186        assert_eq!(secret.expose(), "jane@example.com");
1187        assert_eq!(
1188            serde_json::to_string(&secret).unwrap(),
1189            "\"jane@example.com\""
1190        );
1191    }
1192
1193    /// The shape the generator emits for a *required* list of people. The model has none
1194    /// today (every person list is optional), so this frame is what holds
1195    /// `person_list::deserialize` to the rule its optional sibling is tested against.
1196    #[derive(Deserialize, Default, Debug, PartialEq)]
1197    struct Someone {
1198        #[serde(default, deserialize_with = "flexible_i64::deserialize")]
1199        id: i64,
1200    }
1201
1202    #[derive(Deserialize)]
1203    struct RequiredPeople {
1204        #[serde(deserialize_with = "person_list::deserialize")]
1205        people: Vec<Someone>,
1206    }
1207
1208    #[test]
1209    fn a_required_person_list_reads_a_null_element_as_the_zero_person() {
1210        let read = |body: &str| serde_json::from_str::<RequiredPeople>(body).map(|r| r.people);
1211        assert_eq!(
1212            read(r#"{"people": [null, {"id": "7"}, {}]}"#).unwrap(),
1213            vec![Someone { id: 0 }, Someone { id: 7 }, Someone { id: 0 }]
1214        );
1215        assert!(read(r#"{"people": null}"#).is_err());
1216        assert!(read("{}").is_err());
1217        assert!(read(r#"{"people": [5]}"#).is_err());
1218        assert!(read(r#"{"people": [{"id": null}]}"#).is_err());
1219    }
1220}