1 // Copyright 2014 the V8 project authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 #include "include/v8stdint.h"
6 #include "src/base/flags.h"
7 #include "testing/gtest/include/gtest/gtest.h"
8 
9 namespace v8 {
10 namespace base {
11 
12 namespace {
13 
14 enum Flag1 {
15   kFlag1None = 0,
16   kFlag1First = 1u << 1,
17   kFlag1Second = 1u << 2,
18   kFlag1All = kFlag1None | kFlag1First | kFlag1Second
19 };
20 typedef Flags<Flag1> Flags1;
21 
22 
DEFINE_OPERATORS_FOR_FLAGS(Flags1)23 DEFINE_OPERATORS_FOR_FLAGS(Flags1)
24 
25 
26 Flags1 bar(Flags1 flags1) { return flags1; }
27 
28 }  // namespace
29 
30 
TEST(FlagsTest,BasicOperations)31 TEST(FlagsTest, BasicOperations) {
32   Flags1 a;
33   EXPECT_EQ(kFlag1None, static_cast<int>(a));
34   a |= kFlag1First;
35   EXPECT_EQ(kFlag1First, static_cast<int>(a));
36   a = a | kFlag1Second;
37   EXPECT_EQ(kFlag1All, static_cast<int>(a));
38   a &= kFlag1Second;
39   EXPECT_EQ(kFlag1Second, static_cast<int>(a));
40   a = kFlag1None & a;
41   EXPECT_EQ(kFlag1None, static_cast<int>(a));
42   a ^= (kFlag1All | kFlag1None);
43   EXPECT_EQ(kFlag1All, static_cast<int>(a));
44   Flags1 b = ~a;
45   EXPECT_EQ(kFlag1All, static_cast<int>(a));
46   EXPECT_EQ(~static_cast<int>(a), static_cast<int>(b));
47   Flags1 c = a;
48   EXPECT_EQ(a, c);
49   EXPECT_NE(a, b);
50   EXPECT_EQ(a, bar(a));
51   EXPECT_EQ(a, bar(kFlag1All));
52 }
53 
54 
55 namespace {
56 namespace foo {
57 
58 enum Option {
59   kNoOptions = 0,
60   kOption1 = 1,
61   kOption2 = 2,
62   kAllOptions = kNoOptions | kOption1 | kOption2
63 };
64 typedef Flags<Option> Options;
65 
66 }  // namespace foo
67 
68 
69 DEFINE_OPERATORS_FOR_FLAGS(foo::Options)
70 
71 }  // namespace
72 
73 
TEST(FlagsTest,NamespaceScope)74 TEST(FlagsTest, NamespaceScope) {
75   foo::Options options;
76   options ^= foo::kNoOptions;
77   options |= foo::kOption1 | foo::kOption2;
78   EXPECT_EQ(foo::kAllOptions, static_cast<int>(options));
79 }
80 
81 
82 namespace {
83 
84 struct Foo {
85   enum Enum { kEnum1 = 1, kEnum2 = 2 };
86   typedef Flags<Enum, uint32_t> Enums;
87 };
88 
89 
90 DEFINE_OPERATORS_FOR_FLAGS(Foo::Enums)
91 
92 }  // namespace
93 
94 
TEST(FlagsTest,ClassScope)95 TEST(FlagsTest, ClassScope) {
96   Foo::Enums enums;
97   enums |= Foo::kEnum1;
98   enums |= Foo::kEnum2;
99   EXPECT_TRUE(enums & Foo::kEnum1);
100   EXPECT_TRUE(enums & Foo::kEnum2);
101 }
102 
103 }  // namespace base
104 }  // namespace v8
105