Skip to main content

google_protobuf/upb_kernel/
reflection.rs

1// Protocol Buffers - Google's data interchange format
2// Copyright 2026 Google LLC.  All rights reserved.
3//
4// Use of this source code is governed by a BSD-style
5// license that can be found in the LICENSE file or at
6// https://developers.google.com/open-source/licenses/bsd
7
8//! Reflection support for the upb kernel.
9//!
10//! upb messages carry no descriptors of their own, so every reflective operation first looks up
11//! the message's `MessageDef` in the process-wide `DefPool` (see `def_pool.rs`), then hands both
12//! the message and the def to upb.
13
14use super::upb::TextEncodeOptions;
15use super::{message_def, upb_reflection, UpbGetMessagePtr, UpbWithReflection};
16use crate::__internal::Private;
17use crate::WithReflection;
18
19/// Implemented by every generated message whose `MessageDef` can be looked up at runtime.
20///
21/// `UpbGetMessagePtr<Msg = Self>` ties the message pointer that reflection APIs operate on to the
22/// `MessageDef` they look up by `Self`, so the two can never describe different message types.
23pub trait KernelWithReflection: UpbWithReflection + UpbGetMessagePtr<Msg = Self> {}
24impl<T: UpbWithReflection + UpbGetMessagePtr<Msg = T>> KernelWithReflection for T {}
25
26/// Returns the protobuf TextFormat representation of `msg` with custom options.
27pub fn print_to_text_format<T: WithReflection>(
28    msg: &T,
29    single_line: bool,
30    hide_unknown_fields: bool,
31) -> String {
32    let ptr = msg.get_ptr(Private);
33    let def = message_def::<T>();
34    let options = TextEncodeOptions { single_line, skip_unknown: hide_unknown_fields };
35    // SAFETY:
36    // - `ptr` points to a live message that `msg` keeps alive for the duration of the call.
37    // - `def` describes `T`, and `WithReflection` guarantees `kernelWithReflection`, which
38    //   guarantees `UpbGetMessagePtr<Msg = T>, therefore `ptr` is a `MessagePtr<T>`.
39    // TODO: Pass the global DefPool as `ext_pool` so that extensions are printed.
40    unsafe { upb_reflection::text_encode(ptr, def, None, options) }
41}