xref: /freebsd/contrib/libfido2/openbsd-compat/endian_win32.c (revision 7ef62cebc2f965b0f640263e179276928885e33d)
1 /*
2  * Copyright (c) 2020 Yubico AB. All rights reserved.
3  * Use of this source code is governed by a BSD-style
4  * license that can be found in the LICENSE file.
5  */
6 
7 #include "openbsd-compat.h"
8 
9 #if defined(_WIN32) && !defined(HAVE_ENDIAN_H)
10 
11 /*
12  * Hopefully, if the endianness differs from the end result, the compiler
13  * optimizes these functions with some type of bswap instruction. Or,
14  * otherwise, to just return the input value unmodified. GCC and clang
15  * both does these optimization at least. This should be preferred over
16  * relying on some BYTE_ORDER macro, which may or may not be defined.
17  */
18 
19 uint32_t
20 htole32(uint32_t in)
21 {
22 	uint32_t	 out = 0;
23 	uint8_t		*b = (uint8_t *)&out;
24 
25 	b[0] = (uint8_t)((in >> 0)  & 0xff);
26 	b[1] = (uint8_t)((in >> 8)  & 0xff);
27 	b[2] = (uint8_t)((in >> 16) & 0xff);
28 	b[3] = (uint8_t)((in >> 24) & 0xff);
29 
30 	return (out);
31 }
32 
33 uint64_t
34 htole64(uint64_t in)
35 {
36 	uint64_t	 out = 0;
37 	uint8_t		*b = (uint8_t *)&out;
38 
39 	b[0] = (uint8_t)((in >> 0)  & 0xff);
40 	b[1] = (uint8_t)((in >> 8)  & 0xff);
41 	b[2] = (uint8_t)((in >> 16) & 0xff);
42 	b[3] = (uint8_t)((in >> 24) & 0xff);
43 	b[4] = (uint8_t)((in >> 32) & 0xff);
44 	b[5] = (uint8_t)((in >> 40) & 0xff);
45 	b[6] = (uint8_t)((in >> 48) & 0xff);
46 	b[7] = (uint8_t)((in >> 56) & 0xff);
47 
48 	return (out);
49 }
50 
51 #endif /* WIN32 && !HAVE_ENDIAN_H */
52