Android-cuttlefish cvd tool
cf_endian.h
Go to the documentation of this file.
1//
2// Copyright (C) 2020 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#pragma once
17
18#if __has_include(<endian.h>)
19#include <endian.h> // IWYU pragma: export
20#else
21#include <android-base/endian.h> // IWYU pragma: export
22#endif
23#include <inttypes.h>
24
25// The utilities in android-base/endian.h still require the use of regular int
26// types to store values with any endianness, which requires the user to
27// remember to manually do the required conversions, which is prone to errors.
28// The types introduced here allow handling these values safely.
29
30namespace cuttlefish {
31
32#define DECLARE_TYPE(new_type, base_type, to_new, to_base) \
33 class new_type { \
34 public: \
35 new_type() = default; \
36 explicit new_type(base_type val) : inner_(to_new(val)) {} \
37 new_type(const new_type&) = default; \
38 new_type& operator=(const new_type& other) = default; \
39 volatile new_type& operator=(const new_type& other) volatile { \
40 inner_ = other.inner_; \
41 return *this; \
42 } \
43 base_type as_##base_type() const volatile { return to_base(inner_); } \
44 \
45 private: \
46 base_type inner_; \
47 }; \
48 static_assert(sizeof(new_type) == sizeof(base_type))
49
50DECLARE_TYPE(Le16, uint16_t, htole16, le16toh);
51DECLARE_TYPE(Le32, uint32_t, htole32, le32toh);
52DECLARE_TYPE(Le64, uint64_t, htole64, le64toh);
53DECLARE_TYPE(Be16, uint16_t, htobe16, be16toh);
54DECLARE_TYPE(Be32, uint32_t, htobe32, be32toh);
55DECLARE_TYPE(Be64, uint64_t, htobe64, be64toh);
56
57#undef DECLARE_TYPE
58
59} // namespace cuttlefish
Definition: alloc_driver.h:21
DECLARE_TYPE(Le16, uint16_t, htole16, le16toh)