Skip to main content

buffa/
type_registry.rs

1//! Unified type registry for `Any` expansion and extension brackets — JSON + text.
2//!
3//! `google.protobuf.Any` in both proto3 JSON and textproto needs to know how
4//! to serialize the embedded message by its type URL. Extension fields in
5//! both formats likewise need a lookup by `(extendee, number)` or
6//! `[full_name]`. This module is the single install point for both formats:
7//! populate a [`TypeRegistry`] with generated `register_types(&mut reg)` calls,
8//! then [`set_type_registry`] once at startup.
9//!
10//! The per-format entry types are feature-split so that `json` and `text`
11//! are independently enableable — no `#[cfg]` on struct-literal fields, no
12//! `Option<fn>` placeholders, no cross-feature implication.
13//!
14//! # Usage
15//!
16//! ```rust,no_run
17//! use buffa::type_registry::{TypeRegistry, set_type_registry};
18//!
19//! let mut reg = TypeRegistry::new();
20//! // Per generated file — registers JSON entries (if generate_json was on)
21//! // and text entries (if generate_text was on), as appropriate:
22//! // my_pkg::register_types(&mut reg);
23//! // Well-known types (hand-registered in buffa-types):
24//! // buffa_types::register_wkt_types(&mut reg);
25//! set_type_registry(reg);
26//! ```
27//!
28//! # Codegen helpers
29//!
30//! [`any_to_json`] / [`any_from_json`] (under `json`) and [`any_encode_text`] /
31//! [`any_merge_text`] (under `text`) are generic function pointers emitted by
32//! codegen into each message's entry consts. They compose
33//! `Message::decode_from_slice` / `encode_to_vec` with the message's own
34//! `Serialize`/`Deserialize` or `TextFormat` impl.
35
36use alloc::boxed::Box;
37
38/// Return the protobuf full name carried by an `Any` type URL, for the text
39/// registry.
40///
41/// The `Any` contract identifies the embedded message by the path segment
42/// after the final slash; the URL prefix is application-defined. A string
43/// without a slash carries no name here: text format writes `[name] { ... }`
44/// for an extension field, so only a URL is expanded.
45#[cfg(feature = "text")]
46fn any_type_name(type_url: &str) -> Option<&str> {
47    let (_, type_name) = type_url.rsplit_once('/')?;
48    (!type_name.is_empty()).then_some(type_name)
49}
50
51/// Maximum nesting depth of `google.protobuf.Any` expansions in one
52/// serialization.
53///
54/// `Any` is a flat two-field message (`string type_url`, `bytes value`) whose
55/// nesting lives entirely inside the opaque `value` bytes. A decoder therefore
56/// spends a single [`RECURSION_LIMIT`](crate::RECURSION_LIMIT) level on a chain
57/// of any length — the recursion happens later, when a serializer expands each
58/// level in turn by decoding it and serializing the result. That expansion is
59/// what this bounds.
60///
61/// Set to the same value as [`RECURSION_LIMIT`](crate::RECURSION_LIMIT): both
62/// bound how deeply one message may nest inside another, and one number is
63/// easier to reason about than two. Legitimate `Any` nesting is one or two
64/// levels.
65///
66/// This cap is a constant.
67/// [`DecodeOptions::with_recursion_limit`](crate::DecodeOptions::with_recursion_limit)
68/// does not move it, since it bounds serialization rather than decoding.
69pub const MAX_ANY_EXPANSION_DEPTH: u32 = crate::RECURSION_LIMIT;
70
71// ── Any-expansion depth tracking ───────────────────────────────────────────
72//
73// The textproto path threads its depth through `TextEncoder`, which is passed
74// down the whole cycle. The JSON path cannot: `serde::Serializer` carries no
75// user state, and the registry hop is a bare `fn(&[u8]) -> Value` pointer. So
76// JSON needs ambient depth, scoped the same way `json::with_json_parse_options`
77// scopes its own: thread-local under `std`, a single global under `no_std`.
78
79#[cfg(all(feature = "json", feature = "std"))]
80mod any_depth {
81    use core::cell::Cell;
82    std::thread_local! {
83        static DEPTH: Cell<u32> = const { Cell::new(0) };
84    }
85    /// Increment and return `true`, or return `false` if already at `cap`.
86    pub(crate) fn enter(cap: u32) -> bool {
87        DEPTH.with(|c| {
88            let cur = c.get();
89            if cur >= cap {
90                return false;
91            }
92            c.set(cur + 1);
93            true
94        })
95    }
96    pub(crate) fn leave() {
97        DEPTH.with(|c| c.set(c.get().saturating_sub(1)));
98    }
99}
100
101#[cfg(all(feature = "json", not(feature = "std")))]
102mod any_depth {
103    use core::sync::atomic::{AtomicU32, Ordering};
104    // `no_std` has no thread-local storage, so the counter is process-wide.
105    // The compare-exchange makes it a true increment/decrement pair rather
106    // than a snapshot-and-restore: threads sharing the counter can only ever
107    // over-count, so the bound may reject a legal document early on a
108    // multi-threaded `no_std` host but can never admit an unbounded one. A
109    // snapshot-and-restore would fail the other way — a shallow thread
110    // writing its stale low value back would let a deep chain run past the
111    // cap — which is why this is not simply `set(prev)`.
112    static DEPTH: AtomicU32 = AtomicU32::new(0);
113    pub(crate) fn enter(cap: u32) -> bool {
114        let mut cur = DEPTH.load(Ordering::Relaxed);
115        loop {
116            if cur >= cap {
117                return false;
118            }
119            match DEPTH.compare_exchange_weak(cur, cur + 1, Ordering::Relaxed, Ordering::Relaxed) {
120                Ok(_) => return true,
121                Err(actual) => cur = actual,
122            }
123        }
124    }
125    pub(crate) fn leave() {
126        // Balanced by RAII, so this cannot underflow; saturate rather than
127        // wrap if it somehow does, since a wrapped counter would disable the
128        // bound entirely.
129        let _ = DEPTH.try_update(Ordering::Relaxed, Ordering::Relaxed, |v| {
130            Some(v.saturating_sub(1))
131        });
132    }
133}
134
135/// Scope guard that releases one level of `Any` expansion depth on drop,
136/// including when the serializer returns early with an error.
137#[cfg(feature = "json")]
138#[doc(hidden)]
139#[derive(Debug)]
140pub struct AnyExpansionGuard(());
141
142#[cfg(feature = "json")]
143impl Drop for AnyExpansionGuard {
144    fn drop(&mut self) {
145        any_depth::leave();
146    }
147}
148
149/// Enter one level of `Any` JSON expansion, or return `None` at the cap.
150///
151/// Hold the returned guard for the duration of the nested serialization. A
152/// `None` return means the caller should refuse rather than recurse — see
153/// [`MAX_ANY_EXPANSION_DEPTH`] for why the decoder's recursion limit does not
154/// already cover this.
155///
156/// `#[doc(hidden)]` — support for the hand-written `Any` impls in
157/// `buffa-types`, not public API.
158#[cfg(feature = "json")]
159#[doc(hidden)]
160#[must_use]
161pub fn enter_any_expansion() -> Option<AnyExpansionGuard> {
162    any_depth::enter(MAX_ANY_EXPANSION_DEPTH).then(|| AnyExpansionGuard(()))
163}
164
165// A cap this high stops bounding anything: 100 levels of expansion is already
166// two orders of magnitude past any legitimate `Any` nesting, and the whole
167// point of the constant is that the stack cost stays bounded.
168const _: () = assert!(MAX_ANY_EXPANSION_DEPTH <= 128);
169
170// ── JSON re-exports ────────────────────────────────────────────────────────
171
172#[cfg(feature = "json")]
173pub use crate::any_registry::JsonAnyEntry;
174#[cfg(feature = "json")]
175pub use crate::extension_registry::JsonExtEntry;
176
177/// Deprecated alias for [`JsonAnyEntry`]. Retained for one release cycle.
178#[cfg(feature = "json")]
179#[deprecated(since = "0.3.0", note = "renamed to JsonAnyEntry")]
180pub type AnyTypeEntry = JsonAnyEntry;
181
182/// Deprecated alias for [`JsonExtEntry`]. Retained for one release cycle.
183#[cfg(feature = "json")]
184#[deprecated(since = "0.3.0", note = "renamed to JsonExtEntry")]
185pub type ExtensionRegistryEntry = JsonExtEntry;
186
187// ── TextAnyEntry ───────────────────────────────────────────────────────────
188
189/// Registry entry for a single message type's textproto ↔ `Any` conversion.
190///
191/// Carries fn-ptrs for the `[type_url] { ... }` expanded form. Unlike the
192/// pre-split unified entry, these are non-`Option` — presence in the map
193/// means the type has text-format support.
194#[cfg(feature = "text")]
195pub struct TextAnyEntry {
196    /// Full type URL (e.g. `"type.googleapis.com/google.protobuf.Duration"`).
197    ///
198    /// A URL with no `/` carries no message name, and is found only by an
199    /// exact match.
200    pub type_url: &'static str,
201
202    /// `Any.value` bytes → textproto body: decode, write fields as `{ ... }`.
203    /// Does not write the `[type_url]` name — the encoder does that.
204    pub text_encode: fn(&[u8], &mut crate::text::TextEncoder<'_>) -> core::fmt::Result,
205
206    /// Textproto `{ ... }` body → `Any.value` bytes: merge into a fresh
207    /// instance, re-encode to wire bytes.
208    pub text_merge: AnyTextMergeFn,
209}
210
211#[cfg(feature = "text")]
212impl core::fmt::Debug for TextAnyEntry {
213    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
214        f.debug_struct("TextAnyEntry")
215            .field("type_url", &self.type_url)
216            .finish_non_exhaustive()
217    }
218}
219
220/// `TextAnyEntry::text_merge` fn-pointer type (factored out for clippy's
221/// `type_complexity`).
222#[cfg(feature = "text")]
223pub type AnyTextMergeFn =
224    fn(&mut crate::text::TextDecoder<'_>) -> Result<alloc::vec::Vec<u8>, crate::text::ParseError>;
225
226// ── TextExtEntry ───────────────────────────────────────────────────────────
227
228/// Registry entry for a single extension field's textproto conversion.
229///
230/// Carries fn-ptrs for the `[pkg.ext] { ... }` bracket syntax. Covers
231/// message- and group-typed extensions, singular and repeated. Scalar and
232/// enum extensions have no text entry.
233#[cfg(feature = "text")]
234pub struct TextExtEntry {
235    /// Field number on the extendee.
236    pub number: u32,
237    /// Fully-qualified proto name. Emitted as `[<this>]`.
238    pub full_name: &'static str,
239    /// Fully-qualified extendee message name (no leading dot). Checked on
240    /// decode; a mismatch is a contract violation and fails the parse.
241    pub extendee: &'static str,
242    /// Extract this extension's value from unknown fields and write it.
243    ///
244    /// [`TextEncoder::write_extension_fields`] calls this once per extension
245    /// number, after it has written `[full_name]`, so the function writes
246    /// one value and does not write the name. The repeated helpers
247    /// ([`repeated_message_encode_text`], [`repeated_group_encode_text`])
248    /// are the exception: for each element after the first they have the
249    /// encoder write `[full_name]` again.
250    ///
251    /// [`TextEncoder::write_extension_fields`]: crate::text::TextEncoder::write_extension_fields
252    pub text_encode: fn(
253        u32,
254        &crate::unknown_fields::UnknownFields,
255        &mut crate::text::TextEncoder<'_>,
256    ) -> core::fmt::Result,
257    /// Consume one value and produce unknown-field records.
258    ///
259    /// [`TextDecoder::read_extension`] calls this once per `[full_name]`
260    /// occurrence in the input. Generated `merge_text` appends the records
261    /// of every occurrence to the message's unknown fields.
262    ///
263    /// [`TextDecoder::read_extension`]: crate::text::TextDecoder::read_extension
264    pub text_merge: ExtTextMergeFn,
265}
266
267#[cfg(feature = "text")]
268impl core::fmt::Debug for TextExtEntry {
269    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
270        f.debug_struct("TextExtEntry")
271            .field("number", &self.number)
272            .field("full_name", &self.full_name)
273            .field("extendee", &self.extendee)
274            .finish_non_exhaustive()
275    }
276}
277
278/// `TextExtEntry::text_merge` fn-pointer type.
279#[cfg(feature = "text")]
280pub type ExtTextMergeFn =
281    fn(
282        &mut crate::text::TextDecoder<'_>,
283        u32,
284    )
285        -> Result<alloc::vec::Vec<crate::unknown_fields::UnknownField>, crate::text::ParseError>;
286
287// ── Text-side inner maps ───────────────────────────────────────────────────
288
289#[cfg(feature = "text")]
290#[derive(Default)]
291struct TextAnyMap {
292    entries: hashbrown::HashMap<alloc::string::String, TextAnyEntry>,
293    /// Message full name → the type URL most recently registered for it.
294    by_type_name: hashbrown::HashMap<&'static str, &'static str>,
295}
296
297#[cfg(feature = "text")]
298impl TextAnyMap {
299    fn register(&mut self, entry: TextAnyEntry) {
300        if let Some(type_name) = any_type_name(entry.type_url) {
301            self.by_type_name.insert(type_name, entry.type_url);
302        }
303        self.entries
304            .insert(alloc::string::String::from(entry.type_url), entry);
305    }
306
307    fn lookup(&self, type_url: &str) -> Option<&TextAnyEntry> {
308        if let Some(entry) = self.entries.get(type_url) {
309            return Some(entry);
310        }
311
312        let type_name = any_type_name(type_url)?;
313        let registered_url = *self.by_type_name.get(type_name)?;
314        self.entries.get(registered_url)
315    }
316}
317
318#[cfg(feature = "text")]
319#[derive(Default)]
320struct TextExtMap {
321    by_number: hashbrown::HashMap<&'static str, hashbrown::HashMap<u32, TextExtEntry>>,
322    by_name: hashbrown::HashMap<&'static str, (&'static str, u32)>,
323}
324
325#[cfg(feature = "text")]
326impl TextExtMap {
327    fn register(&mut self, entry: TextExtEntry) {
328        let extendee = entry.extendee;
329        let number = entry.number;
330
331        if let Some(previous) = self
332            .by_number
333            .get_mut(extendee)
334            .and_then(|entries| entries.remove(&number))
335        {
336            self.by_name.remove(previous.full_name);
337        }
338        if let Some((previous_extendee, previous_number)) = self.by_name.remove(entry.full_name) {
339            if let Some(entries) = self.by_number.get_mut(previous_extendee) {
340                entries.remove(&previous_number);
341            }
342        }
343
344        self.by_name.insert(entry.full_name, (extendee, number));
345        self.by_number
346            .entry(extendee)
347            .or_default()
348            .insert(number, entry);
349    }
350
351    fn by_number(&self, extendee: &str, number: u32) -> Option<&TextExtEntry> {
352        self.by_number.get(extendee)?.get(&number)
353    }
354    fn by_name(&self, full_name: &str) -> Option<&TextExtEntry> {
355        let key = self.by_name.get(full_name)?;
356        self.by_number.get(key.0)?.get(&key.1)
357    }
358}
359
360// ── TypeRegistry ───────────────────────────────────────────────────────────
361
362/// Unified registry: JSON `Any` + extension entries (under `json`) and
363/// text `Any` + extension entries (under `text`).
364///
365/// Populate with generated `register_types(&mut reg)` functions, then
366/// install once with [`set_type_registry`]. The JSON half delegates to the
367/// existing [`AnyRegistry`](crate::any_registry::AnyRegistry) and
368/// [`ExtensionRegistry`](crate::extension_registry::ExtensionRegistry) types;
369/// the text half uses parallel maps. Both axes' lookup indirection
370/// (`by_name` → `by_number`) is preserved.
371#[derive(Default)]
372pub struct TypeRegistry {
373    #[cfg(feature = "json")]
374    json_any: crate::any_registry::AnyRegistry,
375    #[cfg(feature = "json")]
376    json_ext: crate::extension_registry::ExtensionRegistry,
377    #[cfg(feature = "text")]
378    text_any: TextAnyMap,
379    #[cfg(feature = "text")]
380    text_ext: TextExtMap,
381}
382
383impl TypeRegistry {
384    /// Creates an empty registry.
385    #[must_use]
386    pub fn new() -> Self {
387        Self::default()
388    }
389
390    /// Registers a JSON `Any` type entry.
391    ///
392    /// Replaces any existing entry for the same type URL. When the same
393    /// message full name is registered under several URLs, a
394    /// [`json_any_by_url`](Self::json_any_by_url) lookup of a URL that is not
395    /// itself registered uses the most recently registered one.
396    ///
397    /// A lookup by name decodes the payload as this message. A payload under
398    /// another prefix that does not decode as it fails to serialize as JSON;
399    /// one that does decode is written with this message's fields.
400    #[cfg(feature = "json")]
401    pub fn register_json_any(&mut self, entry: JsonAnyEntry) {
402        self.json_any.register(entry);
403    }
404
405    /// Registers a JSON extension entry. Replaces any existing entry at the
406    /// same `(extendee, number)` or `full_name`.
407    #[cfg(feature = "json")]
408    pub fn register_json_ext(&mut self, entry: JsonExtEntry) {
409        self.json_ext.register(entry);
410    }
411
412    /// Registers a text `Any` type entry.
413    ///
414    /// Replaces any existing entry for the same type URL. When the same
415    /// message full name is registered under several URLs, a
416    /// [`text_any_by_url`](Self::text_any_by_url) lookup of a URL that is not
417    /// itself registered uses the most recently registered one.
418    ///
419    /// A lookup by name decodes the payload as this message. A payload under
420    /// another prefix that does not decode as it prints with an empty body;
421    /// one that does decode is written with this message's fields.
422    #[cfg(feature = "text")]
423    pub fn register_text_any(&mut self, entry: TextAnyEntry) {
424        self.text_any.register(entry);
425    }
426
427    /// Registers a text extension entry. Replaces any existing entry at the
428    /// same `(extendee, number)` or `full_name`.
429    #[cfg(feature = "text")]
430    pub fn register_text_ext(&mut self, entry: TextExtEntry) {
431        self.text_ext.register(entry);
432    }
433
434    /// Look up a JSON `Any` entry by type URL.
435    ///
436    /// A registered URL finds its own entry. Any other URL is matched by the
437    /// message full name after its last `/`, and a string without a `/` as a
438    /// bare full name. The entry's `type_url` is the registered one, so keep
439    /// the URL you looked up as the `Any`'s `type_url`.
440    #[cfg(feature = "json")]
441    pub fn json_any_by_url(&self, type_url: &str) -> Option<&JsonAnyEntry> {
442        self.json_any.lookup(type_url)
443    }
444
445    /// Look up a JSON extension entry by `(extendee, number)`.
446    #[cfg(feature = "json")]
447    pub fn json_ext_by_number(&self, extendee: &str, number: u32) -> Option<&JsonExtEntry> {
448        self.json_ext.by_number(extendee, number)
449    }
450
451    /// Look up a JSON extension entry by full name.
452    #[cfg(feature = "json")]
453    pub fn json_ext_by_name(&self, full_name: &str) -> Option<&JsonExtEntry> {
454        self.json_ext.by_name(full_name)
455    }
456
457    /// Look up a text `Any` entry by type URL.
458    ///
459    /// A registered URL finds its own entry. Any other URL is matched by the
460    /// message full name after its last `/`. A string without a `/` is found
461    /// only by an exact match, unlike in
462    /// [`json_any_by_url`](Self::json_any_by_url). The entry's `type_url` is
463    /// the registered one, so keep the URL you looked up as the `Any`'s
464    /// `type_url`.
465    #[cfg(feature = "text")]
466    pub fn text_any_by_url(&self, type_url: &str) -> Option<&TextAnyEntry> {
467        self.text_any.lookup(type_url)
468    }
469
470    /// Look up a text extension entry by `(extendee, number)`.
471    #[cfg(feature = "text")]
472    pub fn text_ext_by_number(&self, extendee: &str, number: u32) -> Option<&TextExtEntry> {
473        self.text_ext.by_number(extendee, number)
474    }
475
476    /// Look up a text extension entry by full name.
477    #[cfg(feature = "text")]
478    pub fn text_ext_by_name(&self, full_name: &str) -> Option<&TextExtEntry> {
479        self.text_ext.by_name(full_name)
480    }
481}
482
483/// Deprecated alias for [`TypeRegistry`]. The registry now covers both JSON
484/// and text formats.
485#[deprecated(since = "0.3.0", note = "renamed to TypeRegistry")]
486pub type JsonRegistry = TypeRegistry;
487
488impl core::fmt::Debug for TypeRegistry {
489    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
490        f.debug_struct("TypeRegistry").finish_non_exhaustive()
491    }
492}
493
494// ── Global install ─────────────────────────────────────────────────────────
495
496#[cfg(feature = "text")]
497static TEXT_ANY: core::sync::atomic::AtomicPtr<TextAnyMap> =
498    core::sync::atomic::AtomicPtr::new(core::ptr::null_mut());
499
500#[cfg(feature = "text")]
501static TEXT_EXT: core::sync::atomic::AtomicPtr<TextExtMap> =
502    core::sync::atomic::AtomicPtr::new(core::ptr::null_mut());
503
504/// Install the global type registry.
505///
506/// Decomposes into separate installs per format:
507/// - Under `json`: delegates to the existing [`AnyRegistry`] and
508///   [`ExtensionRegistry`] `AtomicPtr` globals, which generated serde impls
509///   and `Any`'s serde impl consult directly.
510/// - Under `text`: installs parallel text-only maps consulted by
511///   [`TextEncoder::try_write_any_expanded`] / [`TextDecoder::read_any_expansion`]
512///   and the extension bracket methods.
513///
514/// Call once at startup, before any serialization involving `Any` fields or
515/// extension fields. All halves are leaked (live for the program lifetime);
516/// subsequent calls leak the old allocations — same rationale as the
517/// pre-existing `set_any_registry`: avoids use-after-free races with
518/// concurrent readers.
519///
520/// [`AnyRegistry`]: crate::any_registry::AnyRegistry
521/// [`ExtensionRegistry`]: crate::extension_registry::ExtensionRegistry
522/// [`TextEncoder::try_write_any_expanded`]: crate::text::TextEncoder::try_write_any_expanded
523/// [`TextDecoder::read_any_expansion`]: crate::text::TextDecoder::read_any_expansion
524pub fn set_type_registry(reg: TypeRegistry) {
525    // Destructure once, with each binding cfg'd to match its field. This is
526    // the ergonomic form of per-feature field extraction — the binding only
527    // exists when the field does.
528    let TypeRegistry {
529        #[cfg(feature = "json")]
530        json_any,
531        #[cfg(feature = "json")]
532        json_ext,
533        #[cfg(feature = "text")]
534        text_any,
535        #[cfg(feature = "text")]
536        text_ext,
537    } = reg;
538
539    #[cfg(feature = "json")]
540    #[allow(deprecated)]
541    {
542        crate::any_registry::set_any_registry(Box::new(json_any));
543        crate::extension_registry::set_extension_registry(Box::new(json_ext));
544    }
545
546    #[cfg(feature = "text")]
547    {
548        use core::sync::atomic::Ordering;
549        TEXT_ANY.swap(Box::into_raw(Box::new(text_any)), Ordering::Release);
550        TEXT_EXT.swap(Box::into_raw(Box::new(text_ext)), Ordering::Release);
551    }
552}
553
554/// Deprecated: call [`set_type_registry`]. This alias exists for one release
555/// cycle to ease migration; the registry now covers text entries too.
556#[deprecated(since = "0.3.0", note = "renamed to set_type_registry")]
557pub fn set_json_registry(reg: TypeRegistry) {
558    set_type_registry(reg);
559}
560
561// ── Text global lookup (consulted by text encoder/decoder) ─────────────────
562
563/// Look up a text `Any` entry in the global registry. Returns `None` if no
564/// registry is installed, or neither the URL nor its message full name is
565/// registered.
566#[cfg(feature = "text")]
567pub(crate) fn global_text_any(type_url: &str) -> Option<&'static TextAnyEntry> {
568    use core::sync::atomic::Ordering;
569    let ptr = TEXT_ANY.load(Ordering::Acquire);
570    if ptr.is_null() {
571        return None;
572    }
573    // SAFETY: ptr came from Box::into_raw in set_type_registry and is never
574    // freed. Acquire synchronizes with the Release store.
575    unsafe { &*ptr }.lookup(type_url)
576}
577
578/// Look up a text extension entry by `(extendee, number)` in the global registry.
579#[cfg(feature = "text")]
580pub(crate) fn global_text_ext_by_number(
581    extendee: &str,
582    number: u32,
583) -> Option<&'static TextExtEntry> {
584    use core::sync::atomic::Ordering;
585    let ptr = TEXT_EXT.load(Ordering::Acquire);
586    if ptr.is_null() {
587        return None;
588    }
589    // SAFETY: see global_text_any.
590    unsafe { &*ptr }.by_number(extendee, number)
591}
592
593/// Look up a text extension entry by full name in the global registry.
594#[cfg(feature = "text")]
595pub(crate) fn global_text_ext_by_name(full_name: &str) -> Option<&'static TextExtEntry> {
596    use core::sync::atomic::Ordering;
597    let ptr = TEXT_EXT.load(Ordering::Acquire);
598    if ptr.is_null() {
599        return None;
600    }
601    // SAFETY: see global_text_any.
602    unsafe { &*ptr }.by_name(full_name)
603}
604
605/// Clear the global text maps. Test cleanup only; leaks old allocations.
606#[cfg(feature = "text")]
607#[doc(hidden)]
608pub fn clear_text_registry() {
609    use core::sync::atomic::Ordering;
610    TEXT_ANY.swap(core::ptr::null_mut(), Ordering::Release);
611    TEXT_EXT.swap(core::ptr::null_mut(), Ordering::Release);
612}
613
614// ── JSON Any-entry converters (codegen points JsonAnyEntry fields here) ────
615//
616// Monomorphized per message type M; the resulting fn items coerce to the
617// `fn(&[u8]) -> ...` / `fn(serde_json::Value) -> ...` pointer types on
618// JsonAnyEntry. Same pattern as extension_registry::helpers::message_to_json.
619
620/// `Any.value` bytes → JSON: decode `M` from wire bytes, then serialize via
621/// `M`'s own `Serialize` impl.
622///
623/// Codegen emits `to_json: ::buffa::type_registry::any_to_json::<Foo>` in each
624/// message's `JsonAnyEntry` const. Not intended for direct use.
625#[cfg(feature = "json")]
626pub fn any_to_json<M>(bytes: &[u8]) -> Result<serde_json::Value, alloc::string::String>
627where
628    M: crate::Message + serde::Serialize,
629{
630    use alloc::format;
631    let m = M::decode_from_slice(bytes).map_err(|e| format!("{e}"))?;
632    serde_json::to_value(&m).map_err(|e| format!("{e}"))
633}
634
635/// JSON → `Any.value` bytes: deserialize `M` via its `Deserialize` impl, then
636/// encode to wire bytes.
637///
638/// Codegen emits `from_json: ::buffa::type_registry::any_from_json::<Foo>` in
639/// each message's `JsonAnyEntry` const. Not intended for direct use.
640#[cfg(feature = "json")]
641pub fn any_from_json<M>(v: serde_json::Value) -> Result<alloc::vec::Vec<u8>, alloc::string::String>
642where
643    M: crate::Message + for<'de> serde::Deserialize<'de>,
644{
645    use alloc::format;
646    let m: M = serde_json::from_value(v).map_err(|e| format!("{e}"))?;
647    m.try_encode_to_vec().map_err(|e| format!("{e}"))
648}
649
650// ── Text Any-entry converters (codegen points TextAnyEntry fields here) ────
651//
652// Mirror `any_to_json<M>`: monomorphized per message type M, the resulting
653// fn items coerce to the `fn(...)` pointer types on TextAnyEntry.
654
655/// `Any.value` bytes → textproto: decode `M`, write its fields as a
656/// `{ ... }` message body.
657///
658/// Codegen emits `text_encode: ::buffa::type_registry::any_encode_text::<Foo>`
659/// in each message's `TextAnyEntry` const when `generate_text` is on.
660#[cfg(feature = "text")]
661pub fn any_encode_text<M>(bytes: &[u8], enc: &mut crate::text::TextEncoder<'_>) -> core::fmt::Result
662where
663    M: crate::Message + crate::text::TextFormat + Default,
664{
665    // If the stored bytes don't decode (corrupt Any), emit an empty `{}` —
666    // best effort in the fmt::Result error model. Round-trip won't be perfect
667    // but the output is still syntactically valid textproto.
668    //
669    // Deliberately not a `debug_assert!`. `Any.value` is a raw `bytes` field
670    // that decode never validates, so undecodable content is an ordinary
671    // property of untrusted input, not an invariant this library maintains;
672    // asserting on it makes a single malformed byte a panic wherever debug
673    // assertions are on.
674    let m = M::decode_from_slice(bytes).unwrap_or_default();
675    enc.write_map_entry(|enc| m.encode_text(enc))
676}
677
678/// Textproto `{ ... }` body → `Any.value` bytes: merge into a fresh `M`,
679/// re-encode to wire bytes.
680///
681/// Codegen emits `text_merge: ::buffa::type_registry::any_merge_text::<Foo>`.
682#[cfg(feature = "text")]
683pub fn any_merge_text<M>(
684    dec: &mut crate::text::TextDecoder<'_>,
685) -> Result<alloc::vec::Vec<u8>, crate::text::ParseError>
686where
687    M: crate::Message + crate::text::TextFormat + Default,
688{
689    let mut m = M::default();
690    dec.merge_message(&mut m)?;
691    m.try_encode_to_vec().map_err(|_| oversized_message_error())
692}
693
694/// Merged-message payload exceeded the 2 GiB protobuf limit
695/// ([`MAX_MESSAGE_BYTES`](crate::MAX_MESSAGE_BYTES)) — the re-encode step of
696/// a text/JSON converter cannot produce valid wire bytes for it, so the
697/// parse surfaces an error rather than panicking inside a fallible API.
698#[cfg(feature = "text")]
699fn oversized_message_error() -> crate::text::ParseError {
700    crate::text::ParseError::new(
701        0,
702        0,
703        crate::text::ParseErrorKind::Internal("merged message exceeds the 2 GiB protobuf limit"),
704    )
705}
706
707// ── Text extension converters (codegen points TextExtEntry fields here) ────
708//
709// Message- and group-typed extensions only, singular and repeated. Scalar
710// text helpers would mirror the JSON ones in `extension_registry::helpers`;
711// deferred until a use case appears.
712
713/// Textproto encode for a repeated message extension: write each element as
714/// its own `[full_name] { ... }` entry, in wire order.
715///
716/// Codegen emits
717/// `text_encode: ::buffa::type_registry::repeated_message_encode_text::<Foo>`
718/// in the `TextExtEntry` const of a `repeated Foo` extension when
719/// `generate_text` is on. A hand-written [`TextExtEntry`] can store it the
720/// same way.
721///
722/// [`TextEncoder::write_extension_fields`] writes `[full_name]` and then
723/// calls the entry's `text_encode`. Called that way, this function writes
724/// the first element after that name and has the encoder write the name
725/// again before each later element.
726///
727/// Called directly, after a name the caller wrote with
728/// [`TextEncoder::write_extension_name`], it writes the elements as one list
729/// value, `: [{ ... }, { ... }]`, because the encoder repeats only a name
730/// that `write_extension_fields` wrote. [`repeated_message_merge_text`]
731/// parses the list; [`message_merge_text`] rejects it.
732///
733/// A record that does not decode as `M` is skipped, as [`Repeated`] skips
734/// it. When every record is skipped the value is the empty list `: []` in
735/// both cases, which parses to zero elements.
736///
737/// # Errors
738///
739/// Propagates [`core::fmt::Error`] from the underlying writer.
740///
741/// [`TextEncoder::write_extension_fields`]: crate::text::TextEncoder::write_extension_fields
742/// [`TextEncoder::write_extension_name`]: crate::text::TextEncoder::write_extension_name
743/// [`Repeated`]: crate::extension::codecs::Repeated
744#[cfg(feature = "text")]
745pub fn repeated_message_encode_text<M>(
746    n: u32,
747    f: &crate::unknown_fields::UnknownFields,
748    enc: &mut crate::text::TextEncoder<'_>,
749) -> core::fmt::Result
750where
751    M: crate::Message + crate::text::TextFormat + Default,
752{
753    use crate::extension::codecs::{MessageCodec, Repeated};
754    use crate::extension::ExtensionCodec;
755    enc.write_repeated_extension(&Repeated::<MessageCodec<M>>::decode(n, f))
756}
757
758/// Textproto encode for a repeated group extension. Writes the same text as
759/// [`repeated_message_encode_text`], in the same two forms; the elements are
760/// read from `Group` records, and a record of another wire type is skipped.
761/// [`repeated_group_merge_text`] parses the list form; [`group_merge_text`]
762/// rejects it.
763///
764/// Codegen emits
765/// `text_encode: ::buffa::type_registry::repeated_group_encode_text::<Foo>`
766/// in the `TextExtEntry` const of a repeated group-encoded extension when
767/// `generate_text` is on.
768///
769/// # Errors
770///
771/// Propagates [`core::fmt::Error`] from the underlying writer.
772#[cfg(feature = "text")]
773pub fn repeated_group_encode_text<M>(
774    n: u32,
775    f: &crate::unknown_fields::UnknownFields,
776    enc: &mut crate::text::TextEncoder<'_>,
777) -> core::fmt::Result
778where
779    M: crate::Message + crate::text::TextFormat + Default,
780{
781    use crate::extension::codecs::{GroupCodec, Repeated};
782    use crate::extension::ExtensionCodec;
783    enc.write_repeated_extension(&Repeated::<GroupCodec<M>>::decode(n, f))
784}
785
786/// Textproto merge for a repeated message extension. Accepts a message list
787/// or a single message and returns one length-delimited record per element.
788///
789/// Called once per `[full_name]` occurrence, so `[x] {..} [x] {..}` and
790/// `[x]: [{..}, {..}]` yield the same records.
791///
792/// Codegen emits
793/// `text_merge: ::buffa::type_registry::repeated_message_merge_text::<Foo>`
794/// in the `TextExtEntry` const of a `repeated Foo` extension when
795/// `generate_text` is on.
796///
797/// # Errors
798///
799/// Returns a parse error for invalid text, an exceeded decode budget, or a
800/// message that exceeds the protobuf encode-size limit.
801#[cfg(feature = "text")]
802pub fn repeated_message_merge_text<M>(
803    dec: &mut crate::text::TextDecoder<'_>,
804    n: u32,
805) -> Result<alloc::vec::Vec<crate::unknown_fields::UnknownField>, crate::text::ParseError>
806where
807    M: crate::Message + crate::text::TextFormat + Default,
808{
809    let mut records = alloc::vec::Vec::new();
810    dec.read_repeated_into(&mut records, |dec| message_record::<M>(dec, n))?;
811    Ok(records)
812}
813
814/// Textproto merge for a repeated group extension. Reads the same text as
815/// [`repeated_message_merge_text`] and returns one `Group` record per
816/// element.
817///
818/// Codegen emits
819/// `text_merge: ::buffa::type_registry::repeated_group_merge_text::<Foo>`
820/// in the `TextExtEntry` const of a repeated group-encoded extension when
821/// `generate_text` is on.
822///
823/// # Errors
824///
825/// The same errors as [`repeated_message_merge_text`].
826#[cfg(feature = "text")]
827pub fn repeated_group_merge_text<M>(
828    dec: &mut crate::text::TextDecoder<'_>,
829    n: u32,
830) -> Result<alloc::vec::Vec<crate::unknown_fields::UnknownField>, crate::text::ParseError>
831where
832    M: crate::Message + crate::text::TextFormat + Default,
833{
834    let mut records = alloc::vec::Vec::new();
835    dec.read_repeated_into(&mut records, |dec| group_record::<M>(dec, n))?;
836    Ok(records)
837}
838
839/// Textproto encode for a message-typed extension: decode `M` from the
840/// unknown fields (merge semantics), write as a `{ ... }` message body.
841#[cfg(feature = "text")]
842pub fn message_encode_text<M>(
843    n: u32,
844    f: &crate::unknown_fields::UnknownFields,
845    enc: &mut crate::text::TextEncoder<'_>,
846) -> core::fmt::Result
847where
848    M: crate::Message + crate::text::TextFormat + Default,
849{
850    use crate::extension::codecs::MessageCodec;
851    use crate::extension::ExtensionCodec;
852    let m = MessageCodec::<M>::decode(n, f).unwrap_or_default();
853    enc.write_map_entry(|enc| m.encode_text(enc))
854}
855
856/// Textproto merge for a message-typed extension: consume `{ ... }`,
857/// re-encode to a `LengthDelimited` unknown-field record.
858#[cfg(feature = "text")]
859pub fn message_merge_text<M>(
860    dec: &mut crate::text::TextDecoder<'_>,
861    n: u32,
862) -> Result<alloc::vec::Vec<crate::unknown_fields::UnknownField>, crate::text::ParseError>
863where
864    M: crate::Message + crate::text::TextFormat + Default,
865{
866    Ok(alloc::vec![message_record::<M>(dec, n)?])
867}
868
869/// Consume one `{ ... }` message and re-encode it to the `LengthDelimited`
870/// record of extension `n`.
871#[cfg(feature = "text")]
872fn message_record<M>(
873    dec: &mut crate::text::TextDecoder<'_>,
874    n: u32,
875) -> Result<crate::unknown_fields::UnknownField, crate::text::ParseError>
876where
877    M: crate::Message + crate::text::TextFormat + Default,
878{
879    use crate::unknown_fields::{UnknownField, UnknownFieldData};
880    let mut m = M::default();
881    dec.merge_message(&mut m)?;
882    let bytes = m
883        .try_encode_to_vec()
884        .map_err(|_| oversized_message_error())?;
885    Ok(UnknownField {
886        number: n,
887        data: UnknownFieldData::LengthDelimited(bytes),
888    })
889}
890
891/// Textproto encode for a group-encoded extension. Identical body to
892/// [`message_encode_text`] on the encode side — only the wire-type of
893/// the stored unknown field differs (`Group` vs `LengthDelimited`).
894#[cfg(feature = "text")]
895pub fn group_encode_text<M>(
896    n: u32,
897    f: &crate::unknown_fields::UnknownFields,
898    enc: &mut crate::text::TextEncoder<'_>,
899) -> core::fmt::Result
900where
901    M: crate::Message + crate::text::TextFormat + Default,
902{
903    use crate::extension::codecs::GroupCodec;
904    use crate::extension::ExtensionCodec;
905    let m = GroupCodec::<M>::decode(n, f).unwrap_or_default();
906    enc.write_map_entry(|enc| m.encode_text(enc))
907}
908
909/// Textproto merge for a group-encoded extension: consume `{ ... }`,
910/// re-encode the message's fields into a `Group(UnknownFields)` record.
911///
912/// Same round-trip-through-bytes as [`GroupCodec::encode`]: encode `M`
913/// to wire bytes, re-parse as `UnknownFields`, wrap in `Group`. The
914/// inner `UnknownFields` then serialize as `SGROUP … EGROUP` on binary
915/// output.
916///
917/// [`GroupCodec::encode`]: crate::extension::codecs::GroupCodec
918#[cfg(feature = "text")]
919pub fn group_merge_text<M>(
920    dec: &mut crate::text::TextDecoder<'_>,
921    n: u32,
922) -> Result<alloc::vec::Vec<crate::unknown_fields::UnknownField>, crate::text::ParseError>
923where
924    M: crate::Message + crate::text::TextFormat + Default,
925{
926    Ok(alloc::vec![group_record::<M>(dec, n)?])
927}
928
929/// Consume one `{ ... }` message and re-encode its fields to the `Group`
930/// record of extension `n`.
931#[cfg(feature = "text")]
932fn group_record<M>(
933    dec: &mut crate::text::TextDecoder<'_>,
934    n: u32,
935) -> Result<crate::unknown_fields::UnknownField, crate::text::ParseError>
936where
937    M: crate::Message + crate::text::TextFormat + Default,
938{
939    use crate::unknown_fields::{UnknownField, UnknownFieldData, UnknownFields};
940    let mut m = M::default();
941    dec.merge_message(&mut m)?;
942    let bytes = m
943        .try_encode_to_vec()
944        .map_err(|_| oversized_message_error())?;
945    // Freshly-encoded → re-decode cannot fail short of an encoder bug.
946    // Surface as Internal rather than panicking so a library caller
947    // isn't taken down by it.
948    let inner = UnknownFields::decode_from_slice(&bytes).map_err(|_| {
949        crate::text::ParseError::new(
950            0,
951            0,
952            crate::text::ParseErrorKind::Internal(
953                "re-decoding freshly-encoded group message bytes failed",
954            ),
955        )
956    })?;
957    Ok(UnknownField {
958        number: n,
959        data: UnknownFieldData::Group(inner),
960    })
961}
962
963// ── Tests ──────────────────────────────────────────────────────────────────
964
965#[cfg(test)]
966mod tests {
967    use super::*;
968
969    #[test]
970    fn default_is_empty() {
971        let reg = TypeRegistry::default();
972        #[cfg(feature = "json")]
973        assert!(reg.json_any_by_url("anything").is_none());
974        #[cfg(feature = "text")]
975        assert!(reg.text_any_by_url("anything").is_none());
976        #[cfg(not(any(feature = "json", feature = "text")))]
977        let _ = reg;
978    }
979
980    #[test]
981    fn debug_impl() {
982        let reg = TypeRegistry::new();
983        let s = alloc::format!("{reg:?}");
984        assert!(s.contains("TypeRegistry"), "{s}");
985    }
986
987    #[cfg(feature = "json")]
988    #[test]
989    fn refusing_any_expansion_does_not_decrement_active_depth() {
990        let _guards: alloc::vec::Vec<_> = (0..MAX_ANY_EXPANSION_DEPTH)
991            .map(|_| enter_any_expansion().expect("entry below the cap must succeed"))
992            .collect();
993
994        assert!(enter_any_expansion().is_none());
995        assert!(enter_any_expansion().is_none());
996    }
997
998    // ── JSON half ───────────────────────────────────────────────────────────
999
1000    #[cfg(feature = "json")]
1001    mod json {
1002        use super::*;
1003        use crate::any_registry::with_any_registry;
1004        use crate::extension_registry::{extension_registry, helpers};
1005
1006        fn dummy_to_json(_: &[u8]) -> Result<serde_json::Value, alloc::string::String> {
1007            Ok(serde_json::json!({"ok": true}))
1008        }
1009        fn dummy_from_json(
1010            _: serde_json::Value,
1011        ) -> Result<alloc::vec::Vec<u8>, alloc::string::String> {
1012            Ok(alloc::vec![1, 2, 3])
1013        }
1014
1015        fn any_entry(url: &'static str, wkt: bool) -> JsonAnyEntry {
1016            JsonAnyEntry {
1017                type_url: url,
1018                to_json: dummy_to_json,
1019                from_json: dummy_from_json,
1020                is_wkt: wkt,
1021            }
1022        }
1023
1024        fn ext_entry(num: u32, name: &'static str, ext: &'static str) -> JsonExtEntry {
1025            JsonExtEntry {
1026                number: num,
1027                full_name: name,
1028                extendee: ext,
1029                to_json: helpers::int32_to_json,
1030                from_json: helpers::int32_from_json,
1031            }
1032        }
1033
1034        #[test]
1035        fn register_json_any_and_ext_independently() {
1036            let mut reg = TypeRegistry::new();
1037            reg.register_json_any(any_entry("type.googleapis.com/test.Foo", false));
1038            reg.register_json_ext(ext_entry(100, "test.ext", "test.Foo"));
1039
1040            assert!(reg
1041                .json_any_by_url("type.googleapis.com/test.Foo")
1042                .is_some());
1043            assert!(reg.json_ext_by_number("test.Foo", 100).is_some());
1044            assert!(reg.json_ext_by_name("test.ext").is_some());
1045        }
1046
1047        #[test]
1048        fn set_type_registry_installs_json_halves() {
1049            let _g = crate::test_doubles::REGISTRY_TEST_LOCK.lock().unwrap();
1050
1051            let mut reg = TypeRegistry::new();
1052            reg.register_json_any(any_entry("type.googleapis.com/test.Unified", false));
1053            reg.register_json_ext(ext_entry(200, "test.unified_ext", "test.Unified"));
1054            set_type_registry(reg);
1055
1056            with_any_registry(|r| {
1057                let r = r.expect("any registry installed");
1058                assert!(r.lookup("type.googleapis.com/test.Unified").is_some());
1059            });
1060            let ext = extension_registry().expect("extension registry installed");
1061            assert_eq!(ext.by_name("test.unified_ext").map(|e| e.number), Some(200));
1062
1063            crate::any_registry::clear_any_registry();
1064        }
1065
1066        #[test]
1067        #[allow(deprecated)]
1068        fn deprecated_aliases_compile() {
1069            // Type aliases resolve to the new types.
1070            let _: AnyTypeEntry = any_entry("x", false);
1071            let _: ExtensionRegistryEntry = ext_entry(1, "a", "B");
1072            let _: JsonRegistry = TypeRegistry::new();
1073            // Deprecated fn redirects.
1074            let _g = crate::test_doubles::REGISTRY_TEST_LOCK.lock().unwrap();
1075            set_json_registry(TypeRegistry::new());
1076            crate::any_registry::clear_any_registry();
1077        }
1078    }
1079
1080    // ── Text half ───────────────────────────────────────────────────────────
1081
1082    #[cfg(feature = "text")]
1083    mod text {
1084        use super::*;
1085        use crate::unknown_fields::{UnknownField, UnknownFieldData, UnknownFields};
1086
1087        // Hand-implemented Message + TextFormat to avoid depending on codegen
1088        // (mirrors the TestMsg pattern in text/decoder.rs tests).
1089
1090        #[derive(Default, Clone, PartialEq, Debug)]
1091        struct Inner {
1092            n: i32,
1093        }
1094
1095        impl crate::DefaultInstance for Inner {
1096            fn default_instance() -> &'static Self {
1097                static I: crate::__private::OnceBox<Inner> = crate::__private::OnceBox::new();
1098                I.get_or_init(|| alloc::boxed::Box::new(Inner::default()))
1099            }
1100        }
1101
1102        impl crate::Message for Inner {
1103            fn compute_size(&self, _cache: &mut crate::SizeCache) -> u32 {
1104                if self.n != 0 {
1105                    1 + crate::encoding::varint_len(self.n as i64 as u64) as u32
1106                } else {
1107                    0
1108                }
1109            }
1110            fn write_to(&self, _cache: &mut crate::SizeCache, buf: &mut impl crate::EncodeSink) {
1111                if self.n != 0 {
1112                    crate::encoding::Tag::new(1, crate::encoding::WireType::Varint).encode(buf);
1113                    crate::encoding::encode_varint(self.n as i64 as u64, buf);
1114                }
1115            }
1116            fn merge_field(
1117                &mut self,
1118                tag: crate::encoding::Tag,
1119                buf: &mut impl bytes::Buf,
1120                _: crate::DecodeContext<'_>,
1121            ) -> Result<(), crate::DecodeError> {
1122                if tag.field_number() == 1 && tag.wire_type() == crate::encoding::WireType::Varint {
1123                    self.n = crate::encoding::decode_varint(buf)? as i32;
1124                    Ok(())
1125                } else {
1126                    crate::encoding::skip_field(tag, buf)
1127                }
1128            }
1129            fn clear(&mut self) {
1130                self.n = 0;
1131            }
1132        }
1133
1134        impl crate::text::TextFormat for Inner {
1135            fn encode_text(&self, enc: &mut crate::text::TextEncoder<'_>) -> core::fmt::Result {
1136                if self.n != 0 {
1137                    enc.write_field_name("n")?;
1138                    enc.write_i32(self.n)?;
1139                }
1140                Ok(())
1141            }
1142            fn merge_text(
1143                &mut self,
1144                dec: &mut crate::text::TextDecoder<'_>,
1145            ) -> Result<(), crate::text::ParseError> {
1146                while let Some(name) = dec.read_field_name()? {
1147                    match name {
1148                        "n" => self.n = dec.read_i32()?,
1149                        _ => dec.skip_value()?,
1150                    }
1151                }
1152                Ok(())
1153            }
1154        }
1155
1156        fn fields_from(records: alloc::vec::Vec<UnknownField>) -> UnknownFields {
1157            let mut f = UnknownFields::new();
1158            for r in records {
1159                f.push(r);
1160            }
1161            f
1162        }
1163
1164        #[test]
1165        fn message_text_roundtrip() {
1166            let mut dec = crate::text::TextDecoder::new("f { n: 7 }");
1167            dec.read_field_name().unwrap();
1168            let records = message_merge_text::<Inner>(&mut dec, 50).unwrap();
1169            assert_eq!(records.len(), 1);
1170            assert_eq!(records[0].number, 50);
1171            let UnknownFieldData::LengthDelimited(ref bytes) = records[0].data else {
1172                panic!("expected LengthDelimited, got {:?}", records[0].data);
1173            };
1174            assert_eq!(*bytes, alloc::vec![0x08, 0x07]);
1175
1176            let fields = fields_from(records);
1177            let mut s = alloc::string::String::new();
1178            let mut enc = crate::text::TextEncoder::new(&mut s);
1179            enc.write_extension_name("pkg.ext").unwrap();
1180            message_encode_text::<Inner>(50, &fields, &mut enc).unwrap();
1181            assert_eq!(s, "[pkg.ext] {n: 7}");
1182        }
1183
1184        #[test]
1185        fn group_text_roundtrip() {
1186            let mut dec = crate::text::TextDecoder::new("f { n: 7 }");
1187            dec.read_field_name().unwrap();
1188            let records = group_merge_text::<Inner>(&mut dec, 121).unwrap();
1189            assert_eq!(records.len(), 1);
1190            assert_eq!(records[0].number, 121);
1191            let UnknownFieldData::Group(ref inner) = records[0].data else {
1192                panic!("expected Group, got {:?}", records[0].data);
1193            };
1194            let inner_vec: alloc::vec::Vec<_> = inner.iter().collect();
1195            assert_eq!(inner_vec.len(), 1);
1196            assert_eq!(inner_vec[0].number, 1);
1197            assert_eq!(inner_vec[0].data, UnknownFieldData::Varint(7));
1198
1199            let fields = fields_from(records);
1200            let mut s = alloc::string::String::new();
1201            let mut enc = crate::text::TextEncoder::new(&mut s);
1202            enc.write_extension_name("pkg.groupfield").unwrap();
1203            group_encode_text::<Inner>(121, &fields, &mut enc).unwrap();
1204            assert_eq!(s, "[pkg.groupfield] {n: 7}");
1205        }
1206
1207        type RepeatedHelpers = (
1208            &'static str,
1209            fn(u32, &UnknownFields, &mut crate::text::TextEncoder<'_>) -> core::fmt::Result,
1210            ExtTextMergeFn,
1211        );
1212        /// Each repeated helper pair as (registered name, encode, merge).
1213        const REPEATED_HELPERS: [RepeatedHelpers; 2] = [
1214            (
1215                "pkg.rep",
1216                repeated_message_encode_text::<Inner>,
1217                repeated_message_merge_text::<Inner>,
1218            ),
1219            (
1220                "pkg.rep_group",
1221                repeated_group_encode_text::<Inner>,
1222                repeated_group_merge_text::<Inner>,
1223            ),
1224        ];
1225
1226        #[test]
1227        fn repeated_helpers_write_a_list_after_a_name_the_caller_wrote() {
1228            for (name, encode, merge) in REPEATED_HELPERS {
1229                let mut dec = crate::text::TextDecoder::new("f: [{ n: 1 }, { n: 2 }]");
1230                dec.read_field_name().unwrap();
1231                let records = merge(&mut dec, 60).unwrap();
1232                assert_eq!(records.len(), 2, "{name}");
1233
1234                for (count, expected) in [
1235                    (0, "[x]: []"),
1236                    (1, "[x]: [{n: 1}]"),
1237                    (2, "[x]: [{n: 1}, {n: 2}]"),
1238                ] {
1239                    let fields = fields_from(records[..count].to_vec());
1240                    let mut s = alloc::string::String::new();
1241                    let mut enc = crate::text::TextEncoder::new(&mut s);
1242                    enc.write_extension_name("x").unwrap();
1243                    encode(60, &fields, &mut enc).unwrap();
1244                    assert_eq!(s, expected, "{name}");
1245                }
1246
1247                let fields = fields_from(records);
1248                let mut s = alloc::string::String::new();
1249                let mut enc = crate::text::TextEncoder::new_pretty(&mut s);
1250                enc.write_extension_name("x").unwrap();
1251                encode(60, &fields, &mut enc).unwrap();
1252                assert_eq!(s, "[x]: [{\n  n: 1\n}, {\n  n: 2\n}]", "{name}");
1253            }
1254        }
1255
1256        /// Installs a global registry that holds [`REPEATED_HELPERS`] at
1257        /// numbers 60 and 61 of `pkg.Msg`, and returns three records for
1258        /// each. `text_merge` is the singular helper, which rejects a
1259        /// message list: each entry the encoder writes has to hold one
1260        /// message.
1261        fn install_repeated_entries() -> alloc::vec::Vec<UnknownField> {
1262            let singular_merges: [ExtTextMergeFn; 2] =
1263                [message_merge_text::<Inner>, group_merge_text::<Inner>];
1264            let mut reg = TypeRegistry::new();
1265            let mut records = alloc::vec::Vec::new();
1266            for (number, ((full_name, text_encode, merge), text_merge)) in
1267                (60..).zip(REPEATED_HELPERS.into_iter().zip(singular_merges))
1268            {
1269                reg.register_text_ext(TextExtEntry {
1270                    number,
1271                    full_name,
1272                    extendee: "pkg.Msg",
1273                    text_encode,
1274                    text_merge,
1275                });
1276                let mut dec = crate::text::TextDecoder::new("f: [{ n: 1 }, {}, { n: 2 }]");
1277                dec.read_field_name().unwrap();
1278                records.extend(merge(&mut dec, number).unwrap());
1279            }
1280            set_type_registry(reg);
1281            records
1282        }
1283
1284        const REPEATED_ENTRIES: &str = "[pkg.rep] {n: 1} [pkg.rep] {} [pkg.rep] {n: 2} \
1285            [pkg.rep_group] {n: 1} [pkg.rep_group] {} [pkg.rep_group] {n: 2}";
1286
1287        #[test]
1288        fn repeated_entries_parse_with_a_merge_that_reads_one_message() {
1289            let _g = crate::test_doubles::REGISTRY_TEST_LOCK.lock().unwrap();
1290            let records = install_repeated_entries();
1291
1292            let mut s = alloc::string::String::new();
1293            crate::text::TextEncoder::new(&mut s)
1294                .write_extension_fields("pkg.Msg", &fields_from(records.clone()))
1295                .unwrap();
1296            assert_eq!(s, REPEATED_ENTRIES);
1297
1298            let mut dec = crate::text::TextDecoder::new(&s);
1299            let mut reparsed = alloc::vec::Vec::new();
1300            while let Some(name) = dec.read_field_name().unwrap() {
1301                reparsed.extend(dec.read_extension(name, "pkg.Msg").unwrap());
1302            }
1303            assert_eq!(reparsed, records);
1304
1305            clear_text_registry();
1306        }
1307
1308        #[test]
1309        fn repeated_helper_does_not_repeat_a_name_from_an_earlier_entry() {
1310            let _g = crate::test_doubles::REGISTRY_TEST_LOCK.lock().unwrap();
1311            let fields = fields_from(install_repeated_entries());
1312
1313            let mut s = alloc::string::String::new();
1314            let mut enc = crate::text::TextEncoder::new(&mut s);
1315            enc.write_extension_fields("pkg.Msg", &fields).unwrap();
1316            enc.write_extension_name("x").unwrap();
1317            repeated_message_encode_text::<Inner>(60, &fields, &mut enc).unwrap();
1318            assert_eq!(
1319                s,
1320                alloc::format!("{REPEATED_ENTRIES} [x]: [{{n: 1}}, {{}}, {{n: 2}}]")
1321            );
1322
1323            clear_text_registry();
1324        }
1325
1326        /// Installs a global registry that holds `text_encode` as extension
1327        /// 60 of `pkg.Msg`, named `pkg.custom`, and returns two records at
1328        /// that number.
1329        fn install_custom_entry(
1330            text_encode: fn(
1331                u32,
1332                &UnknownFields,
1333                &mut crate::text::TextEncoder<'_>,
1334            ) -> core::fmt::Result,
1335        ) -> UnknownFields {
1336            let mut reg = TypeRegistry::new();
1337            reg.register_text_ext(TextExtEntry {
1338                number: 60,
1339                full_name: "pkg.custom",
1340                extendee: "pkg.Msg",
1341                text_encode,
1342                text_merge: repeated_message_merge_text::<Inner>,
1343            });
1344            set_type_registry(reg);
1345            let mut dec = crate::text::TextDecoder::new("f: [{ n: 1 }, { n: 2 }]");
1346            dec.read_field_name().unwrap();
1347            fields_from(repeated_message_merge_text::<Inner>(&mut dec, 60).unwrap())
1348        }
1349
1350        #[test]
1351        fn repeated_helper_does_not_repeat_the_name_of_an_entry_that_returned() {
1352            fn write_no_value(
1353                _: u32,
1354                _: &UnknownFields,
1355                _: &mut crate::text::TextEncoder<'_>,
1356            ) -> core::fmt::Result {
1357                Ok(())
1358            }
1359
1360            let _g = crate::test_doubles::REGISTRY_TEST_LOCK.lock().unwrap();
1361            let fields = install_custom_entry(write_no_value);
1362
1363            let mut s = alloc::string::String::new();
1364            let mut enc = crate::text::TextEncoder::new(&mut s);
1365            enc.write_extension_fields("pkg.Msg", &fields).unwrap();
1366            repeated_message_encode_text::<Inner>(60, &fields, &mut enc).unwrap();
1367            assert_eq!(s, "[pkg.custom]: [{n: 1}, {n: 2}]");
1368
1369            clear_text_registry();
1370        }
1371
1372        #[test]
1373        fn repeated_helper_does_not_repeat_a_name_that_already_has_a_value() {
1374            fn value_then_a_direct_call(
1375                n: u32,
1376                f: &UnknownFields,
1377                enc: &mut crate::text::TextEncoder<'_>,
1378            ) -> core::fmt::Result {
1379                message_encode_text::<Inner>(n, f, enc)?;
1380                enc.write_extension_name("x")?;
1381                repeated_message_encode_text::<Inner>(n, f, enc)
1382            }
1383
1384            let _g = crate::test_doubles::REGISTRY_TEST_LOCK.lock().unwrap();
1385            let fields = install_custom_entry(value_then_a_direct_call);
1386
1387            let mut s = alloc::string::String::new();
1388            crate::text::TextEncoder::new(&mut s)
1389                .write_extension_fields("pkg.Msg", &fields)
1390                .unwrap();
1391            assert_eq!(s, "[pkg.custom] {n: 2} [x]: [{n: 1}, {n: 2}]");
1392
1393            clear_text_registry();
1394        }
1395
1396        #[test]
1397        fn helpers_satisfy_fn_pointer_signature() {
1398            // Codegen relies on the monomorphized helpers coercing to the
1399            // registry's fn-pointer types.
1400            let _: fn(&[u8], &mut crate::text::TextEncoder<'_>) -> core::fmt::Result =
1401                any_encode_text::<Inner>;
1402            let _: AnyTextMergeFn = any_merge_text::<Inner>;
1403            let _: fn(u32, &UnknownFields, &mut crate::text::TextEncoder<'_>) -> core::fmt::Result =
1404                message_encode_text::<Inner>;
1405            let _: ExtTextMergeFn = message_merge_text::<Inner>;
1406            let _: fn(u32, &UnknownFields, &mut crate::text::TextEncoder<'_>) -> core::fmt::Result =
1407                group_encode_text::<Inner>;
1408            let _: ExtTextMergeFn = group_merge_text::<Inner>;
1409        }
1410
1411        #[test]
1412        fn register_and_lookup_text_any() {
1413            let mut reg = TypeRegistry::new();
1414            reg.register_text_any(TextAnyEntry {
1415                type_url: "type.example.com/Inner",
1416                text_encode: any_encode_text::<Inner>,
1417                text_merge: any_merge_text::<Inner>,
1418            });
1419            assert!(reg.text_any_by_url("type.example.com/Inner").is_some());
1420            assert!(reg.text_any_by_url("custom.example/v1/Inner").is_some());
1421            assert!(reg.text_any_by_url("type.example.com/Missing").is_none());
1422        }
1423
1424        #[test]
1425        fn text_any_lookup_falls_back_to_the_last_url_registered_for_a_name() {
1426            let mut reg = TypeRegistry::new();
1427            for type_url in ["type.example.com/Inner", "custom.example/v1/Inner"] {
1428                reg.register_text_any(TextAnyEntry {
1429                    type_url,
1430                    text_encode: any_encode_text::<Inner>,
1431                    text_merge: any_merge_text::<Inner>,
1432                });
1433            }
1434            let found = |url| reg.text_any_by_url(url).map(|entry| entry.type_url);
1435            assert_eq!(
1436                found("type.example.com/Inner"),
1437                Some("type.example.com/Inner")
1438            );
1439            assert_eq!(
1440                found("custom.example/v1/Inner"),
1441                Some("custom.example/v1/Inner")
1442            );
1443            assert_eq!(
1444                found("other.example/Inner"),
1445                Some("custom.example/v1/Inner")
1446            );
1447        }
1448
1449        #[test]
1450        fn register_and_lookup_text_ext_both_axes() {
1451            let mut reg = TypeRegistry::new();
1452            reg.register_text_ext(TextExtEntry {
1453                number: 50,
1454                full_name: "pkg.inner_ext",
1455                extendee: "pkg.Carrier",
1456                text_encode: message_encode_text::<Inner>,
1457                text_merge: message_merge_text::<Inner>,
1458            });
1459            // by_number axis.
1460            let e = reg.text_ext_by_number("pkg.Carrier", 50).unwrap();
1461            assert_eq!(e.full_name, "pkg.inner_ext");
1462            assert!(reg.text_ext_by_number("pkg.Carrier", 99).is_none());
1463            assert!(reg.text_ext_by_number("other.Msg", 50).is_none());
1464            // by_name axis → same entry via indirection.
1465            assert_eq!(reg.text_ext_by_name("pkg.inner_ext").unwrap().number, 50);
1466            assert!(reg.text_ext_by_name("pkg.missing").is_none());
1467        }
1468
1469        #[test]
1470        fn text_ext_replacement_evicts_both_conflicting_entries() {
1471            let mut reg = TypeRegistry::new();
1472            let make_entry = |number, full_name| TextExtEntry {
1473                number,
1474                full_name,
1475                extendee: "pkg.Carrier",
1476                text_encode: message_encode_text::<Inner>,
1477                text_merge: message_merge_text::<Inner>,
1478            };
1479
1480            reg.register_text_ext(make_entry(50, "pkg.old"));
1481            reg.register_text_ext(make_entry(51, "pkg.new"));
1482            reg.register_text_ext(make_entry(50, "pkg.new"));
1483
1484            assert!(reg.text_ext_by_name("pkg.old").is_none());
1485            assert_eq!(reg.text_ext_by_name("pkg.new").unwrap().number, 50);
1486            assert_eq!(
1487                reg.text_ext_by_number("pkg.Carrier", 50).unwrap().full_name,
1488                "pkg.new"
1489            );
1490            assert!(reg.text_ext_by_number("pkg.Carrier", 51).is_none());
1491        }
1492
1493        #[test]
1494        fn text_ext_keys_the_same_number_per_extendee() {
1495            let mut reg = TypeRegistry::new();
1496            let make_entry = |number, full_name, extendee| TextExtEntry {
1497                number,
1498                full_name,
1499                extendee,
1500                text_encode: message_encode_text::<Inner>,
1501                text_merge: message_merge_text::<Inner>,
1502            };
1503
1504            reg.register_text_ext(make_entry(50, "pkg.ext", "pkg.Carrier"));
1505            reg.register_text_ext(make_entry(50, "other.ext", "other.Carrier"));
1506            assert_eq!(
1507                reg.text_ext_by_number("pkg.Carrier", 50).unwrap().full_name,
1508                "pkg.ext"
1509            );
1510            assert_eq!(
1511                reg.text_ext_by_number("other.Carrier", 50)
1512                    .unwrap()
1513                    .full_name,
1514                "other.ext"
1515            );
1516
1517            reg.register_text_ext(make_entry(7, "pkg.ext", "other.Carrier"));
1518            assert!(reg.text_ext_by_number("pkg.Carrier", 50).is_none());
1519            assert_eq!(
1520                reg.text_ext_by_number("other.Carrier", 7)
1521                    .unwrap()
1522                    .full_name,
1523                "pkg.ext"
1524            );
1525            assert_eq!(
1526                reg.text_ext_by_name("pkg.ext").unwrap().extendee,
1527                "other.Carrier"
1528            );
1529        }
1530
1531        #[test]
1532        fn set_type_registry_installs_text_halves() {
1533            let _g = crate::test_doubles::REGISTRY_TEST_LOCK.lock().unwrap();
1534
1535            let mut reg = TypeRegistry::new();
1536            reg.register_text_any(TextAnyEntry {
1537                type_url: "type.example.com/Global",
1538                text_encode: any_encode_text::<Inner>,
1539                text_merge: any_merge_text::<Inner>,
1540            });
1541            reg.register_text_ext(TextExtEntry {
1542                number: 77,
1543                full_name: "pkg.global_ext",
1544                extendee: "pkg.Msg",
1545                text_encode: message_encode_text::<Inner>,
1546                text_merge: message_merge_text::<Inner>,
1547            });
1548            set_type_registry(reg);
1549
1550            assert!(global_text_any("type.example.com/Global").is_some());
1551            assert!(global_text_any("type.example.com/Absent").is_none());
1552            assert_eq!(
1553                global_text_ext_by_name("pkg.global_ext").map(|e| e.number),
1554                Some(77)
1555            );
1556            assert!(global_text_ext_by_number("pkg.Msg", 77).is_some());
1557
1558            clear_text_registry();
1559            assert!(global_text_any("type.example.com/Global").is_none());
1560        }
1561
1562        #[test]
1563        fn bracketed_names_with_trivia_resolve_through_the_registry() {
1564            let _g = crate::test_doubles::REGISTRY_TEST_LOCK.lock().unwrap();
1565
1566            let mut reg = TypeRegistry::new();
1567            reg.register_text_any(TextAnyEntry {
1568                type_url: "type.example.com/pkg.Inner",
1569                text_encode: any_encode_text::<Inner>,
1570                text_merge: any_merge_text::<Inner>,
1571            });
1572            reg.register_text_ext(TextExtEntry {
1573                number: 77,
1574                full_name: "pkg.trivia_ext",
1575                extendee: "pkg.Msg",
1576                text_encode: message_encode_text::<Inner>,
1577                text_merge: message_merge_text::<Inner>,
1578            });
1579            set_type_registry(reg);
1580
1581            let input = "[ type.example.com / # ] is comment text\n pkg . Inner ] { n: 7 }";
1582            let mut dec = crate::text::TextDecoder::new(input);
1583            let name = dec.read_field_name().unwrap().unwrap();
1584            let (url, value) = dec.read_any_expansion(name).unwrap();
1585            assert_eq!(url, "type.example.com/pkg.Inner");
1586            assert_eq!(value, alloc::vec![0x08, 0x07]);
1587
1588            let input = "[ pkg . # ] is comment text\n trivia_ext ] { n: 7 }";
1589            let mut dec = crate::text::TextDecoder::new(input);
1590            let name = dec.read_field_name().unwrap().unwrap();
1591            let records = dec.read_extension(name, "pkg.Msg").unwrap();
1592            assert_eq!(records.len(), 1);
1593            assert_eq!(records[0].number, 77);
1594
1595            // Stripping trivia does not make an unregistered name resolve.
1596            let mut dec = crate::text::TextDecoder::new("[ pkg . other_ext ] { n: 7 }");
1597            let name = dec.read_field_name().unwrap().unwrap();
1598            let err = dec.read_extension(name, "pkg.Msg").unwrap_err();
1599            assert_eq!(err.kind, crate::text::ParseErrorKind::UnknownField);
1600
1601            clear_text_registry();
1602        }
1603    }
1604}