swap.h 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. /* Interface to byteswapping functions.
  2. Copyright (C) 2006-2022 Free Software Foundation, Inc.
  3. This file is part of libctf.
  4. libctf is free software; you can redistribute it and/or modify it under
  5. the terms of the GNU General Public License as published by the Free
  6. Software Foundation; either version 3, or (at your option) any later
  7. version.
  8. This program is distributed in the hope that it will be useful, but
  9. WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
  11. See the GNU General Public License for more details.
  12. You should have received a copy of the GNU General Public License
  13. along with this program; see the file COPYING. If not see
  14. <http://www.gnu.org/licenses/>. */
  15. #ifndef _CTF_SWAP_H
  16. #define _CTF_SWAP_H
  17. #include "config.h"
  18. #include <stdint.h>
  19. #include <assert.h>
  20. #ifdef HAVE_BYTESWAP_H
  21. #include <byteswap.h>
  22. #endif /* defined(HAVE_BYTESWAP_H) */
  23. /* Provide our own versions of the byteswap functions. */
  24. #if !HAVE_DECL_BSWAP_16
  25. static inline uint16_t
  26. bswap_16 (uint16_t v)
  27. {
  28. return ((v >> 8) & 0xff) | ((v & 0xff) << 8);
  29. }
  30. #endif /* !HAVE_DECL_BSWAP16 */
  31. #if !HAVE_DECL_BSWAP_32
  32. static inline uint32_t
  33. bswap_32 (uint32_t v)
  34. {
  35. return ( ((v & 0xff000000) >> 24)
  36. | ((v & 0x00ff0000) >> 8)
  37. | ((v & 0x0000ff00) << 8)
  38. | ((v & 0x000000ff) << 24));
  39. }
  40. #endif /* !HAVE_DECL_BSWAP32 */
  41. #if !HAVE_DECL_BSWAP_64
  42. static inline uint64_t
  43. bswap_64 (uint64_t v)
  44. {
  45. return ( ((v & 0xff00000000000000ULL) >> 56)
  46. | ((v & 0x00ff000000000000ULL) >> 40)
  47. | ((v & 0x0000ff0000000000ULL) >> 24)
  48. | ((v & 0x000000ff00000000ULL) >> 8)
  49. | ((v & 0x00000000ff000000ULL) << 8)
  50. | ((v & 0x0000000000ff0000ULL) << 24)
  51. | ((v & 0x000000000000ff00ULL) << 40)
  52. | ((v & 0x00000000000000ffULL) << 56));
  53. }
  54. #endif /* !HAVE_DECL_BSWAP64 */
  55. /* < C11? define away static assertions. */
  56. #if !defined (__STDC_VERSION__) || __STDC_VERSION__ < 201112L
  57. #define _Static_assert(cond, err)
  58. #endif
  59. /* Swap the endianness of something. */
  60. #define swap_thing(x) \
  61. do \
  62. { \
  63. _Static_assert (sizeof (x) == 1 || (sizeof (x) % 2 == 0 \
  64. && sizeof (x) <= 8), \
  65. "Invalid size, update endianness code"); \
  66. switch (sizeof (x)) { \
  67. case 2: x = bswap_16 (x); break; \
  68. case 4: x = bswap_32 (x); break; \
  69. case 8: x = bswap_64 (x); break; \
  70. case 1: /* Nothing needs doing */ \
  71. break; \
  72. } \
  73. } \
  74. while (0);
  75. #endif /* !defined(_CTF_SWAP_H) */