buffa-types 0.9.2

Protobuf well-known types for buffa
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
//! Ergonomic helpers for [`google::protobuf::Any`](crate::google::protobuf::Any).

use alloc::string::String;

use crate::google::protobuf::Any;

impl Any {
    /// Pack a message into an [`Any`] with the given type URL.
    ///
    /// The type URL is conventionally of the form
    /// `type.googleapis.com/fully.qualified.TypeName`, but this method does
    /// not enforce that convention — any string is accepted.
    ///
    /// # Panics
    ///
    /// Panics if `msg`'s encoded size exceeds the 2 GiB protobuf limit
    /// ([`buffa::MAX_MESSAGE_BYTES`]) — see [`try_pack`](Self::try_pack)
    /// for the error-returning variant.
    pub fn pack(msg: &impl buffa::Message, type_url: impl Into<String>) -> Self {
        Self {
            type_url: type_url.into(),
            value: msg.encode_to_bytes(),
            ..Default::default()
        }
    }

    /// Pack a message into an [`Any`], returning an error instead of
    /// panicking if the message's encoded size exceeds the 2 GiB protobuf
    /// limit ([`buffa::MAX_MESSAGE_BYTES`]).
    ///
    /// # Errors
    ///
    /// Returns [`buffa::EncodeError::MessageTooLarge`] if the encoded size
    /// exceeds the limit.
    pub fn try_pack(
        msg: &impl buffa::Message,
        type_url: impl Into<String>,
    ) -> Result<Self, buffa::EncodeError> {
        Ok(Self {
            type_url: type_url.into(),
            value: msg.try_encode_to_bytes()?,
            ..Default::default()
        })
    }

    /// Unpack the contained message, decoding its bytes as `T`, **without
    /// checking the `type_url`**.
    ///
    /// This method always attempts to decode the payload as `T` regardless
    /// of whether `type_url` actually identifies `T`. Use [`Any::unpack_if`]
    /// when you need to verify the stored type before decoding.
    ///
    /// # Errors
    ///
    /// Returns a [`buffa::DecodeError`] if the bytes cannot be decoded as `T`.
    pub fn unpack_unchecked<T: buffa::Message>(&self) -> Result<T, buffa::DecodeError> {
        T::decode(&mut self.value.as_ref())
    }

    /// Unpack the contained message as `T`, but only if the `type_url`
    /// matches `expected_type_url`.
    ///
    /// Returns `Ok(None)` when the type URL does not match.
    ///
    /// # Errors
    ///
    /// Returns a [`buffa::DecodeError`] if the type URL matches but the bytes
    /// cannot be decoded as `T`.
    pub fn unpack_if<T: buffa::Message>(
        &self,
        expected_type_url: &str,
    ) -> Result<Option<T>, buffa::DecodeError> {
        if self.type_url != expected_type_url {
            return Ok(None);
        }
        T::decode(&mut self.value.as_ref()).map(Some)
    }

    /// Returns `true` if this [`Any`]'s `type_url` matches the given string.
    pub fn is_type(&self, type_url: &str) -> bool {
        self.type_url == type_url
    }

    /// Returns the type URL stored in this [`Any`].
    pub fn type_url(&self) -> &str {
        &self.type_url
    }
}

// ── WKT type registry ───────────────────────────────────────────────────────

/// Registers all well-known types with the given [`TypeRegistry`].
///
/// This registers Duration, Timestamp, FieldMask, Value, Struct, ListValue,
/// Empty, all wrapper types, Any itself, and the remaining official WKTs
/// (`Api`, `Method`, `Mixin`, `Type`, `Field`, `Enum`, `EnumValue`, `Option`,
/// `SourceContext`), enabling both proto3-compliant
/// JSON serialization (under the `json` feature) and textproto
/// `[type_url] { fields }` Any-expansion when these types appear inside
/// `google.protobuf.Any` fields.
///
/// Text entries are always registered (buffa-types unconditionally enables
/// `buffa/text`). JSON entries are registered under the `json` feature.
///
/// # Example
///
/// ```rust,no_run
/// use buffa::type_registry::{TypeRegistry, set_type_registry};
///
/// let mut reg = TypeRegistry::new();
/// buffa_types::register_wkt_types(&mut reg);
/// set_type_registry(reg);
/// ```
///
/// [`TypeRegistry`]: buffa::type_registry::TypeRegistry
pub fn register_wkt_types(reg: &mut buffa::type_registry::TypeRegistry) {
    use crate::google::protobuf::*;
    use buffa::type_registry::{any_encode_text, any_merge_text, TextAnyEntry};

    macro_rules! register_type {
        ($type:ty, $wkt:expr) => {
            #[cfg(feature = "json")]
            {
                use alloc::string::ToString;
                reg.register_json_any(buffa::type_registry::JsonAnyEntry {
                    type_url: <$type>::TYPE_URL,
                    to_json: |bytes| {
                        let msg = <$type as buffa::Message>::decode(&mut &*bytes)
                            .map_err(|e| e.to_string())?;
                        serde_json::to_value(&msg).map_err(|e| e.to_string())
                    },
                    from_json: |value| {
                        let msg: $type =
                            serde_json::from_value(value).map_err(|e| e.to_string())?;
                        buffa::Message::try_encode_to_vec(&msg).map_err(|e| e.to_string())
                    },
                    is_wkt: $wkt,
                });
            }
            // WKTs all implement TextFormat (generate_text is on for
            // buffa-types). Non-Option fn-ptrs — presence in the text map
            // means text-capable. `$wkt` is irrelevant here: textproto has
            // no `"value"` wrapping distinction.
            reg.register_text_any(TextAnyEntry {
                type_url: <$type>::TYPE_URL,
                text_encode: any_encode_text::<$type>,
                text_merge: any_merge_text::<$type>,
            });
        };
    }
    macro_rules! register_text_only {
        ($type:ty) => {
            reg.register_text_any(TextAnyEntry {
                type_url: <$type>::TYPE_URL,
                text_encode: any_encode_text::<$type>,
                text_merge: any_merge_text::<$type>,
            });
        };
    }

    // WKTs with special JSON mappings (use "value" wrapping in Any JSON).
    register_type!(Duration, true);
    register_type!(Timestamp, true);
    register_type!(FieldMask, true);
    register_type!(Value, true);
    register_type!(Struct, true);
    register_type!(ListValue, true);
    register_type!(BoolValue, true);
    register_type!(Int32Value, true);
    register_type!(UInt32Value, true);
    register_type!(Int64Value, true);
    register_type!(UInt64Value, true);
    register_type!(FloatValue, true);
    register_type!(DoubleValue, true);
    register_type!(StringValue, true);
    register_type!(BytesValue, true);
    register_type!(Any, true);

    // Regular messages (fields inlined in Any JSON). Empty has a
    // hand-written JSON impl; Api/Type/SourceContext and their parts have
    // generated text impls and no serde impls, so they register for
    // textproto Any-expansion without a JSON entry.
    register_type!(Empty, false);

    register_text_only!(Api);
    register_text_only!(Method);
    register_text_only!(Mixin);
    register_text_only!(Type);
    register_text_only!(Field);
    register_text_only!(Enum);
    register_text_only!(EnumValue);
    register_text_only!(crate::google::protobuf::Option);
    register_text_only!(SourceContext);
}

