From 02b424388e4ef62207bb1d71ef160ccaf114673c Mon Sep 17 00:00:00 2001 From: "J. Nick Koston" Date: Fri, 3 Apr 2026 12:28:51 -1000 Subject: [PATCH] [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. --- script/api_protobuf/api_protobuf.py | 26 +++++++++++--------------- 1 file changed, 11 insertions(+), 15 deletions(-) diff --git a/script/api_protobuf/api_protobuf.py b/script/api_protobuf/api_protobuf.py index 4012db336e..1381d5586f 100755 --- a/script/api_protobuf/api_protobuf.py +++ b/script/api_protobuf/api_protobuf.py @@ -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({value}));", + "encode_uint64": "buffer.write_raw_byte(static_cast({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({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)}"