xref: /openbmc/qemu/include/exec/tswap.h (revision 7d87775f)
1 /*
2  * Macros for swapping a value if the endianness is different
3  * between the target and the host.
4  *
5  * SPDX-License-Identifier: LGPL-2.1-or-later
6  */
7 
8 #ifndef TSWAP_H
9 #define TSWAP_H
10 
11 #include "qemu/bswap.h"
12 
13 /**
14  * target_words_bigendian:
15  * Returns true if the (default) endianness of the target is big endian,
16  * false otherwise. Note that in target-specific code, you can use
17  * TARGET_BIG_ENDIAN directly instead. On the other hand, common
18  * code should normally never need to know about the endianness of the
19  * target, so please do *not* use this function unless you know very well
20  * what you are doing!
21  */
22 bool target_words_bigendian(void);
23 
24 /*
25  * If we're in target-specific code, we can hard-code the swapping
26  * condition, otherwise we have to do (slower) run-time checks.
27  */
28 #ifdef COMPILING_PER_TARGET
29 #define target_needs_bswap()  (HOST_BIG_ENDIAN != TARGET_BIG_ENDIAN)
30 #else
31 #define target_needs_bswap()  (HOST_BIG_ENDIAN != target_words_bigendian())
32 #endif /* COMPILING_PER_TARGET */
33 
34 static inline uint16_t tswap16(uint16_t s)
35 {
36     if (target_needs_bswap()) {
37         return bswap16(s);
38     } else {
39         return s;
40     }
41 }
42 
43 static inline uint32_t tswap32(uint32_t s)
44 {
45     if (target_needs_bswap()) {
46         return bswap32(s);
47     } else {
48         return s;
49     }
50 }
51 
52 static inline uint64_t tswap64(uint64_t s)
53 {
54     if (target_needs_bswap()) {
55         return bswap64(s);
56     } else {
57         return s;
58     }
59 }
60 
61 static inline void tswap16s(uint16_t *s)
62 {
63     if (target_needs_bswap()) {
64         *s = bswap16(*s);
65     }
66 }
67 
68 static inline void tswap32s(uint32_t *s)
69 {
70     if (target_needs_bswap()) {
71         *s = bswap32(*s);
72     }
73 }
74 
75 static inline void tswap64s(uint64_t *s)
76 {
77     if (target_needs_bswap()) {
78         *s = bswap64(*s);
79     }
80 }
81 
82 #endif  /* TSWAP_H */
83