Extract string and bytes default value creation to a helper function

PiperOrigin-RevId: 582949483
pull/14689/head
Adrian Sadłocha 1 year ago committed by Copybara-Service
parent 1388e818a7
commit 1fa484c4ed
  1. 8
      src/google/protobuf/compiler/rust/accessors/helpers.cc
  2. 4
      src/google/protobuf/compiler/rust/accessors/helpers.h
  3. 7
      src/google/protobuf/compiler/rust/accessors/singular_string.cc

@ -12,6 +12,7 @@
#include <string>
#include "absl/log/absl_log.h"
#include "absl/strings/escaping.h"
#include "absl/strings/str_cat.h"
#include "absl/strings/str_format.h"
#include "google/protobuf/compiler/rust/context.h"
@ -72,12 +73,13 @@ std::string DefaultValue(Context<FieldDescriptor> field) {
case FieldDescriptor::TYPE_BOOL:
return absl::StrFormat("%v", field.desc().default_value_bool());
case FieldDescriptor::TYPE_STRING:
case FieldDescriptor::TYPE_BYTES:
return absl::StrFormat(
"b\"%s\"", absl::CHexEscape(field.desc().default_value_string()));
case FieldDescriptor::TYPE_GROUP:
case FieldDescriptor::TYPE_MESSAGE:
case FieldDescriptor::TYPE_BYTES:
case FieldDescriptor::TYPE_ENUM:
ABSL_LOG(FATAL) << "Non-singular scalar field type passed: "
<< field.desc().type_name();
ABSL_LOG(FATAL) << "Unsupported field type: " << field.desc().type_name();
}
ABSL_LOG(FATAL) << "unreachable";
}

@ -19,6 +19,10 @@ namespace compiler {
namespace rust {
// Returns the field's default value as a Rust literal / identifier.
//
// Both strings and bytes are represented as a byte string literal, i.e. in the
// format `b"default value here"`. It is the caller's responsibility to convert
// the byte literal to an actual string, if needed.
std::string DefaultValue(Context<FieldDescriptor> field);
} // namespace rust

@ -7,10 +7,10 @@
#include <string>
#include "absl/strings/escaping.h"
#include "absl/strings/string_view.h"
#include "google/protobuf/compiler/cpp/helpers.h"
#include "google/protobuf/compiler/rust/accessors/accessor_generator.h"
#include "google/protobuf/compiler/rust/accessors/helpers.h"
#include "google/protobuf/compiler/rust/context.h"
#include "google/protobuf/compiler/rust/naming.h"
#include "google/protobuf/descriptor.h"
@ -69,8 +69,7 @@ void SingularString::InMsgImpl(Context<FieldDescriptor> field) const {
{
{"field", field.desc().name()},
{"proxied_type", proxied_type},
{"default_val",
absl::CHexEscape(field.desc().default_value_string())},
{"default_val", DefaultValue(field)},
{"view_type", proxied_type},
{"transform_field_entry",
[&] {
@ -98,7 +97,7 @@ void SingularString::InMsgImpl(Context<FieldDescriptor> field) const {
$getter_thunk$,
$setter_thunk$,
$clearer_thunk$,
b"$default_val$",
$default_val$,
)
};
let out = unsafe {

Loading…
Cancel
Save