buffa 0.9.2

A pure Rust Protocol Buffers implementation with first-class editions support
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
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
//! Unified type registry for `Any` expansion and extension brackets — JSON + text.
//!
//! `google.protobuf.Any` in both proto3 JSON and textproto needs to know how
//! to serialize the embedded message by its type URL. Extension fields in
//! both formats likewise need a lookup by `(extendee, number)` or
//! `[full_name]`. This module is the single install point for both formats:
//! populate a [`TypeRegistry`] with generated `register_types(&mut reg)` calls,
//! then [`set_type_registry`] once at startup.
//!
//! The per-format entry types are feature-split so that `json` and `text`
//! are independently enableable — no `#[cfg]` on struct-literal fields, no
//! `Option<fn>` placeholders, no cross-feature implication.
//!
//! # Usage
//!
//! ```rust,no_run
//! use buffa::type_registry::{TypeRegistry, set_type_registry};
//!
//! let mut reg = TypeRegistry::new();
//! // Per generated file — registers JSON entries (if generate_json was on)
//! // and text entries (if generate_text was on), as appropriate:
//! // my_pkg::register_types(&mut reg);
//! // Well-known types (hand-registered in buffa-types):
//! // buffa_types::register_wkt_types(&mut reg);
//! set_type_registry(reg);
//! ```
//!
//! # Codegen helpers
//!
//! [`any_to_json`] / [`any_from_json`] (under `json`) and [`any_encode_text`] /
//! [`any_merge_text`] (under `text`) are generic function pointers emitted by
//! codegen into each message's entry consts. They compose
//! `Message::decode_from_slice` / `encode_to_vec` with the message's own
//! `Serialize`/`Deserialize` or `TextFormat` impl.

use alloc::boxed::Box;

/// Maximum nesting depth of `google.protobuf.Any` expansions in one
/// serialization.
///
/// `Any` is a flat two-field message (`string type_url`, `bytes value`) whose
/// nesting lives entirely inside the opaque `value` bytes. A decoder therefore
/// spends a single [`RECURSION_LIMIT`](crate::RECURSION_LIMIT) level on a chain
/// of any length — the recursion happens later, when a serializer expands each
/// level in turn by decoding it and serializing the result. That expansion is
/// what this bounds.
///
/// Set to the same value as [`RECURSION_LIMIT`](crate::RECURSION_LIMIT): both
/// bound how deeply one message may nest inside another, and one number is
/// easier to reason about than two. Legitimate `Any` nesting is one or two
/// levels.
///
/// This cap is a constant.
/// [`DecodeOptions::with_recursion_limit`](crate::DecodeOptions::with_recursion_limit)
/// does not move it, since it bounds serialization rather than decoding.
pub const MAX_ANY_EXPANSION_DEPTH: u32 = crate::RECURSION_LIMIT;

// ── Any-expansion depth tracking ───────────────────────────────────────────
//
// The textproto path threads its depth through `TextEncoder`, which is passed
// down the whole cycle. The JSON path cannot: `serde::Serializer` carries no
// user state, and the registry hop is a bare `fn(&[u8]) -> Value` pointer. So
// JSON needs ambient depth, scoped the same way `json::with_json_parse_options`
// scopes its own: thread-local under `std`, a single global under `no_std`.

#[cfg(all(feature = "json", feature = "std"))]
mod any_depth {
    use core::cell::Cell;
    std::thread_local! {
        static DEPTH: Cell<u32> = const { Cell::new(0) };
    }
    /// Increment and return `true`, or return `false` if already at `cap`.
    pub(crate) fn enter(cap: u32) -> bool {
        DEPTH.with(|c| {
            let cur = c.get();
            if cur >= cap {
                return false;
            }
            c.set(cur + 1);
            true
        })
    }
    pub(crate) fn leave() {
        DEPTH.with(|c| c.set(c.get().saturating_sub(1)));
    }
}

#[cfg(all(feature = "json", not(feature = "std")))]
mod any_depth {
    use core::sync::atomic::{AtomicU32, Ordering};
    // `no_std` has no thread-local storage, so the counter is process-wide.
    // The compare-exchange makes it a true increment/decrement pair rather
    // than a snapshot-and-restore: threads sharing the counter can only ever
    // over-count, so the bound may reject a legal document early on a
    // multi-threaded `no_std` host but can never admit an unbounded one. A
    // snapshot-and-restore would fail the other way — a shallow thread
    // writing its stale low value back would let a deep chain run past the
    // cap — which is why this is not simply `set(prev)`.
    static DEPTH: AtomicU32 = AtomicU32::new(0);
    pub(crate) fn enter(cap: u32) -> bool {
        let mut cur = DEPTH.load(Ordering::Relaxed);
        loop {
            if cur >= cap {
                return false;
            }
            match DEPTH.compare_exchange_weak(cur, cur + 1, Ordering::Relaxed, Ordering::Relaxed) {
                Ok(_) => return true,
                Err(actual) => cur = actual,
            }
        }
    }
    pub(crate) fn leave() {
        // Balanced by RAII, so this cannot underflow; saturate rather than
        // wrap if it somehow does, since a wrapped counter would disable the
        // bound entirely.
        let _ = DEPTH.fetch_update(Ordering::Relaxed, Ordering::Relaxed, |v| {
            Some(v.saturating_sub(1))
        });
    }
}

/// Scope guard that releases one level of `Any` expansion depth on drop,
/// including when the serializer returns early with an error.
#[cfg(feature = "json")]
#[doc(hidden)]
#[derive(Debug)]
pub struct AnyExpansionGuard(());

