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
31 #if !(defined(__BYTE_ORDER) && defined(__LITTLE_ENDIAN) && \
32 defined(__BIG_ENDIAN))
33 #error "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
46 namespace nanoapp_testing {
47
48 void swapBytes(uint8_t *bytes, size_t size);
49
50 // Note: The 'static' with these 'inline' methods is required for our
51 // unit tests to work, since they compile this header with different
52 // endianness. Without the 'static', we'll just use the first version
53 // of this we compile with, and fail some of the tests.
54
55 template<typename T>
hostToLittleEndian(T * value)56 static inline void hostToLittleEndian(T *value) {
57 #if (__BYTE_ORDER == __BIG_ENDIAN)
58 swapBytes(reinterpret_cast<uint8_t*>(value), sizeof(T));
59 #else
60 // Nothing to do for little endian machines.
61 (void)value;
62 #endif
63 }
64
65 template<typename T>
littleEndianToHost(T * value)66 static inline void littleEndianToHost(T *value) {
67 // This has identical behavior to hostToLittleEndian. We provide both
68 // so code reads more cleanly.
69 hostToLittleEndian(value);
70 }
71
72 } // namespace nanoapp_testing
73
74 #endif // _GTS_NANOAPPS_SHARED_NANO_ENDIAN_H_
75