1 /*
2 * Copyright (C) 2016 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 #ifndef _GTS_NANOAPPS_SHARED_NANO_ENDIAN_H_
18 #define _GTS_NANOAPPS_SHARED_NANO_ENDIAN_H_
19
20 // If the platform has no endian.h, then have the build system set
21 // CHRE_NO_ENDIAN_H, and set __BYTE_ORDER, __LITTLE_ENDIAN, and
22 // __BIG_ENDIAN appropriately.
23 #ifndef CHRE_NO_ENDIAN_H
24 #include <endian.h>
25 #endif
26
27 #include <cstddef>
28 #include <cstdint>
29
30 #if !(defined(__BYTE_ORDER) && defined(__LITTLE_ENDIAN) && \
31 defined(__BIG_ENDIAN))
32 #error \
33 "Need to define the preprocessor defines __BYTE_ORDER, __LITTLE_ENDIAN" \
34 " and __BIG_ENDIAN."
35 #endif
36
37 #if __LITTLE_ENDIAN == __BIG_ENDIAN
38 #error "__LITTLE_ENDIAN and __BIG_ENDIAN must have different values."
39 #endif
40
41 #if ((__BYTE_ORDER != __LITTLE_ENDIAN) && (__BYTE_ORDER != __BIG_ENDIAN))
42 #error "__BYTE_ORDER must be either __LITTLE_ENDIAN or __BIG_ENDIAN."
43 #endif
44
45 namespace nanoapp_testing {
46
47 void swapBytes(uint8_t *bytes, size_t size);
48
49 // Note: The 'static' with these 'inline' methods is required for our
50 // unit tests to work, since they compile this header with different
51 // endianness. Without the 'static', we'll just use the first version
52 // of this we compile with, and fail some of the tests.
53
54 template <typename T>
hostToLittleEndian(T value)55 static inline T hostToLittleEndian(T value) {
56 #if (__BYTE_ORDER == __BIG_ENDIAN)
57 swapBytes(reinterpret_cast<uint8_t *>(&value), sizeof(T));
58 #endif
59 return value;
60 }
61
62 template <typename T>
littleEndianToHost(T value)63 static inline T littleEndianToHost(T value) {
64 // This has identical behavior to hostToLittleEndian. We provide both
65 // so code reads more cleanly.
66 return hostToLittleEndian(value);
67 }
68
69 } // namespace nanoapp_testing
70
71 #endif // _GTS_NANOAPPS_SHARED_NANO_ENDIAN_H_
72