reallyme-buffa 0.1.0

ReallyMe fork: 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
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
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
//! 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;

/// Return the protobuf full name carried by an `Any` type URL, for the text
/// registry.
///
/// The `Any` contract identifies the embedded message by the path segment
/// after the final slash; the URL prefix is application-defined. A string
/// without a slash carries no name here: text format writes `[name] { ... }`
/// for an extension field, so only a URL is expanded.
#[cfg(feature = "text")]
fn any_type_name(type_url: &str) -> Option<&str> {
    let (_, type_name) = type_url.rsplit_once('/')?;
    (!type_name.is_empty()).then_some(type_name)
}

/// 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(|| 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"`).
    ///
    /// A URL with no `/` carries no message name, and is found only by an
    /// exact match.
    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, singular and repeated. Scalar and
/// enum extensions have no text entry.
#[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.
    ///
    /// [`TextEncoder::write_extension_fields`] calls this once per extension
    /// number, after it has written `[full_name]`, so the function writes
    /// one value and does not write the name. The repeated helpers
    /// ([`repeated_message_encode_text`], [`repeated_group_encode_text`])
    /// are the exception: for each element after the first they have the
    /// encoder write `[full_name]` again.
    ///
    /// [`TextEncoder::write_extension_fields`]: crate::text::TextEncoder::write_extension_fields
    pub text_encode: fn(
        u32,
        &crate::unknown_fields::UnknownFields,
        &mut crate::text::TextEncoder<'_>,
    ) -> core::fmt::Result,
    /// Consume one value and produce unknown-field records.
    ///
    /// [`TextDecoder::read_extension`] calls this once per `[full_name]`
    /// occurrence in the input. Generated `merge_text` appends the records
    /// of every occurrence to the message's unknown fields.
    ///
    /// [`TextDecoder::read_extension`]: crate::text::TextDecoder::read_extension
    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>,
    /// Message full name → the type URL most recently registered for it.
    by_type_name: hashbrown::HashMap<&'static str, &'static str>,
}

#[cfg(feature = "text")]
impl TextAnyMap {
    fn register(&mut self, entry: TextAnyEntry) {
        if let Some(type_name) = any_type_name(entry.type_url) {
            self.by_type_name.insert(type_name, entry.type_url);
        }
        self.entries
            .insert(alloc::string::String::from(entry.type_url), entry);
    }

