On 2026-03-16 10:37, Lasse Collin wrote:
if the memcpy examples used exact-width types for "value", then
the code would compile if CHAR_BIT == 8 && sizeof(uint_least16_t) == 2,
and otherwise fail to compile. The return type can still be a _leastN_t.

Thanks for pointing out the problem. Of course the issue is mostly theoretical, but an even better fix is to change the code so that it compiles and runs correctly even on platforms that lack exact-width types like uint16_t. Done via the attached patch.
From d6885b09a30d831ccdb3961d1f9895961ece436e Mon Sep 17 00:00:00 2001
From: Paul Eggert <[email protected]>
Date: Mon, 16 Mar 2026 12:18:23 -0700
Subject: [PATCH] =?UTF-8?q?stdbit-h:=20don=E2=80=99t=20memcpy=20on=20oddba?=
 =?UTF-8?q?ll=20hosts?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

Mostly-theoretical problem reported by Lasse Collin in:
https://lists.gnu.org/r/bug-gnulib/2026-03/msg00135.html
* lib/stdbit.in.h (_GL_STDBIT_OPTIMIZE_VIA_MEMCPY):
Do not define to 1 on oddball hosts.
---
 ChangeLog       |  6 ++++++
 lib/stdbit.in.h | 11 +++++++++--
 2 files changed, 15 insertions(+), 2 deletions(-)

diff --git a/ChangeLog b/ChangeLog
index 314b7b1374..aefe29a107 100644
--- a/ChangeLog
+++ b/ChangeLog
@@ -1,5 +1,11 @@
 2026-03-16  Paul Eggert  <[email protected]>
 
+	stdbit-h: don’t memcpy on oddball hosts
+	Mostly-theoretical problem reported by Lasse Collin in:
+	https://lists.gnu.org/r/bug-gnulib/2026-03/msg00135.html
+	* lib/stdbit.in.h (_GL_STDBIT_OPTIMIZE_VIA_MEMCPY):
+	Do not define to 1 on oddball hosts.
+
 	stdbit-h: be clearer about castless conversion
 	* lib/stdbit.in.h (stdc_load8_beu16, stdc_load8_beu32)
 	(stdc_load8_beu64, stdc_load8_leu16, stdc_load8_leu32)
diff --git a/lib/stdbit.in.h b/lib/stdbit.in.h
index 54df8f3690..a16eb8067d 100644
--- a/lib/stdbit.in.h
+++ b/lib/stdbit.in.h
@@ -1387,7 +1387,7 @@ stdc_memreverse8u64 (uint_least64_t value)
 
 /* ISO C2y § 7.18.21 Endian-Aware 8-Bit Load  */
 
-/* On hosts where _GL_STDBIT_OPTIMIZE_VIA_MEMCPY might be useful,
+/* On hosts where _GL_STDBIT_OPTIMIZE_VIA_MEMCPY (see below) might be useful,
    we need to avoid type-punning, because the compiler's aliasing
    analysis would frequently produce incorrect code, and requiring the
    option '-fno-strict-aliasing' is no viable solution.
@@ -1501,7 +1501,14 @@ stdc_memreverse8u64 (uint_least64_t value)
 #endif
 
 #if defined _GL_HAS_BUILTIN_ASSUME_ALIGNED || defined _MSC_VER
-# define _GL_STDBIT_OPTIMIZE_VIA_MEMCPY 1
+/* The _GL_STDBIT_OPTIMIZE_VIA_MEMCPY trick works on typical hosts
+   where CHAR_BIT == 8 and uint_leastN_t types have minimal sizes.
+   Check to be safe and to document the assumption.  */
+# define _GL_STDBIT_OPTIMIZE_VIA_MEMCPY \
+   ((unsigned char) -1 == 0xFF \
+    && sizeof (uint_least16_t) == 2 \
+    && sizeof (uint_least32_t) == 4 \
+    && sizeof (uint_least64_t) == 8)
 #endif
 
 #ifndef _GL_STDBIT_OPTIMIZE_VIA_MEMCPY
-- 
2.53.0

Reply via email to