Conflict:protobuf-c.c Reference:https://gitee.com/src-openeuler/protobuf-c/pulls/19/files diff --git a/lib/logsrv/protobuf-c.c b/lib/logsrv/protobuf-c.c index 7a6b56d..27267e6 100644 --- a/lib/logsrv/protobuf-c.c +++ b/lib/logsrv/protobuf-c.c @@ -312,10 +312,8 @@ int32_size(int32_t v) static inline uint32_t zigzag32(int32_t v) { - if (v < 0) - return (-(uint32_t)v) * 2 - 1; - else - return (uint32_t)(v) * 2; + // Note: Using unsigned types prevents undefined behavior + return ((uint32_t)v << 1) ^ -((uint32_t)v >> 31); } /** @@ -377,10 +375,8 @@ uint64_size(uint64_t v) static inline uint64_t zigzag64(int64_t v) { - if (v < 0) - return (-(uint64_t)v) * 2 - 1; - else - return (uint64_t)(v) * 2; + // Note: Using unsigned types prevents undefined behavior + return ((uint64_t)v << 1) ^ -((uint64_t)v >> 63); } /** @@ -800,7 +796,8 @@ uint32_pack(uint32_t value, uint8_t *out) } /** - * Pack a signed 32-bit integer and return the number of bytes written. + * Pack a signed 32-bit integer and return the number of bytes written, + * passed as unsigned to avoid implementation-specific behavior. * Negative numbers are encoded as two's complement 64-bit integers. * * \param value @@ -811,14 +808,14 @@ uint32_pack(uint32_t value, uint8_t *out) * Number of bytes written to `out`. */ static inline size_t -int32_pack(int32_t value, uint8_t *out) +int32_pack(uint32_t value, uint8_t *out) { - if (value < 0) { + if ((int32_t)value < 0) { out[0] = value | 0x80; out[1] = (value >> 7) | 0x80; out[2] = (value >> 14) | 0x80; out[3] = (value >> 21) | 0x80; - out[4] = (value >> 28) | 0x80; + out[4] = (value >> 28) | 0xf0; out[5] = out[6] = out[7] = out[8] = 0xff; out[9] = 0x01; return 10; @@ -2423,10 +2420,8 @@ parse_int32(unsigned len, const uint8_t *data) static inline int32_t unzigzag32(uint32_t v) { - if (v & 1) - return -(v >> 1) - 1; - else - return v >> 1; + // Note: Using unsigned types prevents undefined behavior + return (int32_t)((v >> 1) ^ -(v & 1)); } static inline uint32_t @@ -2467,10 +2462,8 @@ parse_uint64(unsigned len, const uint8_t *data) static inline int64_t unzigzag64(uint64_t v) { - if (v & 1) - return -(v >> 1) - 1; - else - return v >> 1; + // Note: Using unsigned types prevents undefined behavior + return (int64_t)((v >> 1) ^ -(v & 1)); } static inline uint64_t