xref: /freebsd/contrib/libfido2/openbsd-compat/endian_win32.c (revision 2ccfa855b2fc331819953e3de1b1c15ce5b95a7e)
10afa8e06SEd Maste /*
20afa8e06SEd Maste  * Copyright (c) 2020 Yubico AB. All rights reserved.
30afa8e06SEd Maste  * Use of this source code is governed by a BSD-style
40afa8e06SEd Maste  * license that can be found in the LICENSE file.
5*2ccfa855SEd Maste  * SPDX-License-Identifier: BSD-2-Clause
60afa8e06SEd Maste  */
70afa8e06SEd Maste 
80afa8e06SEd Maste #include "openbsd-compat.h"
90afa8e06SEd Maste 
100afa8e06SEd Maste #if defined(_WIN32) && !defined(HAVE_ENDIAN_H)
110afa8e06SEd Maste 
120afa8e06SEd Maste /*
130afa8e06SEd Maste  * Hopefully, if the endianness differs from the end result, the compiler
140afa8e06SEd Maste  * optimizes these functions with some type of bswap instruction. Or,
150afa8e06SEd Maste  * otherwise, to just return the input value unmodified. GCC and clang
160afa8e06SEd Maste  * both does these optimization at least. This should be preferred over
170afa8e06SEd Maste  * relying on some BYTE_ORDER macro, which may or may not be defined.
180afa8e06SEd Maste  */
190afa8e06SEd Maste 
200afa8e06SEd Maste uint32_t
htole32(uint32_t in)210afa8e06SEd Maste htole32(uint32_t in)
220afa8e06SEd Maste {
230afa8e06SEd Maste 	uint32_t	 out = 0;
240afa8e06SEd Maste 	uint8_t		*b = (uint8_t *)&out;
250afa8e06SEd Maste 
260afa8e06SEd Maste 	b[0] = (uint8_t)((in >> 0)  & 0xff);
270afa8e06SEd Maste 	b[1] = (uint8_t)((in >> 8)  & 0xff);
280afa8e06SEd Maste 	b[2] = (uint8_t)((in >> 16) & 0xff);
290afa8e06SEd Maste 	b[3] = (uint8_t)((in >> 24) & 0xff);
300afa8e06SEd Maste 
310afa8e06SEd Maste 	return (out);
320afa8e06SEd Maste }
330afa8e06SEd Maste 
340afa8e06SEd Maste uint64_t
htole64(uint64_t in)350afa8e06SEd Maste htole64(uint64_t in)
360afa8e06SEd Maste {
370afa8e06SEd Maste 	uint64_t	 out = 0;
380afa8e06SEd Maste 	uint8_t		*b = (uint8_t *)&out;
390afa8e06SEd Maste 
400afa8e06SEd Maste 	b[0] = (uint8_t)((in >> 0)  & 0xff);
410afa8e06SEd Maste 	b[1] = (uint8_t)((in >> 8)  & 0xff);
420afa8e06SEd Maste 	b[2] = (uint8_t)((in >> 16) & 0xff);
430afa8e06SEd Maste 	b[3] = (uint8_t)((in >> 24) & 0xff);
440afa8e06SEd Maste 	b[4] = (uint8_t)((in >> 32) & 0xff);
450afa8e06SEd Maste 	b[5] = (uint8_t)((in >> 40) & 0xff);
460afa8e06SEd Maste 	b[6] = (uint8_t)((in >> 48) & 0xff);
470afa8e06SEd Maste 	b[7] = (uint8_t)((in >> 56) & 0xff);
480afa8e06SEd Maste 
490afa8e06SEd Maste 	return (out);
500afa8e06SEd Maste }
510afa8e06SEd Maste 
520afa8e06SEd Maste #endif /* WIN32 && !HAVE_ENDIAN_H */
53