Skip to content

Commit 2a249a7

Browse files
Treehugger RobotAndroid (Google) Code Review
authored andcommitted
Merge "Easier ftl::Flags construction" into main
2 parents d7e9d2a + 83c6f9e commit 2a249a7

2 files changed

Lines changed: 23 additions & 1 deletion

File tree

include/ftl/flags.h

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@
2222
#include <bitset>
2323
#include <cstdint>
2424
#include <iterator>
25+
#include <initializer_list>
2526
#include <string>
2627
#include <type_traits>
2728

@@ -40,6 +41,7 @@ class Flags {
4041

4142
public:
4243
constexpr Flags(F f) : mFlags(static_cast<U>(f)) {}
44+
constexpr Flags(std::initializer_list<F> fs) : mFlags(combine(fs)) {}
4345
constexpr Flags() : mFlags(0) {}
4446
constexpr Flags(const Flags<F>& f) : mFlags(f.mFlags) {}
4547

@@ -197,6 +199,14 @@ class Flags {
197199
private:
198200
U mFlags;
199201

202+
static constexpr U combine(std::initializer_list<F> fs) {
203+
U result = 0;
204+
for (const F f : fs) {
205+
result |= static_cast<U>(f);
206+
}
207+
return result;
208+
}
209+
200210
static void appendFlag(std::string& str, const std::string_view& flag, bool& first) {
201211
if (first) {
202212
first = false;

libs/ftl/flags_test.cpp

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@
1717
#include <ftl/flags.h>
1818
#include <gtest/gtest.h>
1919

20-
#include <type_traits>
20+
#include <initializer_list>
2121

2222
namespace android::test {
2323

@@ -59,6 +59,18 @@ TEST(Flags, All) {
5959
ASSERT_FALSE(flags.all(TestFlags::ONE | TestFlags::TWO | TestFlags::THREE));
6060
}
6161

62+
TEST(Flags, ImplicitConstructionAndAssignmentFromInitializerList) {
63+
Flags<TestFlags> flags = {TestFlags::ONE, TestFlags::THREE};
64+
ASSERT_TRUE(flags.test(TestFlags::ONE));
65+
ASSERT_FALSE(flags.test(TestFlags::TWO));
66+
ASSERT_TRUE(flags.test(TestFlags::THREE));
67+
68+
flags = {};
69+
ASSERT_FALSE(flags.test(TestFlags::ONE));
70+
ASSERT_FALSE(flags.test(TestFlags::TWO));
71+
ASSERT_FALSE(flags.test(TestFlags::THREE));
72+
}
73+
6274
TEST(Flags, DefaultConstructor_hasNoFlagsSet) {
6375
Flags<TestFlags> flags;
6476
ASSERT_FALSE(flags.any(TestFlags::ONE | TestFlags::TWO | TestFlags::THREE));

0 commit comments

Comments
 (0)