[api] Use RAW_ENCODE_SMALL_MAP for max_value encode optimization

Replace inline encode_func check with a lookup table, matching the
existing RAW_ENCODE_MAP pattern.
This commit is contained in:
J. Nick Koston
2026-04-03 12:28:51 -10:00
parent 363d811cc1
commit 02b424388e
+11 -15
View File
@@ -240,6 +240,12 @@ 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
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}));",
}
def _encode_with_precomputed_tag(self, value_expr: str) -> str | None:
"""Try to emit a precomputed-tag encode for a forced field.
@@ -252,22 +258,12 @@ class TypeInfo(ABC):
tag = self.calculate_tag()
if tag >= 128:
return None
# When max_value < 128, varint is always 1 byte - use direct byte write
max_val = self.max_value
if (
max_val is not None
and max_val < 128
and self.encode_func
in (
"encode_uint32",
"encode_uint64",
)
):
return (
f"buffer.write_raw_byte({tag});\n"
f"buffer.write_raw_byte(static_cast<uint8_t>({value_expr}));"
)
raw_expr = self.RAW_ENCODE_MAP.get(self.encode_func)
raw_expr = (
self.RAW_ENCODE_SMALL_MAP.get(self.encode_func)
if max_val is not None and max_val < 128
else self.RAW_ENCODE_MAP.get(self.encode_func)
)
if raw_expr is None:
return None
return f"buffer.write_raw_byte({tag});\n{raw_expr.format(value=value_expr)}"