]>
git.ipfire.org Git - thirdparty/binutils-gdb.git/blob - gdbsupport/packed.h
1 /* Copyright (C) 2022 Free Software Foundation, Inc.
3 This file is part of GDB.
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published by
7 the Free Software Foundation; either version 3 of the License, or
8 (at your option) any later version.
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU General Public License for more details.
15 You should have received a copy of the GNU General Public License
16 along with this program. If not, see <http://www.gnu.org/licenses/>. */
23 /* Each instantiation and full specialization of the packed template
24 defines a type that behaves like a given scalar type, but that has
25 byte alignment, and, may optionally have a smaller size than the
26 given scalar type. This is typically used as alternative to
27 bit-fields (and ENUM_BITFIELD), when the fields must have separate
28 memory locations to avoid data races. */
30 template<typename T
, size_t Bytes
= sizeof (T
)>
38 /* Ensure size and aligment are what we expect. */
39 gdb_static_assert (sizeof (packed
) == Bytes
);
40 gdb_static_assert (alignof (packed
) == 1);
42 /* Make sure packed can be wrapped with std::atomic. */
43 #if HAVE_IS_TRIVIALLY_COPYABLE
44 gdb_static_assert (std::is_trivially_copyable
<packed
>::value
);
46 gdb_static_assert (std::is_copy_constructible
<packed
>::value
);
47 gdb_static_assert (std::is_move_constructible
<packed
>::value
);
48 gdb_static_assert (std::is_copy_assignable
<packed
>::value
);
49 gdb_static_assert (std::is_move_assignable
<packed
>::value
);
52 operator T () const noexcept
58 T m_val
: (Bytes
* HOST_CHAR_BIT
) ATTRIBUTE_PACKED
;
61 /* Add some comparisons between std::atomic<packed<T>> and T. We need
62 this because the regular comparisons would require two implicit
63 conversions to go from T to std::atomic<packed<T>>:
66 packed<T> -> std::atomic<packed<T>>
68 and C++ only does one. */
70 template<typename T
, size_t Bytes
>
71 bool operator== (T lhs
, const std::atomic
<packed
<T
, Bytes
>> &rhs
)
73 return lhs
== rhs
.load ();
76 template<typename T
, size_t Bytes
>
77 bool operator== (const std::atomic
<packed
<T
, Bytes
>> &lhs
, T rhs
)
79 return lhs
.load () == rhs
;
82 template<typename T
, size_t Bytes
>
83 bool operator!= (T lhs
, const std::atomic
<packed
<T
, Bytes
>> &rhs
)
88 template<typename T
, size_t Bytes
>
89 bool operator!= (const std::atomic
<packed
<T
, Bytes
>> &lhs
, T rhs
)