[flang-commits] [flang] [flang] Fix UTF-8 minimality checks (PR #159142)

Peter Klausler via flang-commits flang-commits at lists.llvm.org
Tue Sep 16 11:23:55 PDT 2025


================
@@ -158,21 +158,24 @@ DecodedCharacter DecodeRawCharacter<Encoding::UTF_8>(
     const char *cp, std::size_t bytes) {
   auto p{reinterpret_cast<const std::uint8_t *>(cp)};
   char32_t ch{*p};
-  if (ch <= 0x7f) {
+  // Valid UTF-8 encodings must be minimal.
+  if (ch <= 0x7f) { // 1 byte: 7 bits of payload
     return {ch, 1};
-  } else if ((ch & 0xf8) == 0xf0 && bytes >= 4 && ch > 0xf0 &&
-      ((p[1] | p[2] | p[3]) & 0xc0) == 0x80) {
+  } else if ((ch & 0xf8) == 0xf0 && bytes >= 4 &&
+      ((p[1] | p[2] | p[3]) & 0xc0) == 0x80 && (ch > 0xf0 || p[1] > 0x8f)) {
----------------
klausler wrote:

The second and later bytes of a UTF-8 encoding sequence are always values in the range 0x80 to 0xbf.  Their least significant six bits carry their 6-bit payloads.  A four-byte UTF-8 sequence has 21 bits of payload: three bits in the first byte, and six bits in each of the next three bytes.  Since a 3-byte UTF-8 sequence has 16 bits of payload, a minimal four-byte UTF-8 sequence must have at least one of its most significant five (21-16) payload bits set.  These five most significant payload bits are encoded as the three least significant bits of the first byte and as the 0x20 and 0x10 bits of the second byte.  So either the first byte (in the range 0xf0-0xf7) has to be greater than 0xf0, or the second byte (in the range 0x80-0xbf) has to be greater than 0x8f.

https://github.com/llvm/llvm-project/pull/159142


More information about the flang-commits mailing list