[api] Use write_tag_and_fixed32 and extract calculate_tag helper

- Combine tag byte + fixed32 value into single write_tag_and_fixed32()
  method: pos[0] = tag, memcpy(pos+1, &value, 4), pos += 5
- Extract calculate_tag() from duplicated computation in
  calculate_field_id_size() and encode_content
This commit is contained in:
J. Nick Koston
2026-03-20 23:45:23 -10:00
parent 21725983fd
commit 225c770b1b
3 changed files with 64 additions and 114 deletions
+8 -8
View File
@@ -254,14 +254,17 @@ class TypeInfo(ABC):
def dump(self, name: str) -> str:
"""Dump the value to the output."""
def calculate_tag(self) -> int:
"""Calculate the protobuf tag (field_id << 3 | wire_type)."""
return (self.number << 3) | (self.wire_type & 0b111)
def calculate_field_id_size(self) -> int:
"""Calculates the size of a field ID in bytes.
Returns:
The number of bytes needed to encode the field ID
"""
# Calculate the tag by combining field_id and wire_type
tag = (self.number << 3) | (self.wire_type & 0b111)
tag = self.calculate_tag()
# Calculate the varint size
if tag < 128:
@@ -558,13 +561,10 @@ class Fixed32Type(TypeInfo):
@property
def encode_content(self) -> str:
tag = (self.number << 3) | (self.wire_type & 0b111)
tag = self.calculate_tag()
if self.force and tag < 128:
# Emit raw byte writes: precomputed tag + direct memcpy
return (
f"buffer.write_raw_byte({tag});\n"
f"buffer.write_fixed32_raw(this->{self.field_name});"
)
# Emit combined tag+value write: precomputed tag + direct memcpy
return f"buffer.write_tag_and_fixed32({tag}, this->{self.field_name});"
if self.force:
return f"buffer.{self.encode_func}({self.number}, this->{self.field_name}, true);"
return f"buffer.{self.encode_func}({self.number}, this->{self.field_name});"