    fn lookup(&self, type_url: &str) -> Option<&TextAnyEntry> {
        if let Some(entry) = self.entries.get(type_url) {
            return Some(entry);
        }

        let type_name = any_type_name(type_url)?;
        let registered_url = *self.by_type_name.get(type_name)?;
        self.entries.get(registered_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. When the same
    /// message full name is registered under several URLs, a
    /// [`json_any_by_url`](Self::json_any_by_url) lookup of a URL that is not
    /// itself registered uses the most recently registered one.
    ///
    /// A lookup by name decodes the payload as this message. A payload under
    /// another prefix that does not decode as it fails to serialize as JSON;
    /// one that does decode is written with this message's fields.
    #[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.
    ///
    /// Replaces any existing entry for the same type URL. When the same
    /// message full name is registered under several URLs, a
    /// [`text_any_by_url`](Self::text_any_by_url) lookup of a URL that is not
    /// itself registered uses the most recently registered one.
    ///
    /// A lookup by name decodes the payload as this message. A payload under
    /// another prefix that does not decode as it prints with an empty body;
    /// one that does decode is written with this message's fields.
    #[cfg(feature = "text")]
    pub fn register_text_any(&mut self, entry: TextAnyEntry) {
        self.text_any.register(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.
    ///
    /// A registered URL finds its own entry. Any other URL is matched by the
    /// message full name after its last `/`, and a string without a `/` as a
    /// bare full name. The entry's `type_url` is the registered one, so keep
    /// the URL you looked up as the `Any`'s `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.
    ///
    /// A registered URL finds its own entry. Any other URL is matched by the
    /// message full name after its last `/`. A string without a `/` is found
    /// only by an exact match, unlike in
    /// [`json_any_by_url`](Self::json_any_by_url). The entry's `type_url` is
    /// the registered one, so keep the URL you looked up as the `Any`'s
    /// `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 neither the URL nor its message full name is
/// 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) ────
//
// Message- and group-typed extensions only, singular and repeated. Scalar
// text helpers would mirror the JSON ones in `extension_registry::helpers`;
// deferred until a use case appears.

/// Textproto encode for a repeated message extension: write each element as
/// its own `[full_name] { ... }` entry, in wire order.
///
/// Codegen emits
/// `text_encode: ::buffa::type_registry::repeated_message_encode_text::<Foo>`
/// in the `TextExtEntry` const of a `repeated Foo` extension when
/// `generate_text` is on. A hand-written [`TextExtEntry`] can store it the
/// same way.
///
/// [`TextEncoder::write_extension_fields`] writes `[full_name]` and then
/// calls the entry's `text_encode`. Called that way, this function writes
/// the first element after that name and has the encoder write the name
/// again before each later element.
///
/// Called directly, after a name the caller wrote with
/// [`TextEncoder::write_extension_name`], it writes the elements as one list
/// value, `: [{ ... }, { ... }]`, because the encoder repeats only a name
/// that `write_extension_fields` wrote. [`repeated_message_merge_text`]
/// parses the list; [`message_merge_text`] rejects it.
///
/// A record that does not decode as `M` is skipped, as [`Repeated`] skips
/// it. When every record is skipped the value is the empty list `: []` in
/// both cases, which parses to zero elements.
///
/// # Errors
///
/// Propagates [`core::fmt::Error`] from the underlying writer.
///
/// [`TextEncoder::write_extension_fields`]: crate::text::TextEncoder::write_extension_fields
/// [`TextEncoder::write_extension_name`]: crate::text::TextEncoder::write_extension_name
/// [`Repeated`]: crate::extension::codecs::Repeated
#[cfg(feature = "text")]
pub fn repeated_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, Repeated};
    use crate::extension::ExtensionCodec;
    enc.write_repeated_extension(&Repeated::<MessageCodec<M>>::decode(n, f))
}

/// Textproto encode for a repeated group extension. Writes the same text as
/// [`repeated_message_encode_text`], in the same two forms; the elements are
/// read from `Group` records, and a record of another wire type is skipped.
/// [`repeated_group_merge_text`] parses the list form; [`group_merge_text`]
/// rejects it.
///
/// Codegen emits
/// `text_encode: ::buffa::type_registry::repeated_group_encode_text::<Foo>`
/// in the `TextExtEntry` const of a repeated group-encoded extension when
/// `generate_text` is on.
///
/// # Errors
///
/// Propagates [`core::fmt::Error`] from the underlying writer.
#[cfg(feature = "text")]
pub fn repeated_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, Repeated};
    use crate::extension::ExtensionCodec;
    enc.write_repeated_extension(&Repeated::<GroupCodec<M>>::decode(n, f))
}

/// Textproto merge for a repeated message extension. Accepts a message list
/// or a single message and returns one length-delimited record per element.
///
/// Called once per `[full_name]` occurrence, so `[x] {..} [x] {..}` and
/// `[x]: [{..}, {..}]` yield the same records.
///
/// Codegen emits
/// `text_merge: ::buffa::type_registry::repeated_message_merge_text::<Foo>`
/// in the `TextExtEntry` const of a `repeated Foo` extension when
/// `generate_text` is on.
///
/// # Errors
///
/// Returns a parse error for invalid text, an exceeded decode budget, or a
/// message that exceeds the protobuf encode-size limit.
#[cfg(feature = "text")]
pub fn repeated_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,
{
    let mut records = alloc::vec::Vec::new();
    dec.read_repeated_into(&mut records, |dec| message_record::<M>(dec, n))?;
    Ok(records)
}

/// Textproto merge for a repeated group extension. Reads the same text as
/// [`repeated_message_merge_text`] and returns one `Group` record per
/// element.
///
/// Codegen emits
/// `text_merge: ::buffa::type_registry::repeated_group_merge_text::<Foo>`
/// in the `TextExtEntry` const of a repeated group-encoded extension when
/// `generate_text` is on.
///
/// # Errors
///
/// The same errors as [`repeated_message_merge_text`].
#[cfg(feature = "text")]
pub fn repeated_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,
{
    let mut records = alloc::vec::Vec::new();
    dec.read_repeated_into(&mut records, |dec| group_record::<M>(dec, n))?;
    Ok(records)
}

/// 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,
{
    Ok(alloc::vec![message_record::<M>(dec, n)?])
}

/// Consume one `{ ... }` message and re-encode it to the `LengthDelimited`
/// record of extension `n`.
#[cfg(feature = "text")]
fn message_record<M>(
    dec: &mut crate::text::TextDecoder<'_>,
    n: u32,
) -> Result<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(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,
{
    Ok(alloc::vec![group_record::<M>(dec, n)?])
}

/// Consume one `{ ... }` message and re-encode its fields to the `Group`
/// record of extension `n`.
#[cfg(feature = "text")]
fn group_record<M>(
    dec: &mut crate::text::TextDecoder<'_>,
    n: u32,
) -> Result<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(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}");
    }

