From 7096ea82f9cbde709f1c3db6e0e74f737f197d06 Mon Sep 17 00:00:00 2001 From: Tim Ledbetter Date: Wed, 25 Oct 2023 21:52:26 +0100 Subject: [PATCH] LibGfx: Use `count_leading_zeroes` to calculate nearest power of 2 This removes the possibility of an infinite loop. --- Userland/Libraries/LibGfx/Font/WOFF/Font.cpp | 7 +++---- Userland/Libraries/LibGfx/Font/WOFF2/Font.cpp | 7 +++---- 2 files changed, 6 insertions(+), 8 deletions(-) diff --git a/Userland/Libraries/LibGfx/Font/WOFF/Font.cpp b/Userland/Libraries/LibGfx/Font/WOFF/Font.cpp index 38a7e2c0e4..cebd901acc 100644 --- a/Userland/Libraries/LibGfx/Font/WOFF/Font.cpp +++ b/Userland/Libraries/LibGfx/Font/WOFF/Font.cpp @@ -63,10 +63,9 @@ static constexpr u32 WOFF_SIGNATURE = 0x774F4646; static u16 pow_2_less_than_or_equal(u16 x) { - u16 result = 1; - while (result < x) - result <<= 1; - return result; + VERIFY(x > 0); + VERIFY(x < 32769); + return 1 << (sizeof(u16) * 8 - count_leading_zeroes(x - 1)); } ErrorOr> Font::try_load_from_file(DeprecatedString path, unsigned int index) diff --git a/Userland/Libraries/LibGfx/Font/WOFF2/Font.cpp b/Userland/Libraries/LibGfx/Font/WOFF2/Font.cpp index fd24061e16..f3f7c2cb62 100644 --- a/Userland/Libraries/LibGfx/Font/WOFF2/Font.cpp +++ b/Userland/Libraries/LibGfx/Font/WOFF2/Font.cpp @@ -111,10 +111,9 @@ static i16 be_i16(u8 const* ptr) static u16 pow_2_less_than_or_equal(u16 x) { - u16 result = 1; - while (result < x) - result <<= 1; - return result; + VERIFY(x > 0); + VERIFY(x < 32769); + return 1 << (sizeof(u16) * 8 - count_leading_zeroes(x - 1)); } enum class TransformationVersion {