[api] Optimize encode for non-forced enum fields with single-byte tags

When an enum field has max_value < 128 and a single-byte tag, emit
inline write_raw_byte calls instead of calling encode_uint32, which
avoids encode_field_raw and encode_varint_raw function call overhead.
This commit is contained in:
J. Nick Koston
2026-04-05 18:50:23 -10:00
parent acd2fc3711
commit 5c178eab63
2 changed files with 220 additions and 56 deletions
+16 -5
View File
@@ -1330,13 +1330,24 @@ class EnumType(TypeInfo):
@property
def encode_content(self) -> str:
if result := self._encode_with_precomputed_tag(
f"static_cast<uint32_t>(this->{self.field_name})"
):
value_expr = f"static_cast<uint32_t>(this->{self.field_name})"
if result := self._encode_with_precomputed_tag(value_expr):
return result
# For non-forced enum fields with max < 128 and single-byte tag,
# emit a zero-check + two raw byte writes instead of encode_uint32
max_val = self.max_value
if max_val is not None and max_val < 128 and not self.force:
tag = self.calculate_tag()
if tag < 128:
return (
f"if (this->{self.field_name}) {{\n"
f" buffer.write_raw_byte({tag});\n"
f" buffer.write_raw_byte(static_cast<uint8_t>({value_expr}));\n"
f"}}"
)
if self.force:
return f"buffer.{self.encode_func}({self.number}, static_cast<uint32_t>(this->{self.field_name}), true);"
return f"buffer.{self.encode_func}({self.number}, static_cast<uint32_t>(this->{self.field_name}));"
return f"buffer.{self.encode_func}({self.number}, {value_expr}, true);"
return f"buffer.{self.encode_func}({self.number}, {value_expr});"
def dump(self, name: str) -> str:
return f"out.append_p(proto_enum_to_string<{self.cpp_type}>({name}));"