#[cfg(feature = "json")]
impl Drop for AnyExpansionGuard {
    fn drop(&mut self) {
        any_depth::leave();
    }
}

/// Enter one level of `Any` JSON expansion, or return `None` at the cap.
///
/// Hold the returned guard for the duration of the nested serialization. A
/// `None` return means the caller should refuse rather than recurse — see
/// [`MAX_ANY_EXPANSION_DEPTH`] for why the decoder's recursion limit does not
/// already cover this.
///
/// `#[doc(hidden)]` — support for the hand-written `Any` impls in
/// `buffa-types`, not public API.
#[cfg(feature = "json")]
#[doc(hidden)]
#[must_use]
pub fn enter_any_expansion() -> Option<AnyExpansionGuard> {
    any_depth::enter(MAX_ANY_EXPANSION_DEPTH).then_some(AnyExpansionGuard(()))
}

// A cap this high stops bounding anything: 100 levels of expansion is already
// two orders of magnitude past any legitimate `Any` nesting, and the whole
// point of the constant is that the stack cost stays bounded.
const _: () = assert!(MAX_ANY_EXPANSION_DEPTH <= 128);

// ── JSON re-exports ────────────────────────────────────────────────────────

#[cfg(feature = "json")]
pub use crate::any_registry::JsonAnyEntry;
#[cfg(feature = "json")]
pub use crate::extension_registry::JsonExtEntry;

/// Deprecated alias for [`JsonAnyEntry`]. Retained for one release cycle.
#[cfg(feature = "json")]
#[deprecated(since = "0.3.0", note = "renamed to JsonAnyEntry")]
pub type AnyTypeEntry = JsonAnyEntry;

/// Deprecated alias for [`JsonExtEntry`]. Retained for one release cycle.
#[cfg(feature = "json")]
#[deprecated(since = "0.3.0", note = "renamed to JsonExtEntry")]
pub type ExtensionRegistryEntry = JsonExtEntry;

// ── TextAnyEntry ───────────────────────────────────────────────────────────

/// Registry entry for a single message type's textproto ↔ `Any` conversion.
///
/// Carries fn-ptrs for the `[type_url] { ... }` expanded form. Unlike the
/// pre-split unified entry, these are non-`Option` — presence in the map
/// means the type has text-format support.
#[cfg(feature = "text")]
pub struct TextAnyEntry {
    /// Full type URL (e.g. `"type.googleapis.com/google.protobuf.Duration"`).
    pub type_url: &'static str,

    /// `Any.value` bytes → textproto body: decode, write fields as `{ ... }`.
    /// Does not write the `[type_url]` name — the encoder does that.
    pub text_encode: fn(&[u8], &mut crate::text::TextEncoder<'_>) -> core::fmt::Result,

    /// Textproto `{ ... }` body → `Any.value` bytes: merge into a fresh
    /// instance, re-encode to wire bytes.
    pub text_merge: AnyTextMergeFn,
}

#[cfg(feature = "text")]
impl core::fmt::Debug for TextAnyEntry {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        f.debug_struct("TextAnyEntry")
            .field("type_url", &self.type_url)
            .finish_non_exhaustive()
    }
}

/// `TextAnyEntry::text_merge` fn-pointer type (factored out for clippy's
/// `type_complexity`).
#[cfg(feature = "text")]
pub type AnyTextMergeFn =
    fn(&mut crate::text::TextDecoder<'_>) -> Result<alloc::vec::Vec<u8>, crate::text::ParseError>;

// ── TextExtEntry ───────────────────────────────────────────────────────────

/// Registry entry for a single extension field's textproto conversion.
///
/// Carries fn-ptrs for the `[pkg.ext] { ... }` bracket syntax. Covers
/// message- and group-typed extensions (the conformance-exercised forms).
#[cfg(feature = "text")]
pub struct TextExtEntry {
    /// Field number on the extendee.
    pub number: u32,
    /// Fully-qualified proto name. Emitted as `[<this>]`.
    pub full_name: &'static str,
    /// Fully-qualified extendee message name (no leading dot). Checked on
    /// decode; a mismatch is a contract violation and fails the parse.
    pub extendee: &'static str,
    /// Extract this extension's value from unknown fields and write it.
    /// Does not write the `[full_name]` name — the encoder does that.
    pub text_encode: fn(
        u32,
        &crate::unknown_fields::UnknownFields,
        &mut crate::text::TextEncoder<'_>,
    ) -> core::fmt::Result,
    /// Consume a value and produce unknown-field records.
    pub text_merge: ExtTextMergeFn,
}

#[cfg(feature = "text")]
impl core::fmt::Debug for TextExtEntry {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        f.debug_struct("TextExtEntry")
            .field("number", &self.number)
            .field("full_name", &self.full_name)
            .field("extendee", &self.extendee)
            .finish_non_exhaustive()
    }
}

/// `TextExtEntry::text_merge` fn-pointer type.
#[cfg(feature = "text")]
pub type ExtTextMergeFn =
    fn(
        &mut crate::text::TextDecoder<'_>,
        u32,
    )
        -> Result<alloc::vec::Vec<crate::unknown_fields::UnknownField>, crate::text::ParseError>;

// ── Text-side inner maps ───────────────────────────────────────────────────

#[cfg(feature = "text")]
#[derive(Default)]
struct TextAnyMap {
    entries: hashbrown::HashMap<alloc::string::String, TextAnyEntry>,
}

