[api] Add encode_small_varint helper for single-byte tag+value encoding

Replace two separate write_raw_byte calls with a single
encode_small_varint(tag, value) call that writes both bytes
with one bounds check. Used for enum fields with max < 128.
This commit is contained in:
J. Nick Koston
2026-04-05 18:53:48 -10:00
parent 5a6330e366
commit 883a300785
3 changed files with 69 additions and 108 deletions
+11 -6
View File
@@ -244,10 +244,10 @@ class TypeInfo(ABC):
"encode_bool": "buffer.write_raw_byte({value} ? 0x01 : 0x00);",
}
# When max_value < 128, the varint is always 1 byte — use a direct byte write
# When max_value < 128, the varint is always 1 byte — use encode_small_varint
RAW_ENCODE_SMALL_MAP: dict[str, str] = {
"encode_uint32": "buffer.write_raw_byte(static_cast<uint8_t>({value}));",
"encode_uint64": "buffer.write_raw_byte(static_cast<uint8_t>({value}));",
"encode_uint32": "buffer.encode_small_varint({tag}, static_cast<uint8_t>({value}));",
"encode_uint64": "buffer.encode_small_varint({tag}, static_cast<uint8_t>({value}));",
}
def _encode_with_precomputed_tag(self, value_expr: str) -> str | None:
@@ -255,7 +255,7 @@ class TypeInfo(ABC):
Returns the raw encode string if the tag is a single byte and the
encode_func has a known raw equivalent, or None otherwise.
When max_value < 128, uses direct byte write instead of varint encoding.
When max_value < 128, uses encode_small_varint instead of varint encoding.
"""
if not self.force:
return None
@@ -270,6 +270,12 @@ class TypeInfo(ABC):
raw_expr = self.RAW_ENCODE_MAP.get(self.encode_func)
if raw_expr is None:
return None
if (
max_val is not None
and max_val < 128
and self.encode_func in self.RAW_ENCODE_SMALL_MAP
):
return raw_expr.format(tag=tag, value=value_expr)
return f"buffer.write_raw_byte({tag});\n{raw_expr.format(value=value_expr)}"
def _encode_bytes_with_precomputed_tag(
@@ -1341,8 +1347,7 @@ class EnumType(TypeInfo):
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>(this->{self.field_name}));\n"
f" buffer.encode_small_varint({tag}, static_cast<uint8_t>(this->{self.field_name}));\n"
f"}}"
)
if self.force: