1use 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
45pub trait GoJson: Sized + Default {
47 const GO_TYPE: &'static str;
49 fn go_type() -> String {
52 Self::GO_TYPE.to_owned()
53 }
54 fn encode(&self, out: &mut Vec<u8>);
56 fn decode(v: &Node) -> Result<Self, DecodeError> {
58 let mut out = Self::default();
59 out.decode_into(v)?;
60 Ok(out)
61 }
62 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 fn decode_value(v: &Node) -> Result<Self, DecodeError> {
76 let mut out = Self::default();
77 out.decode_into(v)?;
78 Ok(out)
79 }
80 fn is_empty(&self) -> bool;
83 const NULL_CLEARS: bool = false;
86}
87
88pub fn to_vec<T: GoJson>(v: &T) -> Vec<u8> {
90 let mut out = Vec::new();
91 v.encode(&mut out);
92 out
93}
94
95pub fn from_slice<T: GoJson>(raw: &[u8]) -> Result<T, DecodeError> {
97 T::decode(&parse(raw)?)
98}
99
100pub 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
116pub 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
126pub 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
133pub 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 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
149pub 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 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
193pub trait GoStruct: GoJson {
195 fn encode_fields(&self, w: &mut ObjWriter<'_>);
196 fn decode_field(&mut self, key: &str, v: &Node) -> Option<Result<(), DecodeError>>;
199}
200
201pub 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
208pub 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 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#[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
296pub 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
302impl 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 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
359go_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 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
387fn 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 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
463fn 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
480impl 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#[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
522impl 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
538pub 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
574impl<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
629impl<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
654impl<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#[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
747pub type Header = BTreeMap<String, Vec<String>>;
749pub type Metadata = BTreeMap<String, Value>;
751pub type StringMap = BTreeMap<String, String>;
753
754#[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 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#[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 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 #[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 #[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 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}