From a25e2737554b63b2a89c33161163736c2a31ff90 Mon Sep 17 00:00:00 2001 From: Protobuf Team Bot Date: Wed, 8 Jan 2025 00:57:48 -0800 Subject: [PATCH] Internal change PiperOrigin-RevId: 713192418 --- src/google/protobuf/compiler/cpp/message.cc | 39 ++++++++++++++++++++ src/google/protobuf/generated_message_util.h | 14 +++++++ 2 files changed, 53 insertions(+) diff --git a/src/google/protobuf/compiler/cpp/message.cc b/src/google/protobuf/compiler/cpp/message.cc index 4dd75e622f080..7fcf53a72e0ab 100644 --- a/src/google/protobuf/compiler/cpp/message.cc +++ b/src/google/protobuf/compiler/cpp/message.cc @@ -1406,6 +1406,45 @@ void MessageGenerator::GenerateFieldAccessorDefinitions(io::Printer* p) { // Generate type-specific accessors. field_generators_.get(field).GenerateInlineAccessorDefinitions(p); + if (!field->is_repeated()) { + switch (field->cpp_type()) { + case FieldDescriptor::CPPTYPE_INT32: + case FieldDescriptor::CPPTYPE_INT64: + case FieldDescriptor::CPPTYPE_UINT32: + case FieldDescriptor::CPPTYPE_UINT64: + case FieldDescriptor::CPPTYPE_DOUBLE: + case FieldDescriptor::CPPTYPE_FLOAT: + case FieldDescriptor::CPPTYPE_BOOL: + case FieldDescriptor::CPPTYPE_ENUM: + p->Emit( // + {{"field_type", field->cpp_type() == FieldDescriptor::CPPTYPE_ENUM + ? QualifiedClassName(field->enum_type()) + : PrimitiveTypeName(field->cpp_type())}, + {"has", + [&]() { + if (field->has_presence()) { + p->Emit(R"cc(&$message_type$::has_$name$)cc"); + } else { + p->Emit(R"cc(nullptr)cc"); + } + }}}, + R"cc( + struct $message_type$_$name$_Descriptor + : ::google::protobuf::internal::NumericFieldDescriptor< + $message_type$, $field_type$, &$message_type$::$name$, + &$message_type$::set_$name$, + &$message_type$::clear_$name$, $has$> { + static constexpr absl::string_view name = "$name$"; + static constexpr int number = $number$; + }; + )cc"); + break; + case FieldDescriptor::CPPTYPE_STRING: + case FieldDescriptor::CPPTYPE_MESSAGE: + break; + } + } + p->Emit("\n"); } diff --git a/src/google/protobuf/generated_message_util.h b/src/google/protobuf/generated_message_util.h index d73edc3be7421..efac950c6f342 100644 --- a/src/google/protobuf/generated_message_util.h +++ b/src/google/protobuf/generated_message_util.h @@ -391,6 +391,20 @@ constexpr absl::optional EncodePlacementArenaOffsets( return arena_bits; } +template +struct NumericFieldDescriptor { + static field_type Get(const message_type& msg) { return (msg.*get)(); } + static void Set(message_type& msg, field_type value) { (msg.*set)(value); } + static void Clear(message_type& msg) { (msg.*clear)(); } + static constexpr bool has_presence = has != nullptr; + static std::enable_if_t Has(const message_type& msg) { + return (msg.*has)(); + } +}; + } // namespace internal } // namespace protobuf } // namespace google