Debian Codegraph @

include/platform/swap.h

raw
1 /*
2 * This file is part of the flashrom project.
3 *
4 * Copyright (C) 2009 Carl-Daniel Hailfinger
5 * Copyright (C) 2022 secunet Security Networks AG
6 * (written by Thomas Heijligen <[email protected])
7 *
8 * This program is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; version 2 of the License.
11 *
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
16 */
17
18 /*
19 * inline functions and macros shared by endian conversion functions
20 */
21
22 #ifndef ___SWAP_H___
23 #define ___SWAP_H___ 1
24
25 #include <stdint.h>
26
27 /* swap bytes */
28 /* OpenBSD has conflicting definitions for swapX, _swap_X and __swapX */
29 static inline uint8_t ___swap8(const uint8_t value)
30 {
31 return (value & (uint8_t)0xffU);
32 }
33
34 static inline uint16_t ___swap16(const uint16_t value)
35 {
36 return ((value & (uint16_t)0x00ffU) << 8) |
37 ((value & (uint16_t)0xff00U) >> 8);
38 }
39
40 static inline uint32_t ___swap32(const uint32_t value)
41 {
42 return ((value & (uint32_t)0x000000ffUL) << 24) |
43 ((value & (uint32_t)0x0000ff00UL) << 8) |
44 ((value & (uint32_t)0x00ff0000UL) >> 8) |
45 ((value & (uint32_t)0xff000000UL) >> 24);
46 }
47
48 static inline uint64_t ___swap64(const uint64_t value)
49 {
50 return ((value & (uint64_t)0x00000000000000ffULL) << 56) |
51 ((value & (uint64_t)0x000000000000ff00ULL) << 40) |
52 ((value & (uint64_t)0x0000000000ff0000ULL) << 24) |
53 ((value & (uint64_t)0x00000000ff000000ULL) << 8) |
54 ((value & (uint64_t)0x000000ff00000000ULL) >> 8) |
55 ((value & (uint64_t)0x0000ff0000000000ULL) >> 24) |
56 ((value & (uint64_t)0x00ff000000000000ULL) >> 40) |
57 ((value & (uint64_t)0xff00000000000000ULL) >> 56);
58 }
59
60 /*
61 * macro to return the same value as passed.
62 *
63 * `___return_same(cpu_to_le, 8)`
64 * expands to
65 * `uint8_t cpu_to_le8 (const uint8_t value) { return value; }`
66 */
67 #define ___return_same(name, bits) \
68 uint##bits##_t name##bits (const uint##bits##_t value) { return value; }
69
70 /*
71 * macro to return the swapped value as passed.
72 *
73 * `___return_swapped(cpu_to_be, 8)`
74 * expands to
75 * `uint8_t cpu_to_be8 (const uint8_t value) { return ___swap8 (value); }`
76 */
77 #define ___return_swapped(name, bits) \
78 uint##bits##_t name##bits (const uint##bits##_t value) { return ___swap##bits (value); }
79
80 #endif /* !___SWAP_H___ */