xref: /netbsd-src/crypto/external/bsd/openssl/dist/include/internal/endian.h (revision b0d1725196a7921d003d2c66a14f186abda4176b)
1*b0d17251Schristos /*
2*b0d17251Schristos  * Copyright 2019-2021 The OpenSSL Project Authors. All Rights Reserved.
3*b0d17251Schristos  *
4*b0d17251Schristos  * Licensed under the Apache License 2.0 (the "License").  You may not use
5*b0d17251Schristos  * this file except in compliance with the License.  You can obtain a copy
6*b0d17251Schristos  * in the file LICENSE in the source distribution or at
7*b0d17251Schristos  * https://www.openssl.org/source/license.html
8*b0d17251Schristos  */
9*b0d17251Schristos 
10*b0d17251Schristos #ifndef OSSL_INTERNAL_ENDIAN_H
11*b0d17251Schristos # define OSSL_INTERNAL_ENDIAN_H
12*b0d17251Schristos # pragma once
13*b0d17251Schristos 
14*b0d17251Schristos /*
15*b0d17251Schristos  * IS_LITTLE_ENDIAN and IS_BIG_ENDIAN can be used to detect the endiannes
16*b0d17251Schristos  * at compile time. To use it, DECLARE_IS_ENDIAN must be used to declare
17*b0d17251Schristos  * a variable.
18*b0d17251Schristos  *
19*b0d17251Schristos  * L_ENDIAN and B_ENDIAN can be used at preprocessor time. They can be set
20*b0d17251Schristos  * in the configarion using the lib_cppflags variable. If neither is
21*b0d17251Schristos  * set, it will fall back to code works with either endianness.
22*b0d17251Schristos  */
23*b0d17251Schristos 
24*b0d17251Schristos # if defined(__BYTE_ORDER__) && defined(__ORDER_LITTLE_ENDIAN__)
25*b0d17251Schristos #  define DECLARE_IS_ENDIAN const int ossl_is_little_endian = __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
26*b0d17251Schristos #  define IS_LITTLE_ENDIAN (ossl_is_little_endian)
27*b0d17251Schristos #  define IS_BIG_ENDIAN (!ossl_is_little_endian)
28*b0d17251Schristos #  if defined(L_ENDIAN) && (__BYTE_ORDER__ != __ORDER_LITTLE_ENDIAN__)
29*b0d17251Schristos #   error "L_ENDIAN defined on a big endian machine"
30*b0d17251Schristos #  endif
31*b0d17251Schristos #  if defined(B_ENDIAN) && (__BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__)
32*b0d17251Schristos #   error "B_ENDIAN defined on a little endian machine"
33*b0d17251Schristos #  endif
34*b0d17251Schristos #  if !defined(L_ENDIAN) && (__BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__)
35*b0d17251Schristos #   define L_ENDIAN
36*b0d17251Schristos #  endif
37*b0d17251Schristos #  if !defined(B_ENDIAN) && (__BYTE_ORDER__ != __ORDER_LITTLE_ENDIAN__)
38*b0d17251Schristos #   define B_ENDIAN
39*b0d17251Schristos #  endif
40*b0d17251Schristos # else
41*b0d17251Schristos #  define DECLARE_IS_ENDIAN \
42*b0d17251Schristos     const union { \
43*b0d17251Schristos         long one; \
44*b0d17251Schristos         char little; \
45*b0d17251Schristos     } ossl_is_endian = { 1 }
46*b0d17251Schristos 
47*b0d17251Schristos #  define IS_LITTLE_ENDIAN (ossl_is_endian.little != 0)
48*b0d17251Schristos #  define IS_BIG_ENDIAN    (ossl_is_endian.little == 0)
49*b0d17251Schristos # endif
50*b0d17251Schristos 
51*b0d17251Schristos #endif
52