main netmisc / compat / sys / endian.h
  1/*	$NetBSD: endian.h,v 1.39 2026/01/08 15:39:08 nia Exp $	*/
  2
  3#ifndef _SYS_ENDIAN_H_
  4#define _SYS_ENDIAN_H_
  5
  6#include <stdint.h>
  7#include <endian.h>
  8#include <byteswap.h>
  9#include <sys/cdefs.h>
 10
 11#define	_LITTLE_ENDIAN	1234
 12#define	_BIG_ENDIAN	4321
 13#define	_PDP_ENDIAN	3412
 14
 15#ifndef LITTLE_ENDIAN
 16#define	LITTLE_ENDIAN	_LITTLE_ENDIAN
 17#endif
 18#ifndef BIG_ENDIAN
 19#define	BIG_ENDIAN	_BIG_ENDIAN
 20#endif
 21#ifndef PDP_ENDIAN
 22#define	PDP_ENDIAN	_PDP_ENDIAN
 23#endif
 24
 25#ifndef BYTE_ORDER
 26#if __BYTE_ORDER == __LITTLE_ENDIAN
 27#define	BYTE_ORDER	LITTLE_ENDIAN
 28#else
 29#define	BYTE_ORDER	BIG_ENDIAN
 30#endif
 31#endif
 32
 33#ifndef bswap16
 34#define bswap16 bswap_16
 35#endif
 36
 37#ifndef bswap32
 38#define bswap32 bswap_32
 39#endif
 40
 41#ifndef bswap64
 42#define bswap64 bswap_64
 43#endif
 44
 45#if BYTE_ORDER == BIG_ENDIAN
 46#ifndef htobe16
 47#define htobe16(x)	__CAST(uint16_t, (x))
 48#endif
 49#ifndef htobe32
 50#define htobe32(x)	__CAST(uint32_t, (x))
 51#endif
 52#ifndef htobe64
 53#define htobe64(x)	__CAST(uint64_t, (x))
 54#endif
 55#ifndef htole16
 56#define htole16(x)	bswap16(__CAST(uint16_t, (x)))
 57#endif
 58#ifndef htole32
 59#define htole32(x)	bswap32(__CAST(uint32_t, (x)))
 60#endif
 61#ifndef htole64
 62#define htole64(x)	bswap64(__CAST(uint64_t, (x)))
 63#endif
 64#else
 65#ifndef htobe16
 66#define htobe16(x)	bswap16(__CAST(uint16_t, (x)))
 67#endif
 68#ifndef htobe32
 69#define htobe32(x)	bswap32(__CAST(uint32_t, (x)))
 70#endif
 71#ifndef htobe64
 72#define htobe64(x)	bswap64(__CAST(uint64_t, (x)))
 73#endif
 74#ifndef htole16
 75#define htole16(x)	__CAST(uint16_t, (x))
 76#endif
 77#ifndef htole32
 78#define htole32(x)	__CAST(uint32_t, (x))
 79#endif
 80#ifndef htole64
 81#define htole64(x)	__CAST(uint64_t, (x))
 82#endif
 83#endif
 84
 85#ifndef be16toh
 86#define be16toh(x)	htobe16(x)
 87#endif
 88#ifndef be32toh
 89#define be32toh(x)	htobe32(x)
 90#endif
 91#ifndef be64toh
 92#define be64toh(x)	htobe64(x)
 93#endif
 94#ifndef le16toh
 95#define le16toh(x)	htole16(x)
 96#endif
 97#ifndef le32toh
 98#define le32toh(x)	htole32(x)
 99#endif
100#ifndef le64toh
101#define le64toh(x)	htole64(x)
102#endif
103
104static __inline uint16_t NETCOMPAT_UNUSED
105be16dec(const void *_buf)
106{
107	uint16_t u;
108
109	__builtin_memcpy(&u, _buf, sizeof(u));
110	return be16toh(u);
111}
112
113static __inline uint16_t NETCOMPAT_UNUSED
114le16dec(const void *_buf)
115{
116	uint16_t u;
117
118	__builtin_memcpy(&u, _buf, sizeof(u));
119	return le16toh(u);
120}
121
122static __inline uint32_t NETCOMPAT_UNUSED
123be32dec(const void *_buf)
124{
125	uint32_t u;
126
127	__builtin_memcpy(&u, _buf, sizeof(u));
128	return be32toh(u);
129}
130
131static __inline uint32_t NETCOMPAT_UNUSED
132le32dec(const void *_buf)
133{
134	uint32_t u;
135
136	__builtin_memcpy(&u, _buf, sizeof(u));
137	return le32toh(u);
138}
139
140#endif