From f6842f2a4211e3a4977adea49d3d23a4367b67b6 Mon Sep 17 00:00:00 2001 From: jason7708 Date: Tue, 24 Sep 2024 23:48:44 +0800 Subject: [PATCH] [mph] fix mph::to undefined behavior --- mph | 15 ++++++++------- 1 file changed, 8 insertions(+), 7 deletions(-) diff --git a/mph b/mph index 330d07c..2c4adb0 100644 --- a/mph +++ b/mph @@ -774,20 +774,21 @@ template }(); } #endif - T t; - #pragma GCC diagnostic push - #pragma GCC diagnostic ignored "-Warray-bounds" - __builtin_memcpy(&t, data.data(), sizeof(t)); - #pragma GCC diagnostic pop + T t{}; + __builtin_memcpy(&t, data.data(), data.size() < sizeof(t) ? data.size() : sizeof(t)); const auto index = T(data.size() * __CHAR_BIT__); #ifdef __BMI2__ if constexpr (sizeof(t) <= sizeof(u32)) { return __builtin_ia32_bzhi_si(t, index); } else if constexpr (sizeof(t) <= sizeof(u64)) { return __builtin_ia32_bzhi_di(t, index); - } else + } else { + #endif + constexpr T size = sizeof(T) * __CHAR_BIT__; + return index >= size ? t : t & ((T(1) << index) - T(1)); + #ifdef __BMI2__ + } #endif - return t & ((T(1) << index) - T(1)); } } else { // unsafe #pragma GCC diagnostic push