endian.h 1.8 KB

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