#[cfg(feature = "text")]
impl TextAnyMap {
    fn lookup(&self, type_url: &str) -> Option<&TextAnyEntry> {
        self.entries.get(type_url)
    }
}

#[cfg(feature = "text")]
#[derive(Default)]
struct TextExtMap {
    by_number: hashbrown::HashMap<&'static str, hashbrown::HashMap<u32, TextExtEntry>>,
    by_name: hashbrown::HashMap<&'static str, (&'static str, u32)>,
}

#[cfg(feature = "text")]
impl TextExtMap {
    fn register(&mut self, entry: TextExtEntry) {
        let extendee = entry.extendee;
        let number = entry.number;

        if let Some(previous) = self
            .by_number
            .get_mut(extendee)
            .and_then(|entries| entries.remove(&number))
        {
            self.by_name.remove(previous.full_name);
        }
        if let Some((previous_extendee, previous_number)) = self.by_name.remove(entry.full_name) {
            if let Some(entries) = self.by_number.get_mut(previous_extendee) {
                entries.remove(&previous_number);
            }
        }

        self.by_name.insert(entry.full_name, (extendee, number));
        self.by_number
            .entry(extendee)
            .or_default()
            .insert(number, entry);
    }

    fn by_number(&self, extendee: &str, number: u32) -> Option<&TextExtEntry> {
        self.by_number.get(extendee)?.get(&number)
    }
    fn by_name(&self, full_name: &str) -> Option<&TextExtEntry> {
        let key = self.by_name.get(full_name)?;
        self.by_number.get(key.0)?.get(&key.1)
    }
}

// ── TypeRegistry ───────────────────────────────────────────────────────────

/// Unified registry: JSON `Any` + extension entries (under `json`) and
/// text `Any` + extension entries (under `text`).
///
/// Populate with generated `register_types(&mut reg)` functions, then
/// install once with [`set_type_registry`]. The JSON half delegates to the
/// existing [`AnyRegistry`](crate::any_registry::AnyRegistry) and
/// [`ExtensionRegistry`](crate::extension_registry::ExtensionRegistry) types;
/// the text half uses parallel maps. Both axes' lookup indirection
/// (`by_name` → `by_number`) is preserved.
#[derive(Default)]
pub struct TypeRegistry {
    #[cfg(feature = "json")]
    json_any: crate::any_registry::AnyRegistry,
    #[cfg(feature = "json")]
    json_ext: crate::extension_registry::ExtensionRegistry,
    #[cfg(feature = "text")]
    text_any: TextAnyMap,
    #[cfg(feature = "text")]
    text_ext: TextExtMap,
}

impl TypeRegistry {
    /// Creates an empty registry.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Registers a JSON `Any` type entry. Replaces any existing entry for
    /// the same type URL.
    #[cfg(feature = "json")]
    pub fn register_json_any(&mut self, entry: JsonAnyEntry) {
        self.json_any.register(entry);
    }

    /// Registers a JSON extension entry. Replaces any existing entry at the
    /// same `(extendee, number)` or `full_name`.
    #[cfg(feature = "json")]
    pub fn register_json_ext(&mut self, entry: JsonExtEntry) {
        self.json_ext.register(entry);
    }

    /// Registers a text `Any` type entry.
    #[cfg(feature = "text")]
    pub fn register_text_any(&mut self, entry: TextAnyEntry) {
        use alloc::borrow::ToOwned;
        self.text_any
            .entries
            .insert(entry.type_url.to_owned(), entry);
    }

    /// Registers a text extension entry. Replaces any existing entry at the
    /// same `(extendee, number)` or `full_name`.
    #[cfg(feature = "text")]
    pub fn register_text_ext(&mut self, entry: TextExtEntry) {
        self.text_ext.register(entry);
    }

    /// Look up a JSON `Any` entry by type URL.
    #[cfg(feature = "json")]
    pub fn json_any_by_url(&self, type_url: &str) -> Option<&JsonAnyEntry> {
        self.json_any.lookup(type_url)
    }

    /// Look up a JSON extension entry by `(extendee, number)`.
    #[cfg(feature = "json")]
    pub fn json_ext_by_number(&self, extendee: &str, number: u32) -> Option<&JsonExtEntry> {
        self.json_ext.by_number(extendee, number)
    }

    /// Look up a JSON extension entry by full name.
    #[cfg(feature = "json")]
    pub fn json_ext_by_name(&self, full_name: &str) -> Option<&JsonExtEntry> {
        self.json_ext.by_name(full_name)
    }

    /// Look up a text `Any` entry by type URL.
    #[cfg(feature = "text")]
    pub fn text_any_by_url(&self, type_url: &str) -> Option<&TextAnyEntry> {
        self.text_any.lookup(type_url)
    }

    /// Look up a text extension entry by `(extendee, number)`.
    #[cfg(feature = "text")]
    pub fn text_ext_by_number(&self, extendee: &str, number: u32) -> Option<&TextExtEntry> {
        self.text_ext.by_number(extendee, number)
    }

    /// Look up a text extension entry by full name.
    #[cfg(feature = "text")]
    pub fn text_ext_by_name(&self, full_name: &str) -> Option<&TextExtEntry> {
        self.text_ext.by_name(full_name)
    }
}

/// Deprecated alias for [`TypeRegistry`]. The registry now covers both JSON
/// and text formats.
#[deprecated(since = "0.3.0", note = "renamed to TypeRegistry")]
pub type JsonRegistry = TypeRegistry;

impl core::fmt::Debug for TypeRegistry {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        f.debug_struct("TypeRegistry").finish_non_exhaustive()
    }
}

