From 65701fe00700577f9f4e9b96d682bd7cfcc0b76e Mon Sep 17 00:00:00 2001 From: Nemanja Trifunovic Date: Sat, 11 Jan 2025 11:09:19 -0500 Subject: [PATCH] Compile time checks for size of UTF-16 code units --- source/utf8/core.h | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/source/utf8/core.h b/source/utf8/core.h index 627133c..af22969 100644 --- a/source/utf8/core.h +++ b/source/utf8/core.h @@ -43,9 +43,14 @@ DEALINGS IN THE SOFTWARE. #if UTF_CPP_CPLUSPLUS >= 201103L // C++ 11 or later #define UTF_CPP_OVERRIDE override #define UTF_CPP_NOEXCEPT noexcept + #define UTF_CPP_STATIC_ASSERT(condition) static_assert(condition, "UTFCPP static assert"); #else // C++ 98/03 #define UTF_CPP_OVERRIDE #define UTF_CPP_NOEXCEPT throw() + // Simulate static_assert: + template struct StaticAssert {static void assert() {int static_assert_impl[(Condition ? 1 : -1)];} }; + template <> struct StaticAssert {static void assert() {}}; + #define UTF_CPP_STATIC_ASSERT(condition) StaticAssert::assert(); #endif // C++ 11 or later @@ -308,6 +313,10 @@ namespace internal template utf_error validate_next16(word_iterator& it, word_iterator end, utfchar32_t& code_point) { + // Make sure the iterator dereferences a large enough type + typedef typename std::iterator_traits::value_type word_type; + UTF_CPP_STATIC_ASSERT(sizeof(word_type) >= sizeof(utfchar16_t)); + // Check the edge case: if (it == end) return NOT_ENOUGH_ROOM; // Save the original value of it so we can go back in case of failure @@ -395,6 +404,7 @@ namespace internal // the word_type. template word_iterator append16(utfchar32_t cp, word_iterator result) { + UTF_CPP_STATIC_ASSERT(sizeof(word_type) >= sizeof(utfchar16_t)); if (is_in_bmp(cp)) *(result++) = static_cast(cp); else {