// ── TextFormat impl ─────────────────────────────────────────────────────────
//
// Hand-written because textproto packs `Any` as `[type_url] { fields }` when
// the type is registered — a shape the generated field-by-field impl can't
// produce. Codegen's `impl_text.rs` skips `google.protobuf.Any` to avoid a
// conflicting impl.
//
// `try_write_any_expanded` and `read_any_expansion` consult the text-format
// Any map (installed via `set_type_registry`). When no registry is installed,
// this degrades to the vanilla `type_url: "..." value: "..."` form — still
// valid textproto, just not the expanded form.

impl buffa::text::TextFormat for Any {
    fn encode_text(&self, enc: &mut buffa::text::TextEncoder<'_>) -> core::fmt::Result {
        if !self.type_url.is_empty() && enc.try_write_any_expanded(&self.type_url, &self.value)? {
            return Ok(());
        }
        // Vanilla fallback: unregistered type, or no registry installed.
        if !self.type_url.is_empty() {
            enc.write_field_name("type_url")?;
            enc.write_string(&self.type_url)?;
        }
        if !self.value.is_empty() {
            enc.write_field_name("value")?;
            enc.write_bytes(&self.value)?;
        }
        Ok(())
    }

    fn merge_text(
        &mut self,
        dec: &mut buffa::text::TextDecoder<'_>,
    ) -> Result<(), buffa::text::ParseError> {
        while let Some(name) = dec.read_field_name()? {
            match name {
                "type_url" => self.type_url = dec.read_string()?.into_owned(),
                "value" => self.value = dec.read_bytes()?.into(),
                _ if name.starts_with('[') => {
                    let (url, bytes) = dec.read_any_expansion(name)?;
                    self.type_url = url.into();
                    self.value = bytes.into();
                }
                _ => dec.skip_value()?,
            }
        }
        Ok(())
    }
}

#[cfg(test)]
mod text_tests {
    use super::Any;
    use buffa::text::{decode_from_str, encode_to_string};

    #[test]
    fn vanilla_roundtrip_no_registry() {
        // Without a registry installed, Any uses the plain
        // `type_url: "..." value: "..."` form — exactly what the old
        // generated impl did.
        let orig = Any {
            type_url: "type.example.com/Foo".into(),
            value: alloc::vec![0x08, 0x2A].into(), // field 1 = varint 42
            ..Default::default()
        };
        let text = encode_to_string(&orig);
        assert_eq!(text, r#"type_url: "type.example.com/Foo" value: "\010*""#);
        let back: Any = decode_from_str(&text).unwrap();
        assert_eq!(back.type_url, orig.type_url);
        assert_eq!(back.value, orig.value);
    }

    // Registry-manipulating tests live in `serde_tests` below — they share
    // the same global `AtomicPtr` as the JSON tests and must use the same
    // `REGISTRY_LOCK` to serialize.
}

// ── serde impls ──────────────────────────────────────────────────────────────
//
// Proto3 JSON for `Any` uses the global `AnyRegistry` to serialize the
// embedded message with its fields inline (regular messages) or wrapped in a
// `"value"` key (WKTs). Falls back to base64-encoded `value` when the
// registry is absent or the type URL is not registered.

#[cfg(feature = "json")]
struct Base64Bytes<'a>(&'a [u8]);

#[cfg(feature = "json")]
impl serde::Serialize for Base64Bytes<'_> {
    fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
        buffa::json_helpers::bytes::serialize(self.0, s)
    }
}

#[cfg(feature = "json")]
impl serde::Serialize for Any {
    fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
        use serde::ser::SerializeMap;

        if self.type_url.is_empty() {
            return s.serialize_map(Some(0))?.end();
        }