// ── Global install ─────────────────────────────────────────────────────────

#[cfg(feature = "text")]
static TEXT_ANY: core::sync::atomic::AtomicPtr<TextAnyMap> =
    core::sync::atomic::AtomicPtr::new(core::ptr::null_mut());

#[cfg(feature = "text")]
static TEXT_EXT: core::sync::atomic::AtomicPtr<TextExtMap> =
    core::sync::atomic::AtomicPtr::new(core::ptr::null_mut());

/// Install the global type registry.
///
/// Decomposes into separate installs per format:
/// - Under `json`: delegates to the existing [`AnyRegistry`] and
///   [`ExtensionRegistry`] `AtomicPtr` globals, which generated serde impls
///   and `Any`'s serde impl consult directly.
/// - Under `text`: installs parallel text-only maps consulted by
///   [`TextEncoder::try_write_any_expanded`] / [`TextDecoder::read_any_expansion`]
///   and the extension bracket methods.
///
/// Call once at startup, before any serialization involving `Any` fields or
/// extension fields. All halves are leaked (live for the program lifetime);
/// subsequent calls leak the old allocations — same rationale as the
/// pre-existing `set_any_registry`: avoids use-after-free races with
/// concurrent readers.
///
/// [`AnyRegistry`]: crate::any_registry::AnyRegistry
/// [`ExtensionRegistry`]: crate::extension_registry::ExtensionRegistry
/// [`TextEncoder::try_write_any_expanded`]: crate::text::TextEncoder::try_write_any_expanded
/// [`TextDecoder::read_any_expansion`]: crate::text::TextDecoder::read_any_expansion
pub fn set_type_registry(reg: TypeRegistry) {
    // Destructure once, with each binding cfg'd to match its field. This is
    // the ergonomic form of per-feature field extraction — the binding only
    // exists when the field does.
    let TypeRegistry {
        #[cfg(feature = "json")]
        json_any,
        #[cfg(feature = "json")]
        json_ext,
        #[cfg(feature = "text")]
        text_any,
        #[cfg(feature = "text")]
        text_ext,
    } = reg;

    #[cfg(feature = "json")]
    #[allow(deprecated)]
    {
        crate::any_registry::set_any_registry(Box::new(json_any));
        crate::extension_registry::set_extension_registry(Box::new(json_ext));
    }

    #[cfg(feature = "text")]
    {
        use core::sync::atomic::Ordering;
        TEXT_ANY.swap(Box::into_raw(Box::new(text_any)), Ordering::Release);
        TEXT_EXT.swap(Box::into_raw(Box::new(text_ext)), Ordering::Release);
    }
}

/// Deprecated: call [`set_type_registry`]. This alias exists for one release
/// cycle to ease migration; the registry now covers text entries too.
#[deprecated(since = "0.3.0", note = "renamed to set_type_registry")]
pub fn set_json_registry(reg: TypeRegistry) {
    set_type_registry(reg);
}

// ── Text global lookup (consulted by text encoder/decoder) ─────────────────

/// Look up a text `Any` entry in the global registry. Returns `None` if no
/// registry is installed or the URL is not registered.
#[cfg(feature = "text")]
pub(crate) fn global_text_any(type_url: &str) -> Option<&'static TextAnyEntry> {
    use core::sync::atomic::Ordering;
    let ptr = TEXT_ANY.load(Ordering::Acquire);
    if ptr.is_null() {
        return None;
    }
    // SAFETY: ptr came from Box::into_raw in set_type_registry and is never
    // freed. Acquire synchronizes with the Release store.
    unsafe { &*ptr }.lookup(type_url)
}

/// Look up a text extension entry by `(extendee, number)` in the global registry.
#[cfg(feature = "text")]
pub(crate) fn global_text_ext_by_number(
    extendee: &str,
    number: u32,
) -> Option<&'static TextExtEntry> {
    use core::sync::atomic::Ordering;
    let ptr = TEXT_EXT.load(Ordering::Acquire);
    if ptr.is_null() {
        return None;
    }
    // SAFETY: see global_text_any.
    unsafe { &*ptr }.by_number(extendee, number)
}

/// Look up a text extension entry by full name in the global registry.
#[cfg(feature = "text")]
pub(crate) fn global_text_ext_by_name(full_name: &str) -> Option<&'static TextExtEntry> {
    use core::sync::atomic::Ordering;
    let ptr = TEXT_EXT.load(Ordering::Acquire);
    if ptr.is_null() {
        return None;
    }
    // SAFETY: see global_text_any.
    unsafe { &*ptr }.by_name(full_name)
}

/// Clear the global text maps. Test cleanup only; leaks old allocations.
#[cfg(feature = "text")]
#[doc(hidden)]
pub fn clear_text_registry() {
    use core::sync::atomic::Ordering;
    TEXT_ANY.swap(core::ptr::null_mut(), Ordering::Release);
    TEXT_EXT.swap(core::ptr::null_mut(), Ordering::Release);
}

// ── JSON Any-entry converters (codegen points JsonAnyEntry fields here) ────
//
// Monomorphized per message type M; the resulting fn items coerce to the
// `fn(&[u8]) -> ...` / `fn(serde_json::Value) -> ...` pointer types on
// JsonAnyEntry. Same pattern as extension_registry::helpers::message_to_json.

