blob: b7a4191347546acfd8324cee9d3e0c15fc498d81 [file] [log] [blame]
Thomas Huth24be3362023-04-11 20:34:17 +02001/*
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
Thomas Huth24be3362023-04-11 20:34:17 +020011#include "qemu/bswap.h"
12
Philippe Mathieu-Daudé42508262023-12-12 11:34:25 +010013/**
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 */
22bool target_words_bigendian(void);
23
Thomas Huth24be3362023-04-11 20:34:17 +020024/*
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 */
Philippe Mathieu-Daudé7d7a21b2023-06-13 16:29:11 +020028#ifdef COMPILING_PER_TARGET
Thomas Huth24be3362023-04-11 20:34:17 +020029#define target_needs_bswap() (HOST_BIG_ENDIAN != TARGET_BIG_ENDIAN)
30#else
31#define target_needs_bswap() (target_words_bigendian() != HOST_BIG_ENDIAN)
Philippe Mathieu-Daudé7d7a21b2023-06-13 16:29:11 +020032#endif /* COMPILING_PER_TARGET */
Thomas Huth24be3362023-04-11 20:34:17 +020033
34static 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
43static 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
52static 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
61static inline void tswap16s(uint16_t *s)
62{
63 if (target_needs_bswap()) {
64 *s = bswap16(*s);
65 }
66}
67
68static inline void tswap32s(uint32_t *s)
69{
70 if (target_needs_bswap()) {
71 *s = bswap32(*s);
72 }
73}
74
75static inline void tswap64s(uint64_t *s)
76{
77 if (target_needs_bswap()) {
78 *s = bswap64(*s);
79 }
80}
81
82#endif /* TSWAP_H */