xref: /haiku/headers/compatibility/bsd/endian.h (revision c42868a015daa160e093679b2637b1cf9f0b26ba)
1 /*
2  * Copyright 2017 Haiku, Inc. All rights reserved.
3  * Distributed under the terms of the MIT License.
4  */
5 #ifndef _BSD_ENDIAN_H_
6 #define _BSD_ENDIAN_H_
7 
8 
9 #include_next <endian.h>
10 
11 
12 #ifdef _BSD_SOURCE
13 
14 #include <config/HaikuConfig.h>
15 #include <support/ByteOrder.h>
16 #include <support/SupportDefs.h>
17 
18 #ifdef __cplusplus
19 extern "C" {
20 #endif
21 
22 /*
23  * General byte order swapping functions.
24  */
25 #define	bswap16(x)	__swap_int16(x)
26 #define	bswap32(x)	__swap_int32(x)
27 #define	bswap64(x)	__swap_int64(x)
28 
29 /*
30  * Host to big endian, host to little endian, big endian to host, and little
31  * endian to host byte order functions as detailed in byteorder(9).
32  */
33 #if BYTE_ORDER == LITTLE_ENDIAN
34 #define	htobe16(x)	bswap16((x))
35 #define	htobe32(x)	bswap32((x))
36 #define	htobe64(x)	bswap64((x))
37 #define	htole16(x)	((uint16_t)(x))
38 #define	htole32(x)	((uint32_t)(x))
39 #define	htole64(x)	((uint64_t)(x))
40 
41 #define	be16toh(x)	bswap16((x))
42 #define	be32toh(x)	bswap32((x))
43 #define	be64toh(x)	bswap64((x))
44 #define	le16toh(x)	((uint16_t)(x))
45 #define	le32toh(x)	((uint32_t)(x))
46 #define	le64toh(x)	((uint64_t)(x))
47 #else /* BYTE_ORDER != LITTLE_ENDIAN */
48 #define	htobe16(x)	((uint16_t)(x))
49 #define	htobe32(x)	((uint32_t)(x))
50 #define	htobe64(x)	((uint64_t)(x))
51 #define	htole16(x)	bswap16((x))
52 #define	htole32(x)	bswap32((x))
53 #define	htole64(x)	bswap64((x))
54 
55 #define	be16toh(x)	((uint16_t)(x))
56 #define	be32toh(x)	((uint32_t)(x))
57 #define	be64toh(x)	((uint64_t)(x))
58 #define	le16toh(x)	bswap16((x))
59 #define	le32toh(x)	bswap32((x))
60 #define	le64toh(x)	bswap64((x))
61 #endif /* BYTE_ORDER == LITTLE_ENDIAN */
62 
63 /* Alignment-agnostic encode/decode bytestream to/from little/big endian. */
64 
65 static __inline uint32_t
66 be32dec(const void *pp)
67 {
68 	uint8_t const *p = (uint8_t const *)pp;
69 
70 	return (((unsigned)p[0] << 24) | (p[1] << 16) | (p[2] << 8) | p[3]);
71 }
72 
73 static __inline uint64_t
74 be64dec(const void *pp)
75 {
76 	uint8_t const *p = (uint8_t const *)pp;
77 
78 	return (((uint64_t)be32dec(p) << 32) | be32dec(p + 4));
79 }
80 
81 static __inline void
82 be32enc(void *pp, uint32_t u)
83 {
84 	uint8_t *p = (uint8_t *)pp;
85 
86 	p[0] = (u >> 24) & 0xff;
87 	p[1] = (u >> 16) & 0xff;
88 	p[2] = (u >> 8) & 0xff;
89 	p[3] = u & 0xff;
90 }
91 
92 static __inline void
93 be64enc(void *pp, uint64_t u)
94 {
95 	uint8_t *p = (uint8_t *)pp;
96 
97 	be32enc(p, (uint32_t)(u >> 32));
98 	be32enc(p + 4, (uint32_t)(u & 0xffffffffU));
99 }
100 
101 #ifdef __cplusplus
102 }
103 #endif
104 
105 
106 #endif
107 
108 
109 #endif	/* _BSD_ENDIAN_H_ */
110