        let lookup = buffa::any_registry::with_any_registry(|reg| {
            reg.and_then(|r| r.lookup(&self.type_url))
                .map(|e| (e.to_json, e.is_wkt))
        });

        match lookup {
            Some((to_json, is_wkt)) => {
                // `to_json` decodes the payload and serializes it, so an `Any`
                // holding an `Any` re-enters this impl. See
                // `MAX_ANY_EXPANSION_DEPTH` for why the decoder's recursion
                // limit does not bound that.
                let Some(_depth_guard) = buffa::type_registry::enter_any_expansion() else {
                    return Err(serde::ser::Error::custom(alloc::format!(
                        "Any expansion nested deeper than {} levels",
                        buffa::type_registry::MAX_ANY_EXPANSION_DEPTH
                    )));
                };
                let json_val = to_json(&self.value).map_err(serde::ser::Error::custom)?;
                if is_wkt {
                    let mut map = s.serialize_map(Some(2))?;
                    map.serialize_entry("@type", &self.type_url)?;
                    map.serialize_entry("value", &json_val)?;
                    map.end()
                } else {
                    let fields = match &json_val {
                        serde_json::Value::Object(m) => m,
                        _ => {
                            return Err(serde::ser::Error::custom(
                                "Any: to_json for non-WKT must return a JSON object",
                            ))
                        }
                    };
                    let mut map = s.serialize_map(Some(1 + fields.len()))?;
                    map.serialize_entry("@type", &self.type_url)?;
                    for (k, v) in fields {
                        map.serialize_entry(k, v)?;
                    }
                    map.end()
                }
            }
            None => {
                let mut map = s.serialize_map(Some(2))?;
                map.serialize_entry("@type", &self.type_url)?;
                map.serialize_entry("value", &Base64Bytes(&self.value))?;
                map.end()
            }
        }
    }
}

#[cfg(feature = "json")]
impl<'de> serde::Deserialize<'de> for Any {
    fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
        // Buffer the entire object so @type can appear at any position.
        let mut obj: serde_json::Map<String, serde_json::Value> =
            serde::Deserialize::deserialize(d)?;

        let type_url = match obj.remove("@type") {
            Some(serde_json::Value::String(s)) => s,
            Some(_) => {
                return Err(serde::de::Error::custom("@type must be a string"));
            }
            None if obj.is_empty() => return Ok(Self::default()),
            None => {
                return Err(serde::de::Error::custom(
                    "Any object missing string \"@type\"",
                ));
            }
        };

        // The type URL must be non-empty, contain a '/', and have a non-empty
        // fully-qualified type name after the final slash (e.g.
        // "type.googleapis.com/google.protobuf.Duration").
        let type_name = type_url.rsplit('/').next().unwrap_or("");
        if type_url.is_empty() || !type_url.contains('/') || type_name.is_empty() {
            return Err(serde::de::Error::custom(
                "@type must be a valid type URL containing a '/' and a non-empty type name (e.g. type.googleapis.com/pkg.Type)",
            ));
        }

        let lookup = buffa::any_registry::with_any_registry(|reg| {
            reg.and_then(|r| r.lookup(&type_url))
                .map(|e| (e.from_json, e.is_wkt))
        });

        let value = match lookup {
            Some((from_json, true)) => {
                let json_val = obj.remove("value").unwrap_or(serde_json::Value::Null);
                from_json(json_val).map_err(serde::de::Error::custom)?
            }
            Some((from_json, false)) => {
                let json_obj = serde_json::Value::Object(obj);
                from_json(json_obj).map_err(serde::de::Error::custom)?
            }
            None => {
                // Fallback: base64 decode the "value" field.
                match obj.remove("value") {
                    Some(serde_json::Value::String(s)) => buffa::json_helpers::bytes::deserialize(
                        serde::de::value::StringDeserializer::<D::Error>::new(s),
                    )?,
                    _ => alloc::vec::Vec::new(),
                }
            }
        };

        Ok(Self {
            type_url,
            value: value.into(),
            ..Default::default()
        })
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::google::protobuf::Timestamp;
    use buffa::Message as _;

    #[test]
    fn any_view_to_owned_from_source_is_zero_copy() {
        use crate::google::protobuf::__buffa::view::AnyView;
        use buffa::view::{MessageView as _, OwnedView};

        let src = Any {
            type_url: "type.googleapis.com/x".into(),
            value: bytes::Bytes::from_static(&[1u8; 256]),
            ..Default::default()
        };
        let buf = bytes::Bytes::from(src.encode_to_vec());

        // Direct trait path: to_owned_from_source(Some(&buf)) → slice_ref.
        let view = AnyView::decode_view(&buf).unwrap();
        let owned = view.to_owned_from_source(Some(&buf)).unwrap();
        assert_eq!(owned.value, src.value);
        let value_ptr = owned.value.as_ptr() as usize;
        let buf_range = (buf.as_ptr() as usize)..(buf.as_ptr() as usize + buf.len());
        assert!(
            buf_range.contains(&value_ptr),
            "owned.value should point into buf (slice_ref), got {value_ptr:#x} outside {buf_range:#x?}"
        );

        // OwnedView path: the inherent OwnedView::to_owned_message routes
        // through to_owned_from_source(Some(&self.bytes)), so the bytes field
        // is a zero-copy slice_ref into the retained buffer.
        let ov = OwnedView::<AnyView<'static>>::decode(buf.clone()).unwrap();
        let owned2 = ov.to_owned_message();
        assert_eq!(owned2.value, src.value);
        assert!(buf_range.contains(&(owned2.value.as_ptr() as usize)));

        // No-source path still copies (correct, distinct allocation).
        let copied = view.to_owned_message().unwrap();
        assert_eq!(copied.value, src.value);
        assert!(!buf_range.contains(&(copied.value.as_ptr() as usize)));
    }

