Skip to content

Commit 23f7c36

Browse files
committed
Fix endianness conversions for u32, f32 and f64 types
Uses bswap64 by default to handle int64 and uint64 values. For float and doubles, uses appropriate-size bswap operators by first bit-casting floats and doubles to their same-size int types. Otherwise, they will be coerced to an int type before conversion and be returned as int values. Signed-off-by: Matt Leon <mattleon@google.com>
1 parent 66ea330 commit 23f7c36

1 file changed

Lines changed: 10 additions & 2 deletions

File tree

include/proxy-wasm/word.h

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -24,8 +24,16 @@ namespace proxy_wasm {
2424
// Use byteswap functions only when compiling for big-endian platforms.
2525
#if defined(__BYTE_ORDER__) && defined(__ORDER_BIG_ENDIAN__) && \
2626
__BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
27-
#define htowasm(x, vm_uses_wasm_byte_order) ((vm_uses_wasm_byte_order) ? __builtin_bswap32(x) : (x))
28-
#define wasmtoh(x, vm_uses_wasm_byte_order) ((vm_uses_wasm_byte_order) ? __builtin_bswap32(x) : (x))
27+
static inline float bswap(float x) {
28+
return std::bit_cast<float>(__builtin_bswap32(std::bit_cast<int32_t>(x)));
29+
}
30+
static inline double bswap(double x) {
31+
return std::bit_cast<double>(__builtin_bswap64(std::bit_cast<int64_t>(x)));
32+
}
33+
static inline uint32_t bswap(uint32_t x) { return __builtin_bswap32(x); }
34+
static inline auto bswap(auto x) { return __builtin_bswap64(x); }
35+
#define htowasm(x, vm_uses_wasm_byte_order) ((vm_uses_wasm_byte_order) ? bswap(x) : (x))
36+
#define wasmtoh(x, vm_uses_wasm_byte_order) ((vm_uses_wasm_byte_order) ? bswap(x) : (x))
2937
#else
3038
#define htowasm(x, vm_uses_wasm_byte_order) (x)
3139
#define wasmtoh(x, vm_uses_wasm_byte_order) (x)

0 commit comments

Comments
 (0)