[api] Rename VARINT_MAX_ to VARINT_THRESHOLD_ for clarity

These are exclusive upper bounds (value < threshold), not inclusive
maximums. The new name avoids off-by-one confusion if reused.
This commit is contained in:
J. Nick Koston
2026-03-12 22:45:26 -10:00
parent c7af451a56
commit a29206f838
2 changed files with 12 additions and 11 deletions
@@ -253,9 +253,10 @@ APIError APIPlaintextFrameHelper::write_protobuf_messages(ProtoWriteBuffer buffe
for (const auto &msg : messages) {
// Calculate varint sizes for header layout using inline ternary to avoid varint_slow call overhead
uint8_t size_varint_len =
msg.payload_size < ProtoSize::VARINT_MAX_1_BYTE ? 1 : (msg.payload_size < ProtoSize::VARINT_MAX_2_BYTE ? 2 : 3);
uint8_t type_varint_len = msg.message_type < ProtoSize::VARINT_MAX_1_BYTE ? 1 : 2;
uint8_t size_varint_len = msg.payload_size < ProtoSize::VARINT_THRESHOLD_1_BYTE
? 1
: (msg.payload_size < ProtoSize::VARINT_THRESHOLD_2_BYTE ? 2 : 3);
uint8_t type_varint_len = msg.message_type < ProtoSize::VARINT_THRESHOLD_1_BYTE ? 1 : 2;
uint8_t total_header_len = 1 + size_varint_len + type_varint_len;
// Calculate where to start writing the header
+8 -8
View File
@@ -474,10 +474,10 @@ class ProtoDecodableMessage : public ProtoMessage {
class ProtoSize {
public:
// Varint encoding thresholds: values below each threshold fit in N bytes
static constexpr uint32_t VARINT_MAX_1_BYTE = 1 << 7; // 128
static constexpr uint32_t VARINT_MAX_2_BYTE = 1 << 14; // 16384
static constexpr uint32_t VARINT_MAX_3_BYTE = 1 << 21; // 2097152
static constexpr uint32_t VARINT_MAX_4_BYTE = 1 << 28; // 268435456
static constexpr uint32_t VARINT_THRESHOLD_1_BYTE = 1 << 7; // 128
static constexpr uint32_t VARINT_THRESHOLD_2_BYTE = 1 << 14; // 16384
static constexpr uint32_t VARINT_THRESHOLD_3_BYTE = 1 << 21; // 2097152
static constexpr uint32_t VARINT_THRESHOLD_4_BYTE = 1 << 28; // 268435456
/**
* @brief Calculates the size in bytes needed to encode a uint32_t value as a varint
@@ -486,7 +486,7 @@ class ProtoSize {
* @return The number of bytes needed to encode the value
*/
static constexpr inline uint32_t ESPHOME_ALWAYS_INLINE varint(uint32_t value) {
if (value < VARINT_MAX_1_BYTE) [[likely]]
if (value < VARINT_THRESHOLD_1_BYTE) [[likely]]
return 1; // Fast path: 7 bits, most common case
if (__builtin_is_constant_evaluated())
return varint_wide(value);
@@ -498,11 +498,11 @@ class ProtoSize {
static uint32_t varint_slow(uint32_t value) __attribute__((noinline));
// Shared cascade for values >= 128 (used by both constexpr and noinline paths)
static constexpr inline uint32_t ESPHOME_ALWAYS_INLINE varint_wide(uint32_t value) {
if (value < VARINT_MAX_2_BYTE)
if (value < VARINT_THRESHOLD_2_BYTE)
return 2;
if (value < VARINT_MAX_3_BYTE)
if (value < VARINT_THRESHOLD_3_BYTE)
return 3;
if (value < VARINT_MAX_4_BYTE)
if (value < VARINT_THRESHOLD_4_BYTE)
return 4;
return 5;
}