Skip to main content

cpa_plugin/gojson/
mod.rs

1//! Go `encoding/json` for the plugin RPC contract.
2//!
3//! Most `sdk/pluginapi` structs carry no json tags, so the wire names are the Go field
4//! names (`AuthID`, `StorageJSON`). Encoding follows `json.Marshal`: fields in
5//! declaration order, `omitempty`, HTML-escaped strings, `[]byte` as padded standard
6//! base64, maps with sorted keys, `time.Time` as RFC 3339 with nanoseconds. Decoding
7//! follows `json.Unmarshal`: a key matches its field exactly or, failing that,
8//! case-insensitively; unknown keys are ignored; the last duplicate wins; `null` leaves
9//! scalars alone and clears slices and maps; numbers into integer fields must be integer
10//! literals.
11//!
12//! Decoding walks a [`Node`] tree that keeps every object member and number literal,
13//! and follows Go's decode-into-existing rules: struct fields and map keys merge into
14//! what is already there (a map element itself is decoded fresh), a pointer decodes
15//! into its pointee, a slice reuses its elements.
16//!
17//! Structs are declared with [`go_struct!`](crate::go_struct). `[]byte` is
18//! [`bytes::Bytes`]; `map[string]any` and `any` are [`serde_json::Value`].
19//!
20//! ponytail: an empty slice, map or `[]byte` encodes as `null` (Go's nil). Fields Go
21//! builds non-nil while empty use [`NonNil`].
22
23use std::collections::BTreeMap;
24use std::fmt;
25
26use base64::Engine as _;
27use bytes::Bytes;
28use chrono::{DateTime, Datelike, FixedOffset, Timelike};
29use serde_json::Value;
30
31mod node;
32pub use node::{Node, parse, parse_first};
33
34#[derive(Debug, Clone, PartialEq, Eq)]
35pub struct DecodeError(pub String);
36
37impl fmt::Display for DecodeError {
38    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
39        f.write_str(&self.0)
40    }
41}
42
43impl std::error::Error for DecodeError {}
44
45/// A value with Go `encoding/json` semantics.
46pub trait GoJson: Sized + Default {
47    /// Go type name, for error messages.
48    const GO_TYPE: &'static str;
49    /// The Go type as decode errors spell it; containers name their element type
50    /// (`[]string`, `map[string]interface {}`).
51    fn go_type() -> String {
52        Self::GO_TYPE.to_owned()
53    }
54    /// Appends `json.Marshal` output.
55    fn encode(&self, out: &mut Vec<u8>);
56    /// `json.Unmarshal` into a zero value.
57    fn decode(v: &Node) -> Result<Self, DecodeError> {
58        let mut out = Self::default();
59        out.decode_into(v)?;
60        Ok(out)
61    }
62    /// `json.Unmarshal` into an existing value. `null` resets slices, maps, pointers and
63    /// `any`, and leaves everything else alone.
64    fn decode_into(&mut self, v: &Node) -> Result<(), DecodeError> {
65        if v.is_null() {
66            if Self::NULL_CLEARS {
67                *self = Self::default();
68            }
69            return Ok(());
70        }
71        *self = Self::decode_value(v)?;
72        Ok(())
73    }
74    /// Decodes a non-null value from scratch. Implement this or [`Self::decode_into`].
75    fn decode_value(v: &Node) -> Result<Self, DecodeError> {
76        let mut out = Self::default();
77        out.decode_into(v)?;
78        Ok(out)
79    }
80    /// Go `omitempty`: false, 0, "", nil or empty slices and maps, nil pointers. Structs
81    /// (including `time.Time`) are never empty.
82    fn is_empty(&self) -> bool;
83    /// Whether `null` resets the field (slices, maps, pointers, `any`); scalars and
84    /// structs keep their value.
85    const NULL_CLEARS: bool = false;
86}
87
88/// `json.Marshal`.
89pub fn to_vec<T: GoJson>(v: &T) -> Vec<u8> {
90    let mut out = Vec::new();
91    v.encode(&mut out);
92    out
93}
94
95/// `json.Unmarshal` of a complete document.
96pub fn from_slice<T: GoJson>(raw: &[u8]) -> Result<T, DecodeError> {
97    T::decode(&parse(raw)?)
98}
99
100/// `json.NewDecoder(bytes.NewReader(raw)).Decode`: the first value; see [`parse_first`].
101pub fn from_slice_first<T: GoJson>(raw: &[u8]) -> Result<T, DecodeError> {
102    T::decode(&parse_first(raw)?)
103}
104
105fn kind(v: &Node) -> &'static str {
106    match v {
107        Node::Null => "null",
108        Node::Bool(_) => "bool",
109        Node::Number(_) => "number",
110        Node::String(_) => "string",
111        Node::Array(_) => "array",
112        Node::Object(_) => "object",
113    }
114}
115
116/// A value of the wrong JSON kind for `go_type`. Go names a number without its
117/// literal here; [`number_error`] is the numeric-range case that includes it.
118pub fn type_error(v: &Node, go_type: &str) -> DecodeError {
119    let what = match v {
120        Node::Number(_) => "number",
121        other => kind(other),
122    };
123    DecodeError(format!("json: cannot unmarshal {what} into Go value of type {go_type}"))
124}
125
126/// A number that does not fit the numeric `go_type` (Go `"number " + literal`).
127pub fn number_error(literal: &str, go_type: &str) -> DecodeError {
128    DecodeError(format!(
129        "json: cannot unmarshal number {literal} into Go value of type {go_type}"
130    ))
131}
132
133/// Adds the struct field to a decode error, like Go's `UnmarshalTypeError`: the
134/// innermost struct's name and the field path from the outermost struct (array
135/// indexes and map keys are not part of it).
136pub fn in_field(err: DecodeError, strukt: &str, field: &str) -> DecodeError {
137    if let Some((head, ty)) = err.0.split_once(" into Go value of type ") {
138        return DecodeError(format!("{head} into Go struct field {strukt}.{field} of type {ty}"));
139    }
140    // A field of a nested struct: this field goes in front of its path.
141    if let Some((head, rest)) = err.0.split_once(" into Go struct field ")
142        && let Some((inner, path)) = rest.split_once('.')
143    {
144        return DecodeError(format!("{head} into Go struct field {inner}.{field}.{path}"));
145    }
146    err
147}
148
149/// Writes one JSON object field by field.
150pub struct ObjWriter<'a> {
151    out: &'a mut Vec<u8>,
152    first: bool,
153}
154
155impl<'a> ObjWriter<'a> {
156    pub fn begin(out: &'a mut Vec<u8>) -> Self {
157        out.push(b'{');
158        Self { out, first: true }
159    }
160
161    fn key(&mut self, name: &str) {
162        if !self.first {
163            self.out.push(b',');
164        }
165        self.first = false;
166        cpa_common::json::marshal_str(self.out, name.as_bytes(), true);
167        self.out.push(b':');
168    }
169
170    pub fn field<T: GoJson>(&mut self, name: &str, v: &T, omitempty: bool) {
171        if omitempty && v.is_empty() {
172            return;
173        }
174        self.key(name);
175        v.encode(self.out);
176    }
177
178    /// Fields of an embedded struct, flattened like Go embedding.
179    pub fn embed<T: GoStruct>(&mut self, v: &T) {
180        let mut inner = ObjWriter {
181            out: &mut *self.out,
182            first: self.first,
183        };
184        v.encode_fields(&mut inner);
185        self.first = inner.first;
186    }
187
188    pub fn end(self) {
189        self.out.push(b'}');
190    }
191}
192
193/// A Go struct: encodes its fields in order and decodes them by name.
194pub trait GoStruct: GoJson {
195    fn encode_fields(&self, w: &mut ObjWriter<'_>);
196    /// Decodes `v` into the field named `key` (exact match first, then
197    /// case-insensitive). `None` when no field matches.
198    fn decode_field(&mut self, key: &str, v: &Node) -> Option<Result<(), DecodeError>>;
199}
200
201/// Decodes an object into a fresh struct.
202pub fn decode_struct<T: GoStruct>(v: &Node) -> Result<T, DecodeError> {
203    let mut out = T::default();
204    decode_struct_into(&mut out, v)?;
205    Ok(out)
206}
207
208/// Decodes an object member by member into an existing struct; later duplicates decode
209/// over earlier ones.
210pub fn decode_struct_into<T: GoStruct>(out: &mut T, v: &Node) -> Result<(), DecodeError> {
211    match v {
212        Node::Null => Ok(()),
213        Node::Object(members) => {
214            // Go keeps decoding after a type mismatch and reports the first one.
215            let mut first_err = None;
216            for (key, value) in members {
217                if let Some(Err(e)) = out.decode_field(key, value) {
218                    first_err.get_or_insert(e);
219                }
220            }
221            first_err.map_or(Ok(()), Err)
222        }
223        other => Err(type_error(other, &T::go_type())),
224    }
225}
226
227/// Declares a Go struct with its wire names. Append `omitempty` after a name for Go's
228/// `,omitempty`.
229///
230/// ```ignore
231/// go_struct! {
232///     pub struct PayloadResponse("pluginapi.PayloadResponse") {
233///         "Body" => body: Bytes,
234///         "path" omitempty => path: String,
235///     }
236/// }
237/// ```
238#[macro_export]
239macro_rules! go_struct {
240    (
241        $(#[$meta:meta])*
242        pub struct $name:ident ($go_type:literal) {
243            $( $(#[$fmeta:meta])* $wire:literal $($omit:ident)? => $field:ident : $ty:ty ),* $(,)?
244        }
245    ) => {
246        $(#[$meta])*
247        #[derive(Debug, Clone, Default, PartialEq)]
248        pub struct $name {
249            $( $(#[$fmeta])* pub $field: $ty, )*
250        }
251
252        impl $crate::gojson::GoJson for $name {
253            const GO_TYPE: &'static str = $go_type;
254            fn encode(&self, out: &mut Vec<u8>) {
255                let mut w = $crate::gojson::ObjWriter::begin(out);
256                $crate::gojson::GoStruct::encode_fields(self, &mut w);
257                w.end();
258            }
259            fn decode_into(&mut self, v: &$crate::gojson::Node) -> Result<(), $crate::gojson::DecodeError> {
260                $crate::gojson::decode_struct_into(self, v)
261            }
262            fn is_empty(&self) -> bool {
263                false
264            }
265        }
266
267        impl $crate::gojson::GoStruct for $name {
268            #[allow(unused_variables)]
269            fn encode_fields(&self, w: &mut $crate::gojson::ObjWriter<'_>) {
270                $( w.field($wire, &self.$field, $crate::go_struct!(@omit $($omit)?)); )*
271            }
272            #[allow(unused_variables)]
273            fn decode_field(
274                &mut self,
275                key: &str,
276                v: &$crate::gojson::Node,
277            ) -> Option<Result<(), $crate::gojson::DecodeError>> {
278                $(
279                    if key == $wire {
280                        return Some($crate::gojson::decode_field_value(&mut self.$field, v, $go_type, $wire));
281                    }
282                )*
283                $(
284                    if key.eq_ignore_ascii_case($wire) {
285                        return Some($crate::gojson::decode_field_value(&mut self.$field, v, $go_type, $wire));
286                    }
287                )*
288                None
289            }
290        }
291    };
292    (@omit omitempty) => { true };
293    (@omit) => { false };
294}
295
296/// Decodes one field into its current value.
297pub fn decode_field_value<T: GoJson>(slot: &mut T, v: &Node, strukt: &str, field: &str) -> Result<(), DecodeError> {
298    slot.decode_into(v)
299        .map_err(|e| in_field(e, strukt.rsplit('.').next().unwrap_or(strukt), field))
300}
301
302// ----------------------------------------------------------------------------------------
303// Scalars
304
305impl GoJson for String {
306    const GO_TYPE: &'static str = "string";
307    fn encode(&self, out: &mut Vec<u8>) {
308        cpa_common::json::marshal_str(out, self.as_bytes(), true);
309    }
310    fn decode_value(v: &Node) -> Result<Self, DecodeError> {
311        match v {
312            Node::String(s) => Ok(s.clone()),
313            other => Err(type_error(other, Self::GO_TYPE)),
314        }
315    }
316    fn is_empty(&self) -> bool {
317        self.is_empty()
318    }
319}
320
321impl GoJson for bool {
322    const GO_TYPE: &'static str = "bool";
323    fn encode(&self, out: &mut Vec<u8>) {
324        out.extend_from_slice(if *self { b"true" } else { b"false" });
325    }
326    fn decode_value(v: &Node) -> Result<Self, DecodeError> {
327        match v {
328            Node::Bool(b) => Ok(*b),
329            other => Err(type_error(other, Self::GO_TYPE)),
330        }
331    }
332    fn is_empty(&self) -> bool {
333        !*self
334    }
335}
336
337macro_rules! go_int {
338    ($t:ty, $go:literal) => {
339        impl GoJson for $t {
340            const GO_TYPE: &'static str = $go;
341            fn encode(&self, out: &mut Vec<u8>) {
342                out.extend_from_slice(self.to_string().as_bytes());
343            }
344            /// Go parses the literal with `strconv.ParseInt`/`ParseUint`: `1.0`, `1e2` and
345            /// out-of-range values are errors.
346            fn decode_value(v: &Node) -> Result<Self, DecodeError> {
347                match v {
348                    Node::Number(n) => n.parse::<$t>().map_err(|_| number_error(n, Self::GO_TYPE)),
349                    other => Err(type_error(other, Self::GO_TYPE)),
350                }
351            }
352            fn is_empty(&self) -> bool {
353                *self == 0
354            }
355        }
356    };
357}
358
359// Go `int` has the platform's pointer width, like `isize`.
360go_int!(isize, "int");
361go_int!(i64, "int64");
362go_int!(i32, "int32");
363go_int!(u32, "uint32");
364go_int!(u64, "uint64");
365
366impl GoJson for f64 {
367    const GO_TYPE: &'static str = "float64";
368    fn encode(&self, out: &mut Vec<u8>) {
369        // json.Marshal rejects NaN and Inf; the host never produces them.
370        out.extend_from_slice(
371            cpa_common::json::json_float(*self)
372                .unwrap_or_else(|| "0".into())
373                .as_bytes(),
374        );
375    }
376    fn decode_value(v: &Node) -> Result<Self, DecodeError> {
377        match v {
378            Node::Number(n) => node::parse_f64(n),
379            other => Err(type_error(other, Self::GO_TYPE)),
380        }
381    }
382    fn is_empty(&self) -> bool {
383        *self == 0.0
384    }
385}
386
387/// `encoding/base64.StdEncoding.Decode` as `encoding/json` uses it: padding required,
388/// CR and LF skipped anywhere, non-zero trailing bits accepted. The error is Go's
389/// `CorruptInputError`, naming the same input offset (`decodeQuantum`).
390fn decode_base64(s: &str) -> Result<Bytes, DecodeError> {
391    let src = s.as_bytes();
392    let corrupt = |at: usize| DecodeError(format!("illegal base64 data at input byte {at}"));
393    let value = |c: u8| match c {
394        b'A'..=b'Z' => Some(c - b'A'),
395        b'a'..=b'z' => Some(c - b'a' + 26),
396        b'0'..=b'9' => Some(c - b'0' + 52),
397        b'+' => Some(62),
398        b'/' => Some(63),
399        _ => None,
400    };
401    let newline = |c: u8| c == b'\n' || c == b'\r';
402    let mut out = Vec::with_capacity(src.len() / 4 * 3);
403    let mut si = 0;
404    while si < src.len() {
405        let mut quantum = [0u8; 4];
406        let mut len = 4;
407        let mut trailing = None;
408        let mut j = 0;
409        while j < 4 {
410            if si == src.len() {
411                if j == 0 {
412                    return Ok(out.into());
413                }
414                return Err(corrupt(si - j));
415            }
416            let c = src[si];
417            si += 1;
418            if let Some(v) = value(c) {
419                quantum[j] = v;
420                j += 1;
421                continue;
422            }
423            if newline(c) {
424                continue;
425            }
426            if c != b'=' || j < 2 {
427                return Err(corrupt(si - 1));
428            }
429            if j == 2 {
430                // "==" is expected; the first `=` is consumed.
431                while si < src.len() && newline(src[si]) {
432                    si += 1;
433                }
434                if si == src.len() {
435                    return Err(corrupt(src.len()));
436                }
437                if src[si] != b'=' {
438                    return Err(corrupt(si - 1));
439                }
440                si += 1;
441            }
442            while si < src.len() && newline(src[si]) {
443                si += 1;
444            }
445            if si < src.len() {
446                trailing = Some(si);
447            }
448            len = j;
449            break;
450        }
451        let v = (u32::from(quantum[0]) << 18)
452            | (u32::from(quantum[1]) << 12)
453            | (u32::from(quantum[2]) << 6)
454            | u32::from(quantum[3]);
455        out.extend_from_slice(&[(v >> 16) as u8, (v >> 8) as u8, v as u8][..len - 1]);
456        if let Some(at) = trailing {
457            return Err(corrupt(at));
458        }
459    }
460    Ok(out.into())
461}
462
463/// `[]byte`: a base64 string, or a JSON array of byte values (a `null` element is 0).
464fn decode_byte_slice(v: &Node) -> Result<Bytes, DecodeError> {
465    match v {
466        Node::String(s) => decode_base64(s),
467        Node::Array(items) => items
468            .iter()
469            .map(|item| match item {
470                Node::Null => Ok(0),
471                Node::Number(n) => n.parse::<u8>().map_err(|_| number_error(n, "uint8")),
472                other => Err(type_error(other, "uint8")),
473            })
474            .collect::<Result<Vec<u8>, _>>()
475            .map(Bytes::from),
476        other => Err(type_error(other, "[]uint8")),
477    }
478}
479
480/// `[]byte`: standard padded base64; empty encodes as `null` (Go's nil).
481impl GoJson for Bytes {
482    const GO_TYPE: &'static str = "[]uint8";
483    const NULL_CLEARS: bool = true;
484    fn encode(&self, out: &mut Vec<u8>) {
485        if self.is_empty() {
486            out.extend_from_slice(b"null");
487            return;
488        }
489        out.push(b'"');
490        out.extend_from_slice(base64::engine::general_purpose::STANDARD.encode(self).as_bytes());
491        out.push(b'"');
492    }
493    fn decode_value(v: &Node) -> Result<Self, DecodeError> {
494        decode_byte_slice(v)
495    }
496    fn is_empty(&self) -> bool {
497        Bytes::is_empty(self)
498    }
499}
500
501/// A `[]byte` Go builds non-nil (for example from `io.ReadAll`): encodes `""` when
502/// empty instead of `null`.
503#[derive(Debug, Clone, Default, PartialEq, Eq)]
504pub struct NonNilBytes(pub Bytes);
505
506impl GoJson for NonNilBytes {
507    const GO_TYPE: &'static str = "[]uint8";
508    const NULL_CLEARS: bool = true;
509    fn encode(&self, out: &mut Vec<u8>) {
510        out.push(b'"');
511        out.extend_from_slice(base64::engine::general_purpose::STANDARD.encode(&self.0).as_bytes());
512        out.push(b'"');
513    }
514    fn decode_value(v: &Node) -> Result<Self, DecodeError> {
515        decode_byte_slice(v).map(NonNilBytes)
516    }
517    fn is_empty(&self) -> bool {
518        self.0.is_empty()
519    }
520}
521
522/// `any` / `map[string]any` values: Go decodes numbers to float64 and encodes maps with
523/// sorted keys.
524impl GoJson for Value {
525    const GO_TYPE: &'static str = "interface {}";
526    const NULL_CLEARS: bool = true;
527    fn encode(&self, out: &mut Vec<u8>) {
528        encode_any(self, out);
529    }
530    fn decode_value(v: &Node) -> Result<Self, DecodeError> {
531        v.to_value()
532    }
533    fn is_empty(&self) -> bool {
534        self.is_null()
535    }
536}
537
538/// Go's encoding of a value decoded into `any`.
539pub fn encode_any(v: &Value, out: &mut Vec<u8>) {
540    match v {
541        Value::Null => out.extend_from_slice(b"null"),
542        Value::Bool(b) => b.encode(out),
543        Value::Number(n) => match n.as_f64() {
544            Some(f) => f.encode(out),
545            None => out.extend_from_slice(n.to_string().as_bytes()),
546        },
547        Value::String(s) => cpa_common::json::marshal_str(out, s.as_bytes(), true),
548        Value::Array(items) => {
549            out.push(b'[');
550            for (i, item) in items.iter().enumerate() {
551                if i > 0 {
552                    out.push(b',');
553                }
554                encode_any(item, out);
555            }
556            out.push(b']');
557        }
558        Value::Object(map) => {
559            let sorted: BTreeMap<&String, &Value> = map.iter().collect();
560            out.push(b'{');
561            for (i, (key, item)) in sorted.into_iter().enumerate() {
562                if i > 0 {
563                    out.push(b',');
564                }
565                cpa_common::json::marshal_str(out, key.as_bytes(), true);
566                out.push(b':');
567                encode_any(item, out);
568            }
569            out.push(b'}');
570        }
571    }
572}
573
574// ----------------------------------------------------------------------------------------
575// Containers
576
577/// A slice: decoding reuses existing elements and truncates to the array's length.
578impl<T: GoJson> GoJson for Vec<T> {
579    const GO_TYPE: &'static str = "slice";
580    const NULL_CLEARS: bool = true;
581    fn go_type() -> String {
582        format!("[]{}", T::go_type())
583    }
584    fn encode(&self, out: &mut Vec<u8>) {
585        if self.is_empty() {
586            out.extend_from_slice(b"null");
587            return;
588        }
589        encode_items(self, out);
590    }
591    fn decode_into(&mut self, v: &Node) -> Result<(), DecodeError> {
592        match v {
593            Node::Null => {
594                self.clear();
595                Ok(())
596            }
597            Node::Array(items) => {
598                let mut first_err = None;
599                for (i, item) in items.iter().enumerate() {
600                    if i == self.len() {
601                        self.push(T::default());
602                    }
603                    if let Err(e) = self[i].decode_into(item) {
604                        first_err.get_or_insert(e);
605                    }
606                }
607                self.truncate(items.len());
608                first_err.map_or(Ok(()), Err)
609            }
610            other => Err(type_error(other, &Self::go_type())),
611        }
612    }
613    fn is_empty(&self) -> bool {
614        Vec::is_empty(self)
615    }
616}
617
618fn encode_items<T: GoJson>(items: &[T], out: &mut Vec<u8>) {
619    out.push(b'[');
620    for (i, item) in items.iter().enumerate() {
621        if i > 0 {
622            out.push(b',');
623        }
624        item.encode(out);
625    }
626    out.push(b']');
627}
628
629/// A pointer: `null` makes it nil; a value decodes into the existing pointee.
630impl<T: GoJson> GoJson for Option<T> {
631    const GO_TYPE: &'static str = T::GO_TYPE;
632    const NULL_CLEARS: bool = true;
633    fn go_type() -> String {
634        T::go_type()
635    }
636    fn encode(&self, out: &mut Vec<u8>) {
637        match self {
638            None => out.extend_from_slice(b"null"),
639            Some(v) => v.encode(out),
640        }
641    }
642    fn decode_into(&mut self, v: &Node) -> Result<(), DecodeError> {
643        if v.is_null() {
644            *self = None;
645            return Ok(());
646        }
647        self.get_or_insert_with(T::default).decode_into(v)
648    }
649    fn is_empty(&self) -> bool {
650        self.is_none()
651    }
652}
653
654/// A map: keys merge into the existing map; each element is decoded fresh.
655impl<T: GoJson> GoJson for BTreeMap<String, T> {
656    const GO_TYPE: &'static str = "map";
657    const NULL_CLEARS: bool = true;
658    fn go_type() -> String {
659        format!("map[string]{}", T::go_type())
660    }
661    fn encode(&self, out: &mut Vec<u8>) {
662        if self.is_empty() {
663            out.extend_from_slice(b"null");
664            return;
665        }
666        encode_map(self, out);
667    }
668    fn decode_into(&mut self, v: &Node) -> Result<(), DecodeError> {
669        match v {
670            Node::Null => {
671                self.clear();
672                Ok(())
673            }
674            Node::Object(members) => {
675                let mut first_err = None;
676                for (k, item) in members {
677                    match T::decode(item) {
678                        Ok(value) => {
679                            self.insert(k.clone(), value);
680                        }
681                        Err(e) => {
682                            first_err.get_or_insert(e);
683                        }
684                    }
685                }
686                first_err.map_or(Ok(()), Err)
687            }
688            other => Err(type_error(other, &Self::go_type())),
689        }
690    }
691    fn is_empty(&self) -> bool {
692        BTreeMap::is_empty(self)
693    }
694}
695
696fn encode_map<T: GoJson>(map: &BTreeMap<String, T>, out: &mut Vec<u8>) {
697    out.push(b'{');
698    for (i, (key, item)) in map.iter().enumerate() {
699        if i > 0 {
700            out.push(b',');
701        }
702        cpa_common::json::marshal_str(out, key.as_bytes(), true);
703        out.push(b':');
704        item.encode(out);
705    }
706    out.push(b'}');
707}
708
709/// A slice or map Go builds non-nil even when empty: encodes `[]` / `{}`.
710#[derive(Debug, Clone, Default, PartialEq)]
711pub struct NonNil<T>(pub T);
712
713impl<T: GoJson> GoJson for NonNil<Vec<T>> {
714    const GO_TYPE: &'static str = "slice";
715    const NULL_CLEARS: bool = true;
716    fn go_type() -> String {
717        Vec::<T>::go_type()
718    }
719    fn encode(&self, out: &mut Vec<u8>) {
720        encode_items(&self.0, out);
721    }
722    fn decode_into(&mut self, v: &Node) -> Result<(), DecodeError> {
723        self.0.decode_into(v)
724    }
725    fn is_empty(&self) -> bool {
726        self.0.is_empty()
727    }
728}
729
730impl<T: GoJson> GoJson for NonNil<BTreeMap<String, T>> {
731    const GO_TYPE: &'static str = "map";
732    const NULL_CLEARS: bool = true;
733    fn go_type() -> String {
734        BTreeMap::<String, T>::go_type()
735    }
736    fn encode(&self, out: &mut Vec<u8>) {
737        encode_map(&self.0, out);
738    }
739    fn decode_into(&mut self, v: &Node) -> Result<(), DecodeError> {
740        self.0.decode_into(v)
741    }
742    fn is_empty(&self) -> bool {
743        self.0.is_empty()
744    }
745}
746
747/// `http.Header` and `url.Values`.
748pub type Header = BTreeMap<String, Vec<String>>;
749/// `map[string]any`.
750pub type Metadata = BTreeMap<String, Value>;
751/// `map[string]string`.
752pub type StringMap = BTreeMap<String, String>;
753
754// ----------------------------------------------------------------------------------------
755// time.Time and json.RawMessage
756
757/// `time.Time`; `None` is the zero time (`0001-01-01T00:00:00Z`).
758#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
759pub struct GoTime(pub Option<DateTime<FixedOffset>>);
760
761impl GoTime {
762    pub fn now_utc() -> Self {
763        Self(Some(chrono::Utc::now().fixed_offset()))
764    }
765
766    pub fn is_zero(&self) -> bool {
767        self.0.is_none()
768    }
769
770    /// `time.Format(time.RFC3339Nano)`.
771    pub fn rfc3339_nano(&self) -> String {
772        let Some(t) = self.0 else {
773            return "0001-01-01T00:00:00Z".into();
774        };
775        let mut s = format!(
776            "{:04}-{:02}-{:02}T{:02}:{:02}:{:02}",
777            t.year(),
778            t.month(),
779            t.day(),
780            t.hour(),
781            t.minute(),
782            t.second()
783        );
784        let nanos = t.nanosecond() % 1_000_000_000;
785        if nanos != 0 {
786            let frac = format!("{nanos:09}");
787            s.push('.');
788            s.push_str(frac.trim_end_matches('0'));
789        }
790        let offset = t.offset().local_minus_utc();
791        if offset == 0 {
792            s.push('Z');
793        } else {
794            let sign = if offset < 0 { '-' } else { '+' };
795            let abs = offset.abs();
796            s.push_str(&format!("{sign}{:02}:{:02}", abs / 3600, abs % 3600 / 60));
797        }
798        s
799    }
800}
801
802impl GoJson for GoTime {
803    const GO_TYPE: &'static str = "time.Time";
804    fn encode(&self, out: &mut Vec<u8>) {
805        out.push(b'"');
806        out.extend_from_slice(self.rfc3339_nano().as_bytes());
807        out.push(b'"');
808    }
809    fn decode_value(v: &Node) -> Result<Self, DecodeError> {
810        match v {
811            Node::String(s) => {
812                let t = DateTime::parse_from_rfc3339(s)
813                    .map_err(|e| DecodeError(format!("parsing time {s:?} as RFC3339: {e}")))?;
814                let zero = t.naive_utc()
815                    == chrono::NaiveDate::from_ymd_opt(1, 1, 1)
816                        .unwrap()
817                        .and_hms_opt(0, 0, 0)
818                        .unwrap();
819                Ok(Self((!zero).then_some(t)))
820            }
821            other => Err(type_error(other, Self::GO_TYPE)),
822        }
823    }
824    fn is_empty(&self) -> bool {
825        false
826    }
827}
828
829/// `json.RawMessage`: marshalled compact with HTML escaping; `null` when empty.
830#[derive(Debug, Clone, Default, PartialEq, Eq)]
831pub struct RawJson(pub Bytes);
832
833impl GoJson for RawJson {
834    const GO_TYPE: &'static str = "json.RawMessage";
835    const NULL_CLEARS: bool = true;
836    fn encode(&self, out: &mut Vec<u8>) {
837        if self.0.is_empty() {
838            out.extend_from_slice(b"null");
839        } else {
840            out.extend_from_slice(&cpa_common::json::compact(&self.0, true));
841        }
842    }
843    /// The member's JSON text re-rendered compactly. ponytail: Go keeps the raw member
844    /// text; whitespace and string escapes (`\u003c` vs `<`) can differ, the JSON value
845    /// cannot. Keep source spans in `Node` if a byte-exact consumer appears.
846    fn decode_into(&mut self, v: &Node) -> Result<(), DecodeError> {
847        self.0 = Bytes::from(v.to_json());
848        Ok(())
849    }
850    fn is_empty(&self) -> bool {
851        self.0.is_empty()
852    }
853}
854
855#[cfg(test)]
856mod tests {
857    use super::*;
858
859    crate::go_struct! {
860        pub struct Sample("pluginapi.Sample") {
861            "AuthID" => auth_id: String,
862            "Body" => body: Bytes,
863            "Headers" => headers: Header,
864            "Count" => count: i64,
865            "path" omitempty => path: String,
866            "Meta" => meta: Metadata,
867            "At" => at: GoTime,
868            "Items" omitempty => items: Vec<String>,
869        }
870    }
871
872    #[test]
873    fn encodes_like_json_marshal() {
874        let mut headers = Header::new();
875        headers.insert("X-B".into(), vec!["2".into()]);
876        headers.insert("A".into(), vec!["<1>".into()]);
877        let s = Sample {
878            auth_id: "a&b".into(),
879            body: Bytes::from_static(b"hi"),
880            headers,
881            count: 7,
882            path: String::new(),
883            meta: [
884                ("z".to_owned(), serde_json::json!(1)),
885                ("a".to_owned(), serde_json::json!(0.5)),
886            ]
887            .into(),
888            at: GoTime::default(),
889            items: vec![],
890        };
891        assert_eq!(
892            String::from_utf8(to_vec(&s)).unwrap(),
893            r#"{"AuthID":"a\u0026b","Body":"aGk=","Headers":{"A":["\u003c1\u003e"],"X-B":["2"]},"Count":7,"Meta":{"a":0.5,"z":1},"At":"0001-01-01T00:00:00Z"}"#
894        );
895    }
896
897    /// Go matches keys exactly first, then case-insensitively; unknown keys are ignored;
898    /// integer fields reject non-integer literals.
899    #[test]
900    fn decodes_like_json_unmarshal() {
901        let s: Sample = from_slice(br#"{"authid":"x","AuthID":"y","body":"aGk=","unknown":1,"count":3,"PATH":"/p","at":"2026-01-02T03:04:05.5+02:00"}"#).unwrap();
902        assert_eq!(s.auth_id, "y");
903        assert_eq!(s.body, Bytes::from_static(b"hi"));
904        assert_eq!(s.count, 3);
905        assert_eq!(s.path, "/p");
906        assert_eq!(s.at.rfc3339_nano(), "2026-01-02T03:04:05.5+02:00");
907        let err = from_slice::<Sample>(br#"{"Count":1.5}"#).unwrap_err();
908        assert!(err.0.contains("Go struct field Sample.Count of type int64"), "{err}");
909        assert!(from_slice::<Sample>(br#"{"Body":"!!"}"#).is_err());
910        let s: Sample = from_slice(br#"{"Body":[104,105],"Count":null}"#).unwrap();
911        assert_eq!(s.body, Bytes::from_static(b"hi"));
912    }
913
914    /// Go decodes member by member into the existing value: a second spelling of a map
915    /// field merges keys; a later struct member decodes over the earlier one field by
916    /// field; base64 accepts non-zero trailing bits; a null byte element is 0.
917    #[test]
918    fn decodes_into_existing_values_like_go() {
919        crate::go_struct! {
920            pub struct Resp("pluginapi.ManagementResponse") {
921                "Headers" => headers: Header,
922                "Body" => body: Bytes,
923                "Inner" => inner: Option<Sample>,
924            }
925        }
926        let r: Resp = from_slice(
927            br#"{"Headers":{"A":["1"]},"headers":{"B":["2"]},"Body":"Zh==","Inner":{"Count":1},"inner":{"Path":"/p"}}"#,
928        )
929        .unwrap();
930        assert_eq!(r.headers.keys().collect::<Vec<_>>(), ["A", "B"]);
931        assert_eq!(r.body, Bytes::from_static(b"f"));
932        let inner = r.inner.unwrap();
933        assert_eq!((inner.count, inner.path.as_str()), (1, "/p"));
934        let r: Resp = from_slice(br#"{"Body":[null,65]}"#).unwrap();
935        assert_eq!(r.body, Bytes::from_static(&[0, 65]));
936        assert!(from_slice::<Resp>(br#"{"Body":[256]}"#).is_err());
937        assert!(from_slice::<Resp>(br#"{"Headers":{"a":["x"]},"Body":1e400}"#).is_err());
938        // An unknown member never needs to fit a Go type.
939        assert!(from_slice::<Resp>(br#"{"unused":1e400}"#).is_ok());
940    }
941
942    #[test]
943    fn non_nil_and_option_encode_empty_values() {
944        assert_eq!(to_vec(&NonNil(Vec::<String>::new())), b"[]");
945        assert_eq!(to_vec(&None::<Vec<String>>), b"null");
946        assert_eq!(to_vec(&Vec::<String>::new()), b"null");
947    }
948}