/// `Any.value` bytes → JSON: decode `M` from wire bytes, then serialize via
/// `M`'s own `Serialize` impl.
///
/// Codegen emits `to_json: ::buffa::type_registry::any_to_json::<Foo>` in each
/// message's `JsonAnyEntry` const. Not intended for direct use.
#[cfg(feature = "json")]
pub fn any_to_json<M>(bytes: &[u8]) -> Result<serde_json::Value, alloc::string::String>
where
    M: crate::Message + serde::Serialize,
{
    use alloc::format;
    let m = M::decode_from_slice(bytes).map_err(|e| format!("{e}"))?;
    serde_json::to_value(&m).map_err(|e| format!("{e}"))
}

/// JSON → `Any.value` bytes: deserialize `M` via its `Deserialize` impl, then
/// encode to wire bytes.
///
/// Codegen emits `from_json: ::buffa::type_registry::any_from_json::<Foo>` in
/// each message's `JsonAnyEntry` const. Not intended for direct use.
#[cfg(feature = "json")]
pub fn any_from_json<M>(v: serde_json::Value) -> Result<alloc::vec::Vec<u8>, alloc::string::String>
where
    M: crate::Message + for<'de> serde::Deserialize<'de>,
{
    use alloc::format;
    let m: M = serde_json::from_value(v).map_err(|e| format!("{e}"))?;
    m.try_encode_to_vec().map_err(|e| format!("{e}"))
}

// ── Text Any-entry converters (codegen points TextAnyEntry fields here) ────
//
// Mirror `any_to_json<M>`: monomorphized per message type M, the resulting
// fn items coerce to the `fn(...)` pointer types on TextAnyEntry.