    #[cfg(feature = "json")]
    #[test]
    fn refusing_any_expansion_does_not_decrement_active_depth() {
        let _guards: alloc::vec::Vec<_> = (0..MAX_ANY_EXPANSION_DEPTH)
            .map(|_| enter_any_expansion().expect("entry below the cap must succeed"))
            .collect();

        assert!(enter_any_expansion().is_none());
        assert!(enter_any_expansion().is_none());
    }

    // ── 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());
        }

        #[test]
        fn set_type_registry_installs_json_halves() {
            let _g = crate::test_doubles::REGISTRY_TEST_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 = crate::test_doubles::REGISTRY_TEST_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}");
        }

        type RepeatedHelpers = (
            &'static str,
            fn(u32, &UnknownFields, &mut crate::text::TextEncoder<'_>) -> core::fmt::Result,
            ExtTextMergeFn,
        );
        /// Each repeated helper pair as (registered name, encode, merge).
        const REPEATED_HELPERS: [RepeatedHelpers; 2] = [
            (
                "pkg.rep",
                repeated_message_encode_text::<Inner>,
                repeated_message_merge_text::<Inner>,
            ),
            (
                "pkg.rep_group",
                repeated_group_encode_text::<Inner>,
                repeated_group_merge_text::<Inner>,
            ),
        ];

        #[test]
        fn repeated_helpers_write_a_list_after_a_name_the_caller_wrote() {
            for (name, encode, merge) in REPEATED_HELPERS {
                let mut dec = crate::text::TextDecoder::new("f: [{ n: 1 }, { n: 2 }]");
                dec.read_field_name().unwrap();
                let records = merge(&mut dec, 60).unwrap();
                assert_eq!(records.len(), 2, "{name}");

                for (count, expected) in [
                    (0, "[x]: []"),
                    (1, "[x]: [{n: 1}]"),
                    (2, "[x]: [{n: 1}, {n: 2}]"),
                ] {
                    let fields = fields_from(records[..count].to_vec());
                    let mut s = alloc::string::String::new();
                    let mut enc = crate::text::TextEncoder::new(&mut s);
                    enc.write_extension_name("x").unwrap();
                    encode(60, &fields, &mut enc).unwrap();
                    assert_eq!(s, expected, "{name}");
                }

                let fields = fields_from(records);
                let mut s = alloc::string::String::new();
                let mut enc = crate::text::TextEncoder::new_pretty(&mut s);
                enc.write_extension_name("x").unwrap();
                encode(60, &fields, &mut enc).unwrap();
                assert_eq!(s, "[x]: [{\n  n: 1\n}, {\n  n: 2\n}]", "{name}");
            }
        }

        /// Installs a global registry that holds [`REPEATED_HELPERS`] at
        /// numbers 60 and 61 of `pkg.Msg`, and returns three records for
        /// each. `text_merge` is the singular helper, which rejects a
        /// message list: each entry the encoder writes has to hold one
        /// message.
        fn install_repeated_entries() -> alloc::vec::Vec<UnknownField> {
            let singular_merges: [ExtTextMergeFn; 2] =
                [message_merge_text::<Inner>, group_merge_text::<Inner>];
            let mut reg = TypeRegistry::new();
            let mut records = alloc::vec::Vec::new();
            for (number, ((full_name, text_encode, merge), text_merge)) in
                (60..).zip(REPEATED_HELPERS.into_iter().zip(singular_merges))
            {
                reg.register_text_ext(TextExtEntry {
                    number,
                    full_name,
                    extendee: "pkg.Msg",
                    text_encode,
                    text_merge,
                });
                let mut dec = crate::text::TextDecoder::new("f: [{ n: 1 }, {}, { n: 2 }]");
                dec.read_field_name().unwrap();
                records.extend(merge(&mut dec, number).unwrap());
            }
            set_type_registry(reg);
            records
        }

        const REPEATED_ENTRIES: &str = "[pkg.rep] {n: 1} [pkg.rep] {} [pkg.rep] {n: 2} \
            [pkg.rep_group] {n: 1} [pkg.rep_group] {} [pkg.rep_group] {n: 2}";

        #[test]
        fn repeated_entries_parse_with_a_merge_that_reads_one_message() {
            let _g = crate::test_doubles::REGISTRY_TEST_LOCK.lock().unwrap();
            let records = install_repeated_entries();

            let mut s = alloc::string::String::new();
            crate::text::TextEncoder::new(&mut s)
                .write_extension_fields("pkg.Msg", &fields_from(records.clone()))
                .unwrap();
            assert_eq!(s, REPEATED_ENTRIES);

            let mut dec = crate::text::TextDecoder::new(&s);
            let mut reparsed = alloc::vec::Vec::new();
            while let Some(name) = dec.read_field_name().unwrap() {
                reparsed.extend(dec.read_extension(name, "pkg.Msg").unwrap());
            }
            assert_eq!(reparsed, records);

            clear_text_registry();
        }

        #[test]
        fn repeated_helper_does_not_repeat_a_name_from_an_earlier_entry() {
            let _g = crate::test_doubles::REGISTRY_TEST_LOCK.lock().unwrap();
            let fields = fields_from(install_repeated_entries());

            let mut s = alloc::string::String::new();
            let mut enc = crate::text::TextEncoder::new(&mut s);
            enc.write_extension_fields("pkg.Msg", &fields).unwrap();
            enc.write_extension_name("x").unwrap();
            repeated_message_encode_text::<Inner>(60, &fields, &mut enc).unwrap();
            assert_eq!(
                s,
                alloc::format!("{REPEATED_ENTRIES} [x]: [{{n: 1}}, {{}}, {{n: 2}}]")
            );

            clear_text_registry();
        }

        /// Installs a global registry that holds `text_encode` as extension
        /// 60 of `pkg.Msg`, named `pkg.custom`, and returns two records at
        /// that number.
        fn install_custom_entry(
            text_encode: fn(
                u32,
                &UnknownFields,
                &mut crate::text::TextEncoder<'_>,
            ) -> core::fmt::Result,
        ) -> UnknownFields {
            let mut reg = TypeRegistry::new();
            reg.register_text_ext(TextExtEntry {
                number: 60,
                full_name: "pkg.custom",
                extendee: "pkg.Msg",
                text_encode,
                text_merge: repeated_message_merge_text::<Inner>,
            });
            set_type_registry(reg);
            let mut dec = crate::text::TextDecoder::new("f: [{ n: 1 }, { n: 2 }]");
            dec.read_field_name().unwrap();
            fields_from(repeated_message_merge_text::<Inner>(&mut dec, 60).unwrap())
        }

        #[test]
        fn repeated_helper_does_not_repeat_the_name_of_an_entry_that_returned() {
            fn write_no_value(
                _: u32,
                _: &UnknownFields,
                _: &mut crate::text::TextEncoder<'_>,
            ) -> core::fmt::Result {
                Ok(())
            }

            let _g = crate::test_doubles::REGISTRY_TEST_LOCK.lock().unwrap();
            let fields = install_custom_entry(write_no_value);

            let mut s = alloc::string::String::new();
            let mut enc = crate::text::TextEncoder::new(&mut s);
            enc.write_extension_fields("pkg.Msg", &fields).unwrap();
            repeated_message_encode_text::<Inner>(60, &fields, &mut enc).unwrap();
            assert_eq!(s, "[pkg.custom]: [{n: 1}, {n: 2}]");

            clear_text_registry();
        }

        #[test]
        fn repeated_helper_does_not_repeat_a_name_that_already_has_a_value() {
            fn value_then_a_direct_call(
                n: u32,
                f: &UnknownFields,
                enc: &mut crate::text::TextEncoder<'_>,
            ) -> core::fmt::Result {
                message_encode_text::<Inner>(n, f, enc)?;
                enc.write_extension_name("x")?;
                repeated_message_encode_text::<Inner>(n, f, enc)
            }

            let _g = crate::test_doubles::REGISTRY_TEST_LOCK.lock().unwrap();
            let fields = install_custom_entry(value_then_a_direct_call);

            let mut s = alloc::string::String::new();
            crate::text::TextEncoder::new(&mut s)
                .write_extension_fields("pkg.Msg", &fields)
                .unwrap();
            assert_eq!(s, "[pkg.custom] {n: 2} [x]: [{n: 1}, {n: 2}]");

            clear_text_registry();
        }

        #[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("custom.example/v1/Inner").is_some());
            assert!(reg.text_any_by_url("type.example.com/Missing").is_none());
        }

        #[test]
        fn text_any_lookup_falls_back_to_the_last_url_registered_for_a_name() {
            let mut reg = TypeRegistry::new();
            for type_url in ["type.example.com/Inner", "custom.example/v1/Inner"] {
                reg.register_text_any(TextAnyEntry {
                    type_url,
                    text_encode: any_encode_text::<Inner>,
                    text_merge: any_merge_text::<Inner>,
                });
            }
            let found = |url| reg.text_any_by_url(url).map(|entry| entry.type_url);
            assert_eq!(
                found("type.example.com/Inner"),
                Some("type.example.com/Inner")
            );
            assert_eq!(
                found("custom.example/v1/Inner"),
                Some("custom.example/v1/Inner")
            );
            assert_eq!(
                found("other.example/Inner"),
                Some("custom.example/v1/Inner")
            );
        }

        #[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"
            );
        }

        #[test]
        fn set_type_registry_installs_text_halves() {
            let _g = crate::test_doubles::REGISTRY_TEST_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());
        }

        #[test]
        fn bracketed_names_with_trivia_resolve_through_the_registry() {
            let _g = crate::test_doubles::REGISTRY_TEST_LOCK.lock().unwrap();

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

            let input = "[ type.example.com / # ] is comment text\n pkg . Inner ] { n: 7 }";
            let mut dec = crate::text::TextDecoder::new(input);
            let name = dec.read_field_name().unwrap().unwrap();
            let (url, value) = dec.read_any_expansion(name).unwrap();
            assert_eq!(url, "type.example.com/pkg.Inner");
            assert_eq!(value, alloc::vec![0x08, 0x07]);

            let input = "[ pkg . # ] is comment text\n trivia_ext ] { n: 7 }";
            let mut dec = crate::text::TextDecoder::new(input);
            let name = dec.read_field_name().unwrap().unwrap();
            let records = dec.read_extension(name, "pkg.Msg").unwrap();
            assert_eq!(records.len(), 1);
            assert_eq!(records[0].number, 77);

            // Stripping trivia does not make an unregistered name resolve.
            let mut dec = crate::text::TextDecoder::new("[ pkg . other_ext ] { n: 7 }");
            let name = dec.read_field_name().unwrap().unwrap();
            let err = dec.read_extension(name, "pkg.Msg").unwrap_err();
            assert_eq!(err.kind, crate::text::ParseErrorKind::UnknownField);

            clear_text_registry();
        }
    }
}