]> wimlib.net Git - wimlib/commitdiff
Use memcpy() for unaligned accesses
authorEric Biggers <ebiggers3@gmail.com>
Fri, 22 May 2020 05:35:29 +0000 (22:35 -0700)
committerEric Biggers <ebiggers3@gmail.com>
Fri, 22 May 2020 05:42:40 +0000 (22:42 -0700)
For unaligned memory accesses, with modern compilers memcpy() is
compiled just as efficiently as __attribute__((packed)).  This also
avoids using a nonstandard extension and potentially running into the
gcc 10 bug https://gcc.gnu.org/bugzilla/show_bug.cgi?id=94994.

include/wimlib/unaligned.h

index 473f5e2578f4b88e7907ae4466f7e26371506c22..5700e405713c292be8a464bbe8563f617e21102e 100644 (file)
 #ifndef _WIMLIB_UNALIGNED_H
 #define _WIMLIB_UNALIGNED_H
 
+#include <string.h>
+
 #include "wimlib/compiler.h"
 #include "wimlib/endianness.h"
 #include "wimlib/types.h"
 
 #define DEFINE_UNALIGNED_TYPE(type)                            \
-struct type##_unaligned {                                      \
-       type v;                                                 \
-} _packed_attribute _may_alias_attribute;                      \
-                                                               \
 static forceinline type                                                \
 load_##type##_unaligned(const void *p)                         \
 {                                                              \
-       return ((const struct type##_unaligned *)p)->v;         \
+       type v;                                                 \
+       memcpy(&v, p, sizeof(v));                               \
+       return v;                                               \
 }                                                              \
                                                                \
 static forceinline void                                                \
-store_##type##_unaligned(type val, void *p)                    \
+store_##type##_unaligned(type v, void *p)                      \
 {                                                              \
-       ((struct type##_unaligned *)p)->v = val;                \
+       memcpy(p, &v, sizeof(v));                               \
 }
 
 DEFINE_UNALIGNED_TYPE(u16);