/// `Any.value` bytes → textproto: decode `M`, write its fields as a
/// `{ ... }` message body.
///
/// Codegen emits `text_encode: ::buffa::type_registry::any_encode_text::<Foo>`
/// in each message's `TextAnyEntry` const when `generate_text` is on.
#[cfg(feature = "text")]
pub fn any_encode_text<M>(bytes: &[u8], enc: &mut crate::text::TextEncoder<'_>) -> core::fmt::Result
where
    M: crate::Message + crate::text::TextFormat + Default,
{
    // If the stored bytes don't decode (corrupt Any), emit an empty `{}` —
    // best effort in the fmt::Result error model. Round-trip won't be perfect
    // but the output is still syntactically valid textproto.
    //
    // Deliberately not a `debug_assert!`. `Any.value` is a raw `bytes` field
    // that decode never validates, so undecodable content is an ordinary
    // property of untrusted input, not an invariant this library maintains;
    // asserting on it makes a single malformed byte a panic wherever debug
    // assertions are on.
    let m = M::decode_from_slice(bytes).unwrap_or_default();
    enc.write_map_entry(|enc| m.encode_text(enc))
}

/// Textproto `{ ... }` body → `Any.value` bytes: merge into a fresh `M`,
/// re-encode to wire bytes.
///
/// Codegen emits `text_merge: ::buffa::type_registry::any_merge_text::<Foo>`.
#[cfg(feature = "text")]
pub fn any_merge_text<M>(
    dec: &mut crate::text::TextDecoder<'_>,
) -> Result<alloc::vec::Vec<u8>, crate::text::ParseError>
where
    M: crate::Message + crate::text::TextFormat + Default,
{
    let mut m = M::default();
    dec.merge_message(&mut m)?;
    m.try_encode_to_vec().map_err(|_| oversized_message_error())
}

/// Merged-message payload exceeded the 2 GiB protobuf limit
/// ([`MAX_MESSAGE_BYTES`](crate::MAX_MESSAGE_BYTES)) — the re-encode step of
/// a text/JSON converter cannot produce valid wire bytes for it, so the
/// parse surfaces an error rather than panicking inside a fallible API.
#[cfg(feature = "text")]
fn oversized_message_error() -> crate::text::ParseError {
    crate::text::ParseError::new(
        0,
        0,
        crate::text::ParseErrorKind::Internal("merged message exceeds the 2 GiB protobuf limit"),
    )
}

// ── Text extension converters (codegen points TextExtEntry fields here) ────
//
// Conformance only exercises `[pkg.ext] { ... }` for message/group-typed
// extensions. Scalar text helpers would mirror the JSON ones in
// `extension_registry::helpers`; deferred until a use case appears.

/// Textproto encode for a message-typed extension: decode `M` from the
/// unknown fields (merge semantics), write as a `{ ... }` message body.
#[cfg(feature = "text")]
pub fn message_encode_text<M>(
    n: u32,
    f: &crate::unknown_fields::UnknownFields,
    enc: &mut crate::text::TextEncoder<'_>,
) -> core::fmt::Result
where
    M: crate::Message + crate::text::TextFormat + Default,
{
    use crate::extension::codecs::MessageCodec;
    use crate::extension::ExtensionCodec;
    let m = MessageCodec::<M>::decode(n, f).unwrap_or_default();
    enc.write_map_entry(|enc| m.encode_text(enc))
}

/// Textproto merge for a message-typed extension: consume `{ ... }`,
/// re-encode to a `LengthDelimited` unknown-field record.
#[cfg(feature = "text")]
pub fn message_merge_text<M>(
    dec: &mut crate::text::TextDecoder<'_>,
    n: u32,
) -> Result<alloc::vec::Vec<crate::unknown_fields::UnknownField>, crate::text::ParseError>
where
    M: crate::Message + crate::text::TextFormat + Default,
{
    use crate::unknown_fields::{UnknownField, UnknownFieldData};
    let mut m = M::default();
    dec.merge_message(&mut m)?;
    let bytes = m
        .try_encode_to_vec()
        .map_err(|_| oversized_message_error())?;
    Ok(alloc::vec![UnknownField {
        number: n,
        data: UnknownFieldData::LengthDelimited(bytes),
    }])
}

/// Textproto encode for a group-encoded extension. Identical body to
/// [`message_encode_text`] on the encode side — only the wire-type of
/// the stored unknown field differs (`Group` vs `LengthDelimited`).
#[cfg(feature = "text")]
pub fn group_encode_text<M>(
    n: u32,
    f: &crate::unknown_fields::UnknownFields,
    enc: &mut crate::text::TextEncoder<'_>,
) -> core::fmt::Result
where
    M: crate::Message + crate::text::TextFormat + Default,
{
    use crate::extension::codecs::GroupCodec;
    use crate::extension::ExtensionCodec;
    let m = GroupCodec::<M>::decode(n, f).unwrap_or_default();
    enc.write_map_entry(|enc| m.encode_text(enc))
}

/// Textproto merge for a group-encoded extension: consume `{ ... }`,
/// re-encode the message's fields into a `Group(UnknownFields)` record.
///
/// Same round-trip-through-bytes as [`GroupCodec::encode`]: encode `M`
/// to wire bytes, re-parse as `UnknownFields`, wrap in `Group`. The
/// inner `UnknownFields` then serialize as `SGROUP … EGROUP` on binary
/// output.
///
/// [`GroupCodec::encode`]: crate::extension::codecs::GroupCodec
#[cfg(feature = "text")]
pub fn group_merge_text<M>(
    dec: &mut crate::text::TextDecoder<'_>,
    n: u32,
) -> Result<alloc::vec::Vec<crate::unknown_fields::UnknownField>, crate::text::ParseError>
where
    M: crate::Message + crate::text::TextFormat + Default,
{
    use crate::unknown_fields::{UnknownField, UnknownFieldData, UnknownFields};
    let mut m = M::default();
    dec.merge_message(&mut m)?;
    let bytes = m
        .try_encode_to_vec()
        .map_err(|_| oversized_message_error())?;
    // Freshly-encoded → re-decode cannot fail short of an encoder bug.
    // Surface as Internal rather than panicking so a library caller
    // isn't taken down by it.
    let inner = UnknownFields::decode_from_slice(&bytes).map_err(|_| {
        crate::text::ParseError::new(
            0,
            0,
            crate::text::ParseErrorKind::Internal(
                "re-decoding freshly-encoded group message bytes failed",
            ),
        )
    })?;
    Ok(alloc::vec![UnknownField {
        number: n,
        data: UnknownFieldData::Group(inner),
    }])
}

// ── Tests ──────────────────────────────────────────────────────────────────

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn default_is_empty() {
        let reg = TypeRegistry::default();
        #[cfg(feature = "json")]
        assert!(reg.json_any_by_url("anything").is_none());
        #[cfg(feature = "text")]
        assert!(reg.text_any_by_url("anything").is_none());
        #[cfg(not(any(feature = "json", feature = "text")))]
        let _ = reg;
    }

    #[test]
    fn debug_impl() {
        let reg = TypeRegistry::new();
        let s = alloc::format!("{reg:?}");
        assert!(s.contains("TypeRegistry"), "{s}");
    }

    // ── JSON half ───────────────────────────────────────────────────────────

    #[cfg(feature = "json")]
    mod json {
        use super::*;
        use crate::any_registry::with_any_registry;
        use crate::extension_registry::{extension_registry, helpers};

        fn dummy_to_json(_: &[u8]) -> Result<serde_json::Value, alloc::string::String> {
            Ok(serde_json::json!({"ok": true}))
        }
        fn dummy_from_json(
            _: serde_json::Value,
        ) -> Result<alloc::vec::Vec<u8>, alloc::string::String> {
            Ok(alloc::vec![1, 2, 3])
        }

        fn any_entry(url: &'static str, wkt: bool) -> JsonAnyEntry {
            JsonAnyEntry {
                type_url: url,
                to_json: dummy_to_json,
                from_json: dummy_from_json,
                is_wkt: wkt,
            }
        }

        fn ext_entry(num: u32, name: &'static str, ext: &'static str) -> JsonExtEntry {
            JsonExtEntry {
                number: num,
                full_name: name,
                extendee: ext,
                to_json: helpers::int32_to_json,
                from_json: helpers::int32_from_json,
            }
        }

        #[test]
        fn register_json_any_and_ext_independently() {
            let mut reg = TypeRegistry::new();
            reg.register_json_any(any_entry("type.googleapis.com/test.Foo", false));
            reg.register_json_ext(ext_entry(100, "test.ext", "test.Foo"));

            assert!(reg
                .json_any_by_url("type.googleapis.com/test.Foo")
                .is_some());
            assert!(reg.json_ext_by_number("test.Foo", 100).is_some());
            assert!(reg.json_ext_by_name("test.ext").is_some());
        }

        /// Serializes this test with the global-registry tests in `any_registry`
        /// and `extension_registry` — all three modules share the same two
        /// `AtomicPtr` globals.
        static GLOBAL_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());

        #[test]
        fn set_type_registry_installs_json_halves() {
            let _g = GLOBAL_LOCK.lock().unwrap();

            let mut reg = TypeRegistry::new();
            reg.register_json_any(any_entry("type.googleapis.com/test.Unified", false));
            reg.register_json_ext(ext_entry(200, "test.unified_ext", "test.Unified"));
            set_type_registry(reg);

            with_any_registry(|r| {
                let r = r.expect("any registry installed");
                assert!(r.lookup("type.googleapis.com/test.Unified").is_some());
            });
            let ext = extension_registry().expect("extension registry installed");
            assert_eq!(ext.by_name("test.unified_ext").map(|e| e.number), Some(200));

            crate::any_registry::clear_any_registry();
        }

        #[test]
        #[allow(deprecated)]
        fn deprecated_aliases_compile() {
            // Type aliases resolve to the new types.
            let _: AnyTypeEntry = any_entry("x", false);
            let _: ExtensionRegistryEntry = ext_entry(1, "a", "B");
            let _: JsonRegistry = TypeRegistry::new();
            // Deprecated fn redirects.
            let _g = GLOBAL_LOCK.lock().unwrap();
            set_json_registry(TypeRegistry::new());
            crate::any_registry::clear_any_registry();
        }
    }

    // ── Text half ───────────────────────────────────────────────────────────

    #[cfg(feature = "text")]
    mod text {
        use super::*;
        use crate::unknown_fields::{UnknownField, UnknownFieldData, UnknownFields};

        // Hand-implemented Message + TextFormat to avoid depending on codegen
        // (mirrors the TestMsg pattern in text/decoder.rs tests).

        #[derive(Default, Clone, PartialEq, Debug)]
        struct Inner {
            n: i32,
        }

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

        impl crate::Message for Inner {
            fn compute_size(&self, _cache: &mut crate::SizeCache) -> u32 {
                if self.n != 0 {
                    1 + crate::encoding::varint_len(self.n as i64 as u64) as u32
                } else {
                    0
                }
            }
            fn write_to(&self, _cache: &mut crate::SizeCache, buf: &mut impl crate::EncodeSink) {
                if self.n != 0 {
                    crate::encoding::Tag::new(1, crate::encoding::WireType::Varint).encode(buf);
                    crate::encoding::encode_varint(self.n as i64 as u64, buf);
                }
            }
            fn merge_field(
                &mut self,
                tag: crate::encoding::Tag,
                buf: &mut impl bytes::Buf,
                _: crate::DecodeContext<'_>,
            ) -> Result<(), crate::DecodeError> {
                if tag.field_number() == 1 && tag.wire_type() == crate::encoding::WireType::Varint {
                    self.n = crate::encoding::decode_varint(buf)? as i32;
                    Ok(())
                } else {
                    crate::encoding::skip_field(tag, buf)
                }
            }
            fn clear(&mut self) {
                self.n = 0;
            }
        }

        impl crate::text::TextFormat for Inner {
            fn encode_text(&self, enc: &mut crate::text::TextEncoder<'_>) -> core::fmt::Result {
                if self.n != 0 {
                    enc.write_field_name("n")?;
                    enc.write_i32(self.n)?;
                }
                Ok(())
            }
            fn merge_text(
                &mut self,
                dec: &mut crate::text::TextDecoder<'_>,
            ) -> Result<(), crate::text::ParseError> {
                while let Some(name) = dec.read_field_name()? {
                    match name {
                        "n" => self.n = dec.read_i32()?,
                        _ => dec.skip_value()?,
                    }
                }
                Ok(())
            }
        }

        fn fields_from(records: alloc::vec::Vec<UnknownField>) -> UnknownFields {
            let mut f = UnknownFields::new();
            for r in records {
                f.push(r);
            }
            f
        }

        #[test]
        fn message_text_roundtrip() {
            let mut dec = crate::text::TextDecoder::new("f { n: 7 }");
            dec.read_field_name().unwrap();
            let records = message_merge_text::<Inner>(&mut dec, 50).unwrap();
            assert_eq!(records.len(), 1);
            assert_eq!(records[0].number, 50);
            let UnknownFieldData::LengthDelimited(ref bytes) = records[0].data else {
                panic!("expected LengthDelimited, got {:?}", records[0].data);
            };
            assert_eq!(*bytes, alloc::vec![0x08, 0x07]);

            let fields = fields_from(records);
            let mut s = alloc::string::String::new();
            let mut enc = crate::text::TextEncoder::new(&mut s);
            enc.write_extension_name("pkg.ext").unwrap();
            message_encode_text::<Inner>(50, &fields, &mut enc).unwrap();
            assert_eq!(s, "[pkg.ext] {n: 7}");
        }

        #[test]
        fn group_text_roundtrip() {
            let mut dec = crate::text::TextDecoder::new("f { n: 7 }");
            dec.read_field_name().unwrap();
            let records = group_merge_text::<Inner>(&mut dec, 121).unwrap();
            assert_eq!(records.len(), 1);
            assert_eq!(records[0].number, 121);
            let UnknownFieldData::Group(ref inner) = records[0].data else {
                panic!("expected Group, got {:?}", records[0].data);
            };
            let inner_vec: alloc::vec::Vec<_> = inner.iter().collect();
            assert_eq!(inner_vec.len(), 1);
            assert_eq!(inner_vec[0].number, 1);
            assert_eq!(inner_vec[0].data, UnknownFieldData::Varint(7));

            let fields = fields_from(records);
            let mut s = alloc::string::String::new();
            let mut enc = crate::text::TextEncoder::new(&mut s);
            enc.write_extension_name("pkg.groupfield").unwrap();
            group_encode_text::<Inner>(121, &fields, &mut enc).unwrap();
            assert_eq!(s, "[pkg.groupfield] {n: 7}");
        }

        #[test]
        fn helpers_satisfy_fn_pointer_signature() {
            // Codegen relies on the monomorphized helpers coercing to the
            // registry's fn-pointer types.
            let _: fn(&[u8], &mut crate::text::TextEncoder<'_>) -> core::fmt::Result =
                any_encode_text::<Inner>;
            let _: AnyTextMergeFn = any_merge_text::<Inner>;
            let _: fn(u32, &UnknownFields, &mut crate::text::TextEncoder<'_>) -> core::fmt::Result =
                message_encode_text::<Inner>;
            let _: ExtTextMergeFn = message_merge_text::<Inner>;
            let _: fn(u32, &UnknownFields, &mut crate::text::TextEncoder<'_>) -> core::fmt::Result =
                group_encode_text::<Inner>;
            let _: ExtTextMergeFn = group_merge_text::<Inner>;
        }

        #[test]
        fn register_and_lookup_text_any() {
            let mut reg = TypeRegistry::new();
            reg.register_text_any(TextAnyEntry {
                type_url: "type.example.com/Inner",
                text_encode: any_encode_text::<Inner>,
                text_merge: any_merge_text::<Inner>,
            });
            assert!(reg.text_any_by_url("type.example.com/Inner").is_some());
            assert!(reg.text_any_by_url("type.example.com/Missing").is_none());
        }

        #[test]
        fn register_and_lookup_text_ext_both_axes() {
            let mut reg = TypeRegistry::new();
            reg.register_text_ext(TextExtEntry {
                number: 50,
                full_name: "pkg.inner_ext",
                extendee: "pkg.Carrier",
                text_encode: message_encode_text::<Inner>,
                text_merge: message_merge_text::<Inner>,
            });
            // by_number axis.
            let e = reg.text_ext_by_number("pkg.Carrier", 50).unwrap();
            assert_eq!(e.full_name, "pkg.inner_ext");
            assert!(reg.text_ext_by_number("pkg.Carrier", 99).is_none());
            assert!(reg.text_ext_by_number("other.Msg", 50).is_none());
            // by_name axis → same entry via indirection.
            assert_eq!(reg.text_ext_by_name("pkg.inner_ext").unwrap().number, 50);
            assert!(reg.text_ext_by_name("pkg.missing").is_none());
        }

        #[test]
        fn text_ext_replacement_evicts_both_conflicting_entries() {
            let mut reg = TypeRegistry::new();
            let make_entry = |number, full_name| TextExtEntry {
                number,
                full_name,
                extendee: "pkg.Carrier",
                text_encode: message_encode_text::<Inner>,
                text_merge: message_merge_text::<Inner>,
            };

            reg.register_text_ext(make_entry(50, "pkg.old"));
            reg.register_text_ext(make_entry(51, "pkg.new"));
            reg.register_text_ext(make_entry(50, "pkg.new"));

            assert!(reg.text_ext_by_name("pkg.old").is_none());
            assert_eq!(reg.text_ext_by_name("pkg.new").unwrap().number, 50);
            assert_eq!(
                reg.text_ext_by_number("pkg.Carrier", 50).unwrap().full_name,
                "pkg.new"
            );
            assert!(reg.text_ext_by_number("pkg.Carrier", 51).is_none());
        }

        #[test]
        fn text_ext_keys_the_same_number_per_extendee() {
            let mut reg = TypeRegistry::new();
            let make_entry = |number, full_name, extendee| TextExtEntry {
                number,
                full_name,
                extendee,
                text_encode: message_encode_text::<Inner>,
                text_merge: message_merge_text::<Inner>,
            };

            reg.register_text_ext(make_entry(50, "pkg.ext", "pkg.Carrier"));
            reg.register_text_ext(make_entry(50, "other.ext", "other.Carrier"));
            assert_eq!(
                reg.text_ext_by_number("pkg.Carrier", 50).unwrap().full_name,
                "pkg.ext"
            );
            assert_eq!(
                reg.text_ext_by_number("other.Carrier", 50)
                    .unwrap()
                    .full_name,
                "other.ext"
            );

            reg.register_text_ext(make_entry(7, "pkg.ext", "other.Carrier"));
            assert!(reg.text_ext_by_number("pkg.Carrier", 50).is_none());
            assert_eq!(
                reg.text_ext_by_number("other.Carrier", 7)
                    .unwrap()
                    .full_name,
                "pkg.ext"
            );
            assert_eq!(
                reg.text_ext_by_name("pkg.ext").unwrap().extendee,
                "other.Carrier"
            );
        }

        /// Serializes with other tests touching the global TEXT_ANY/TEXT_EXT.
        static GLOBAL_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());

        #[test]
        fn set_type_registry_installs_text_halves() {
            let _g = GLOBAL_LOCK.lock().unwrap();

            let mut reg = TypeRegistry::new();
            reg.register_text_any(TextAnyEntry {
                type_url: "type.example.com/Global",
                text_encode: any_encode_text::<Inner>,
                text_merge: any_merge_text::<Inner>,
            });
            reg.register_text_ext(TextExtEntry {
                number: 77,
                full_name: "pkg.global_ext",
                extendee: "pkg.Msg",
                text_encode: message_encode_text::<Inner>,
                text_merge: message_merge_text::<Inner>,
            });
            set_type_registry(reg);

            assert!(global_text_any("type.example.com/Global").is_some());
            assert!(global_text_any("type.example.com/Absent").is_none());
            assert_eq!(
                global_text_ext_by_name("pkg.global_ext").map(|e| e.number),
                Some(77)
            );
            assert!(global_text_ext_by_number("pkg.Msg", 77).is_some());

            clear_text_registry();
            assert!(global_text_any("type.example.com/Global").is_none());
        }
    }
}