    #[cfg(feature = "arbitrary")]
    #[test]
    fn any_arbitrary_with_bytes_value() {
        use arbitrary::{Arbitrary, Unstructured};
        // Regression pin for https://github.com/anthropics/buffa/issues/88:
        // Any.value is bytes::Bytes (not Vec<u8>), so derive(Arbitrary) on Any
        // requires the ::buffa::__private::arbitrary_bytes shim.
        let raw = [0u8; 64];
        let mut u = Unstructured::new(&raw);
        let any = Any::arbitrary(&mut u).unwrap();
        let _ = any.value.slice(..);
    }

    /// Test double whose `compute_size` reports over the 2 GiB limit and
    /// whose `write_to` writes nothing — exercises `pack`'s guard without
    /// materializing gigabytes. Mirrors buffa's crate-internal
    /// `test_doubles::SizedMsg` (`#[cfg(test)]` items don't cross the crate
    /// boundary).
    #[derive(Clone, Default, PartialEq, Debug)]
    struct HugeMsg;

    impl buffa::DefaultInstance for HugeMsg {
        fn default_instance() -> &'static Self {
            static INST: buffa::__private::OnceBox<HugeMsg> = buffa::__private::OnceBox::new();
            INST.get_or_init(|| alloc::boxed::Box::new(HugeMsg))
        }
    }

    impl buffa::Message for HugeMsg {
        fn compute_size(&self, _cache: &mut buffa::SizeCache) -> u32 {
            buffa::MAX_MESSAGE_BYTES + 1
        }
        fn write_to(&self, _cache: &mut buffa::SizeCache, _buf: &mut impl buffa::EncodeSink) {}
        fn merge_field(
            &mut self,
            tag: buffa::encoding::Tag,
            buf: &mut impl bytes::Buf,
            _ctx: buffa::DecodeContext<'_>,
        ) -> Result<(), buffa::DecodeError> {
            buffa::encoding::skip_field(tag, buf)?;
            Ok(())
        }
        fn clear(&mut self) {}
    }

    #[test]
    fn try_pack_over_limit_errs() {
        assert_eq!(
            Any::try_pack(&HugeMsg, "type.googleapis.com/x"),
            Err(buffa::EncodeError::MessageTooLarge)
        );
    }

    #[test]
    #[should_panic(expected = "2 GiB protobuf limit")]
    fn pack_over_limit_panics() {
        let _ = Any::pack(&HugeMsg, "type.googleapis.com/x");
    }

    #[test]
    fn try_pack_matches_pack_for_normal_messages() {
        let ts = Timestamp {
            seconds: 42,
            ..Default::default()
        };
        let url = "type.googleapis.com/google.protobuf.Timestamp";
        assert_eq!(Any::try_pack(&ts, url).unwrap(), Any::pack(&ts, url));
    }

    #[test]
    fn pack_and_unpack() {
        let ts = Timestamp {
            seconds: 1_000_000_000,
            nanos: 0,
            ..Default::default()
        };
        let any = Any::pack(&ts, "type.googleapis.com/google.protobuf.Timestamp");
        assert_eq!(
            any.type_url(),
            "type.googleapis.com/google.protobuf.Timestamp"
        );

        let decoded: Timestamp = any.unpack_unchecked().unwrap();
        assert_eq!(decoded, ts);
    }

    #[test]
    fn unpack_if_matching() {
        let ts = Timestamp {
            seconds: 42,
            ..Default::default()
        };
        let any = Any::pack(&ts, "type.googleapis.com/google.protobuf.Timestamp");

        let result: Option<Timestamp> = any
            .unpack_if("type.googleapis.com/google.protobuf.Timestamp")
            .unwrap();
        assert_eq!(result, Some(ts));
    }

    #[test]
    fn unpack_if_wrong_type_returns_none() {
        let ts = Timestamp {
            seconds: 42,
            ..Default::default()
        };
        let any = Any::pack(&ts, "type.googleapis.com/google.protobuf.Timestamp");

        let result: Option<Timestamp> = any
            .unpack_if("type.googleapis.com/google.protobuf.Duration")
            .unwrap();
        assert!(result.is_none());
    }

    #[test]
    fn clone_shares_payload_buffer() {
        let orig = Any {
            type_url: "type.googleapis.com/example.Msg".into(),
            value: alloc::vec![0xAB; 1024].into(),
            ..Default::default()
        };
        let dup = orig.clone();
        assert_eq!(orig.value.as_ptr(), dup.value.as_ptr());
        assert_eq!(orig.value.len(), dup.value.len());
    }

    #[test]
    fn is_type() {
        let ts = Timestamp::default();
        let any = Any::pack(&ts, "type.googleapis.com/google.protobuf.Timestamp");
        assert!(any.is_type("type.googleapis.com/google.protobuf.Timestamp"));
        assert!(!any.is_type("type.googleapis.com/google.protobuf.Duration"));
    }

    #[test]
    fn round_trip_encoding() {
        let ts = Timestamp {
            seconds: 99,
            nanos: 1,
            ..Default::default()
        };
        let any = Any::pack(&ts, "test");

        let bytes = any.encode_to_vec();
        let decoded_any = Any::decode(&mut bytes.as_slice()).unwrap();
        let decoded_ts: Timestamp = decoded_any.unpack_unchecked().unwrap();
        assert_eq!(decoded_ts, ts);
    }

    #[cfg(feature = "json")]
    mod serde_tests {
        use super::*;
        use crate::google::protobuf::Duration;
        use buffa::any_registry::clear_any_registry;
        use buffa::type_registry::{
            clear_text_registry, set_type_registry, TypeRegistry, MAX_ANY_EXPANSION_DEPTH,
        };

        /// Mutex to serialize tests that manipulate the global registries.
        /// Each test binary needs its own lock since #[cfg(test)] modules
        /// cannot be shared across crates.
        static REGISTRY_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());

        fn with_registry<R>(f: impl FnOnce() -> R) -> R {
            let _guard = REGISTRY_LOCK.lock().unwrap();
            let mut reg = TypeRegistry::new();
            register_wkt_types(&mut reg);
            set_type_registry(reg);
            let result = f();
            clear_any_registry();
            clear_text_registry();
            result
        }

        fn without_registry<R>(f: impl FnOnce() -> R) -> R {
            let _guard = REGISTRY_LOCK.lock().unwrap();
            clear_any_registry();
            clear_text_registry();
            f()
        }

        // ── TextFormat impl (Any expansion) ─────────────────────────────────
        //
        // Here rather than in `text_tests` because these manipulate the
        // same global `AtomicPtr` as the JSON tests above — both must
        // serialize on `REGISTRY_LOCK`.

        #[test]
        fn text_registry_roundtrip_wkt() {
            use crate::google::protobuf::Empty;
            use buffa::text::{decode_from_str, encode_to_string};
            with_registry(|| {
                // register_wkt_types installs Empty with text fn-ptrs.
                let any = Any::pack(&Empty::default(), Empty::TYPE_URL);
                let text = encode_to_string(&any);
                // Empty has no fields → `{}`.
                assert_eq!(text, "[type.googleapis.com/google.protobuf.Empty] {}");

                let back: Any = decode_from_str(&text).unwrap();
                assert_eq!(back.type_url, Empty::TYPE_URL);
                assert_eq!(back.value, alloc::vec::Vec::<u8>::new());
            });
        }

        #[test]
        fn text_registry_roundtrip_source_context() {
            use crate::google::protobuf::SourceContext;
            use buffa::text::{decode_from_str, encode_to_string};
            with_registry(|| {
                let sc = SourceContext {
                    file_name: "google/protobuf/api.proto".into(),
                    ..Default::default()
                };
                let any = Any::pack(&sc, SourceContext::TYPE_URL);
                let text = encode_to_string(&any);
                assert_eq!(
                    text,
                    r#"[type.googleapis.com/google.protobuf.SourceContext] {file_name: "google/protobuf/api.proto"}"#
                );

                let back: Any = decode_from_str(&text).unwrap();
                assert_eq!(back.type_url, SourceContext::TYPE_URL);
                let unpacked: SourceContext = back.unpack_unchecked().unwrap();
                assert_eq!(unpacked.file_name, sc.file_name);
            });
        }

        #[test]
        fn text_registry_roundtrip_type_and_option() {
            // `Type` carries a repeated message and an enum; `Option` holds
            // an `Any`, so its expansion nests a second registered type.
            use crate::google::protobuf::{Field, SourceContext, Syntax, Type};
            use buffa::text::{decode_from_str, encode_to_string};
            with_registry(|| {
                let ty = Type {
                    name: "google.example.v1.Msg".into(),
                    fields: alloc::vec![Field {
                        name: "id".into(),
                        number: 1,
                        json_name: "id".into(),
                        ..Default::default()
                    }],
                    syntax: Syntax::SYNTAX_PROTO3.into(),
                    ..Default::default()
                };
                let any = Any::pack(&ty, Type::TYPE_URL);
                let text = encode_to_string(&any);
                assert!(
                    text.starts_with("[type.googleapis.com/google.protobuf.Type] {"),
                    "{text}"
                );
                let back: Any = decode_from_str(&text).unwrap();
                let unpacked: Type = back.unpack_unchecked().unwrap();
                assert_eq!(unpacked, ty);

                let sc = SourceContext {
                    file_name: "a/b.proto".into(),
                    ..Default::default()
                };
                let opt = crate::google::protobuf::Option {
                    name: "source".into(),
                    value: buffa::MessageField::some(Any::pack(&sc, SourceContext::TYPE_URL)),
                    ..Default::default()
                };
                let any = Any::pack(&opt, crate::google::protobuf::Option::TYPE_URL);
                let text = encode_to_string(&any);
                assert!(
                    text.contains("[type.googleapis.com/google.protobuf.SourceContext]"),
                    "nested Any must expand through the registry: {text}"
                );
                let back: Any = decode_from_str(&text).unwrap();
                let unpacked: crate::google::protobuf::Option = back.unpack_unchecked().unwrap();
                assert_eq!(unpacked, opt);
            });
        }

        #[test]
        fn text_unregistered_url_errors_on_decode() {
            use buffa::text::decode_from_str;
            // Registry installed but URL not in it — the
            // `AnyFieldWithInvalidType` conformance shape.
            with_registry(|| {
                let result: Result<Any, _> =
                    decode_from_str("[type.googleapis.com/unknown.Type] { x: 1 }");
                assert!(result.is_err(), "unknown URL should error, not skip");
            });
        }

        #[test]
        fn text_bracket_without_registry_errors() {
            use buffa::text::decode_from_str;
            // No registry at all → bracket name is a registry miss → error.
            without_registry(|| {
                let result: Result<Any, _> = decode_from_str("[type.example.com/Unknown] { x: 1 }");
                assert!(result.is_err());
            });
        }

        #[test]
        fn serialize_wkt_uses_value_wrapping() {
            with_registry(|| {
                let ts = Timestamp {
                    seconds: 1_000_000_000,
                    nanos: 0,
                    ..Default::default()
                };
                let any = Any::pack(&ts, Timestamp::TYPE_URL);
                let json = serde_json::to_value(&any).unwrap();
                assert_eq!(json["@type"], Timestamp::TYPE_URL);
                assert_eq!(json["value"], "2001-09-09T01:46:40Z");
            });
        }

        #[test]
        fn serialize_duration_wkt() {
            with_registry(|| {
                let dur = Duration::from_secs_nanos(1, 500_000_000);
                let any = Any::pack(&dur, Duration::TYPE_URL);
                let json = serde_json::to_value(&any).unwrap();
                assert_eq!(json["@type"], Duration::TYPE_URL);
                assert_eq!(json["value"], "1.500s");
            });
        }

        #[test]
        fn serialize_empty_any_is_empty_object() {
            with_registry(|| {
                let any = Any::default();
                let json = serde_json::to_string(&any).unwrap();
                assert_eq!(json, "{}");
            });
        }

        #[test]
        fn deserialize_wkt_from_json() {
            with_registry(|| {
                let json = r#"{
                    "@type": "type.googleapis.com/google.protobuf.Duration",
                    "value": "1.5s"
                }"#;
                let any: Any = serde_json::from_str(json).unwrap();
                assert_eq!(any.type_url, Duration::TYPE_URL);

                let dur: Duration = any.unpack_unchecked().unwrap();
                assert_eq!(dur.seconds, 1);
                assert_eq!(dur.nanos, 500_000_000);
            });
        }

        #[test]
        fn deserialize_unordered_type_tag() {
            with_registry(|| {
                // @type appears after the value field.
                let json = r#"{
                    "value": "1.5s",
                    "@type": "type.googleapis.com/google.protobuf.Duration"
                }"#;
                let any: Any = serde_json::from_str(json).unwrap();
                assert_eq!(any.type_url, Duration::TYPE_URL);

                let dur: Duration = any.unpack_unchecked().unwrap();
                assert_eq!(dur.seconds, 1);
                assert_eq!(dur.nanos, 500_000_000);
            });
        }

        #[test]
        fn roundtrip_wkt_json() {
            with_registry(|| {
                let ts = Timestamp {
                    seconds: 1_000_000_000,
                    nanos: 0,
                    ..Default::default()
                };
                let any = Any::pack(&ts, Timestamp::TYPE_URL);
                let json = serde_json::to_string(&any).unwrap();
                let decoded: Any = serde_json::from_str(&json).unwrap();
                let decoded_ts: Timestamp = decoded.unpack_unchecked().unwrap();
                assert_eq!(decoded_ts, ts);
            });
        }

        #[test]
        fn nested_any_roundtrip() {
            with_registry(|| {
                let dur = Duration::from_secs(42);
                let inner_any = Any::pack(&dur, Duration::TYPE_URL);
                let outer_any = Any::pack(&inner_any, Any::TYPE_URL);

                let json = serde_json::to_string(&outer_any).unwrap();
                let decoded_outer: Any = serde_json::from_str(&json).unwrap();
                let decoded_inner: Any = decoded_outer.unpack_unchecked().unwrap();
                let decoded_dur: Duration = decoded_inner.unpack_unchecked().unwrap();
                assert_eq!(decoded_dur.seconds, 42);
            });
        }

        #[test]
        fn fallback_base64_without_registry() {
            without_registry(|| {
                let any = Any {
                    type_url: "type.googleapis.com/unknown.Type".into(),
                    value: vec![0x08, 0x96, 0x01].into(),
                    ..Default::default()
                };
                let json = serde_json::to_string(&any).unwrap();
                assert!(json.contains("@type"));
                assert!(json.contains("value"));

                let decoded: Any = serde_json::from_str(&json).unwrap();
                assert_eq!(decoded.type_url, any.type_url);
                assert_eq!(decoded.value, any.value);
            });
        }

        #[test]
        fn deserialize_missing_type_returns_default() {
            let json = r#"{}"#;
            let any: Any = serde_json::from_str(json).unwrap();
            assert_eq!(any, Any::default());
        }

        #[test]
        fn deserialize_rejects_nonempty_object_without_type() {
            for json in [r#"{"value":""}"#, r#"{"unknown":1}"#] {
                let err = serde_json::from_str::<Any>(json).unwrap_err();
                assert!(
                    err.to_string()
                        .contains("Any object missing string \"@type\""),
                    "{json}: {err}"
                );
            }
        }

        #[test]
        fn fallback_base64_with_registry_but_unknown_type() {
            with_registry(|| {
                let any = Any {
                    type_url: "type.googleapis.com/unknown.Type".into(),
                    value: vec![0x08, 0x96, 0x01].into(),
                    ..Default::default()
                };
                let json = serde_json::to_string(&any).unwrap();
                let decoded: Any = serde_json::from_str(&json).unwrap();
                assert_eq!(decoded.type_url, any.type_url);
                assert_eq!(decoded.value, any.value);
            });
        }

        #[test]
        fn deserialize_rejects_empty_type_url() {
            let json = r#"{"@type": "", "value": ""}"#;
            let err = serde_json::from_str::<Any>(json).unwrap_err();
            assert!(err.to_string().contains("valid type URL"), "{err}");
        }

        #[test]
        fn deserialize_rejects_type_url_without_slash() {
            let json = r#"{"@type": "not_a_url", "value": ""}"#;
            let err = serde_json::from_str::<Any>(json).unwrap_err();
            assert!(err.to_string().contains("valid type URL"), "{err}");
        }

        #[test]
        fn deserialize_accepts_arbitrary_type_url_prefix() {
            without_registry(|| {
                let json = r#"{"@type": "example.com/custom.Type", "value": "CAI="}"#;
                let any: Any = serde_json::from_str(json).unwrap();
                assert_eq!(any.type_url, "example.com/custom.Type");
                assert_eq!(any.value, vec![0x08, 0x02]);
            });
        }

        #[test]
        fn deserialize_rejects_type_url_with_empty_type_name() {
            without_registry(|| {
                let json = r#"{"@type": "type.googleapis.com/", "value": ""}"#;
                let err = serde_json::from_str::<Any>(json).unwrap_err();
                assert!(err.to_string().contains("valid type URL"), "{err}");
            });
        }

        // ── Non-WKT registered type (fields inlined at top level) ─────
        // WKTs use {"@type": ..., "value": <json>} wrapping.
        // Regular messages use {"@type": ..., "field1": ..., "field2": ...}.
        // Previously only the WKT path was tested.

        /// Hand-written to_json: decode the Any bytes as a single varint
        /// field (number=1), return it as a JSON object {"id": N}.
        fn user_type_to_json(bytes: &[u8]) -> Result<serde_json::Value, String> {
            use buffa::encoding::Tag;
            let mut cur = bytes;
            let mut id = 0i64;
            while !cur.is_empty() {
                let tag = Tag::decode(&mut cur).map_err(|e| e.to_string())?;
                if tag.field_number() == 1 {
                    id =
                        buffa::encoding::decode_varint(&mut cur).map_err(|e| e.to_string())? as i64;
                } else {
                    buffa::encoding::skip_field(tag, &mut cur).map_err(|e| e.to_string())?;
                }
            }
            Ok(serde_json::json!({ "id": id }))
        }

        /// Hand-written from_json: extract {"id": N}, encode as varint field 1.
        fn user_type_from_json(value: serde_json::Value) -> Result<alloc::vec::Vec<u8>, String> {
            use buffa::encoding::{encode_varint, Tag, WireType};
            let id = value
                .get("id")
                .and_then(|v| v.as_i64())
                .ok_or_else(|| "missing or invalid 'id' field".to_string())?;
            let mut buf = alloc::vec::Vec::new();
            Tag::new(1, WireType::Varint).encode(&mut buf);
            encode_varint(id as u64, &mut buf);
            Ok(buf)
        }

        fn with_user_type_registry<R>(f: impl FnOnce() -> R) -> R {
            use buffa::type_registry::JsonAnyEntry;
            let _guard = REGISTRY_LOCK.lock().unwrap();
            let mut reg = TypeRegistry::new();
            // Register as NON-WKT (is_wkt=false) — fields inline at top level.
            reg.register_json_any(JsonAnyEntry {
                type_url: "type.example.com/user.Thing",
                to_json: user_type_to_json,
                from_json: user_type_from_json,
                is_wkt: false,
            });
            set_type_registry(reg);
            let result = f();
            clear_any_registry();
            clear_text_registry();
            result
        }

        #[test]
        fn serialize_non_wkt_inlines_fields() {
            with_user_type_registry(|| {
                // Encode {id: 42} as proto wire bytes.
                let any = Any {
                    type_url: "type.example.com/user.Thing".into(),
                    // field 1, varint 42: tag=0x08, value=0x2A
                    value: vec![0x08, 0x2A].into(),
                    ..Default::default()
                };

                let json = serde_json::to_value(&any).unwrap();
                // Non-WKT format: fields at top level alongside @type.
                assert_eq!(json["@type"], "type.example.com/user.Thing");
                assert_eq!(json["id"], 42);
                // Should NOT have a "value" wrapper key.
                assert!(
                    json.get("value").is_none(),
                    "non-WKT should not use 'value' wrapping: {json}"
                );
            });
        }

        #[test]
        fn deserialize_non_wkt_from_inlined_fields() {
            with_user_type_registry(|| {
                let json = r#"{
                    "@type": "type.example.com/user.Thing",
                    "id": 99
                }"#;
                let any: Any = serde_json::from_str(json).unwrap();
                assert_eq!(any.type_url, "type.example.com/user.Thing");
                // Verify the from_json encoded it back to wire bytes.
                assert_eq!(any.value, vec![0x08, 99]);
            });
        }

        #[test]
        fn non_wkt_round_trip() {
            with_user_type_registry(|| {
                let original = Any {
                    type_url: "type.example.com/user.Thing".into(),
                    value: vec![0x08, 0x07].into(), // id=7
                    ..Default::default()
                };
                let json = serde_json::to_string(&original).unwrap();
                let decoded: Any = serde_json::from_str(&json).unwrap();
                assert_eq!(decoded.type_url, original.type_url);
                assert_eq!(decoded.value, original.value);
            });
        }

        #[test]
        fn serialize_non_wkt_rejects_non_object_json() {
            // If to_json for a non-WKT type returns something other than a
            // JSON object, serialization must fail (can't inline non-object
            // fields alongside @type).
            use buffa::type_registry::JsonAnyEntry;
            let _guard = REGISTRY_LOCK.lock().unwrap();
            let mut reg = TypeRegistry::new();
            reg.register_json_any(JsonAnyEntry {
                type_url: "type.example.com/user.BadType",
                to_json: |_bytes| Ok(serde_json::Value::Number(42.into())),
                from_json: |_v| Ok(alloc::vec::Vec::new()),
                is_wkt: false,
            });
            set_type_registry(reg);

            let any = Any {
                type_url: "type.example.com/user.BadType".into(),
                value: vec![].into(),
                ..Default::default()
            };
            let result = serde_json::to_string(&any);
            clear_any_registry();
            clear_text_registry();
            assert!(result.is_err(), "expected error for non-object to_json");
            assert!(
                result
                    .unwrap_err()
                    .to_string()
                    .contains("must return a JSON object"),
                "wrong error message"
            );
        }

        /// Corrupt `Any.value` bytes are ordinary untrusted input, not an
        /// invariant violation, so encoding them must not panic.
        ///
        /// `Any.value` is a raw `bytes` field that decode never validates.
        /// The release path already falls back to an empty body; a
        /// `debug_assert!` on the same condition makes a single malformed
        /// byte a panic wherever debug assertions are on — which this test
        /// suite has, so it fails here.
        #[test]
        fn corrupt_any_value_bytes_encode_to_text_without_panicking() {
            with_registry(|| {
                let a = Any {
                    type_url: Duration::TYPE_URL.to_string(),
                    // 0xFF is a varint continuation byte with nothing after
                    // it: a truncated field, not a valid Duration.
                    value: bytes::Bytes::from_static(&[0xFF]),
                    ..Default::default()
                };
                assert_eq!(
                    buffa::text::encode_to_string(&a),
                    "[type.googleapis.com/google.protobuf.Duration] {}",
                    "the expansion is still emitted, with an empty body"
                );
            });
        }

        #[test]
        fn deserialize_rejects_non_string_type() {
            // @type as a non-string value → error.
            let json = r#"{"@type": 123}"#;
            let err = serde_json::from_str::<Any>(json).unwrap_err();
            assert!(err.to_string().contains("@type must be a string"), "{err}");
        }

        /// An `Any` chain `depth` levels deep.
        fn any_chain(depth: usize) -> Any {
            let mut cur = Any::default();
            for _ in 0..depth {
                cur = Any {
                    type_url: Any::TYPE_URL.to_string(),
                    value: buffa::Message::encode_to_vec(&cur).into(),
                    ..Default::default()
                };
            }
            cur
        }

        #[test]
        fn a_shallow_any_chain_still_expands() {
            with_registry(|| {
                let json = serde_json::to_string(&any_chain(8)).expect("well within the cap");
                // Eight expansions, so eight nested "@type" keys.
                assert_eq!(json.matches("\"@type\"").count(), 8, "{json}");
            });
        }

        #[test]
        fn a_deep_any_chain_is_refused_rather_than_recursed() {
            with_registry(|| {
                // Deep enough to overflow a worker-sized stack if unbounded:
                // the decode below is cheap and shallow either way.
                let deep = any_chain(usize::try_from(MAX_ANY_EXPANSION_DEPTH).unwrap() + 5);
                let wire = buffa::Message::encode_to_vec(&deep);
                let decoded = <Any as buffa::Message>::decode_from_slice(&wire)
                    .expect("decoding the chain is one level deep and always succeeds");

                let err = serde_json::to_string(&decoded)
                    .expect_err("expansion past the cap must be an error, not a deeper stack");
                assert!(
                    err.to_string()
                        .contains(&alloc::format!("{MAX_ANY_EXPANSION_DEPTH} levels")),
                    "the error should state the limit it hit, as a number the \
                     reader can act on rather than a constant to go look up: {err}"
                );
            });
        }

        #[test]
        fn the_expansion_depth_is_restored_after_a_refusal() {
            with_registry(|| {
                let deep = any_chain(usize::try_from(MAX_ANY_EXPANSION_DEPTH).unwrap() + 5);
                assert!(serde_json::to_string(&deep).is_err());

                // The counter is ambient, so a refusal that failed to unwind
                // it would leave this thread unable to serialize any `Any`
                // again — a far worse outcome than the rejection itself.
                let json = serde_json::to_string(&any_chain(4))
                    .expect("a rejected serialization must not poison the thread");
                assert_eq!(json.matches("\"@type\"").count(), 4, "{json}");
            });
        }

        #[test]
        fn a_deep_any_chain_falls_back_to_the_vanilla_text_form() {
            with_registry(|| {
                let deep = any_chain(usize::try_from(MAX_ANY_EXPANSION_DEPTH).unwrap() + 5);
                // Textproto has no error channel here beyond a writer failure,
                // so past the cap the encoder emits the unexpanded
                // `type_url`/`value` form: still valid textproto, and finite.
                let text = buffa::text::encode_to_string(&deep);
                assert!(
                    text.contains("type_url:"),
                    "the innermost levels must fall back to the vanilla form: {text}"
                );
                // Count the expansion bracket itself, not bare `[` — a length
                // prefix of 0x5B inside the escaped `value` bytes renders as a
                // literal `[` and would inflate a looser count. Exact, so a
                // regression that expands one level too many also fails.
                assert_eq!(
                    text.matches("[type.googleapis.com/google.protobuf.Any]")
                        .count(),
                    usize::try_from(MAX_ANY_EXPANSION_DEPTH).unwrap(),
                    "expansion should stop at exactly the cap"
                );
            });
        }
    }
}