Line data Source code
1 : /*
2 : *
3 : * Copyright (c) 2021 Project CHIP Authors
4 : * All rights reserved.
5 : *
6 : * Licensed under the Apache License, Version 2.0 (the "License");
7 : * you may not use this file except in compliance with the License.
8 : * You may obtain a copy of the License at
9 : *
10 : * http://www.apache.org/licenses/LICENSE-2.0
11 : *
12 : * Unless required by applicable law or agreed to in writing, software
13 : * distributed under the License is distributed on an "AS IS" BASIS,
14 : * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 : * See the License for the specific language governing permissions and
16 : * limitations under the License.
17 : */
18 :
19 : #pragma once
20 :
21 : #include <cstdint>
22 : #include <lib/support/TypeTraits.h>
23 :
24 : namespace chip {
25 : namespace Access {
26 :
27 : // Using bitfield values so privilege set and auth mode can be stored together.
28 : // Privilege set can have more than one value expressed (e.g. View,
29 : // ProxyView, and Operate).
30 : // NOTE: Every time this enum class changes, we need to update the constexpr
31 : // "kAllPrivilegeBits" below.
32 : enum class Privilege : uint8_t
33 : {
34 : kView = 1 << 0,
35 : kProxyView = 1 << 1,
36 : kOperate = 1 << 2,
37 : kManage = 1 << 3,
38 : kAdminister = 1 << 4
39 : };
40 :
41 : // Constant expression that contains all the values
42 : // defined inside the enum class "Privilege", and only those values.
43 : constexpr uint8_t kAllPrivilegeBits = //
44 : static_cast<uint8_t>(Privilege::kView) | //
45 : static_cast<uint8_t>(Privilege::kProxyView) | //
46 : static_cast<uint8_t>(Privilege::kOperate) | //
47 : static_cast<uint8_t>(Privilege::kManage) | //
48 : static_cast<uint8_t>(Privilege::kAdminister);
49 :
50 : /*
51 : * Checks if a Privilege enum class value is valid.
52 : *
53 : * A valid privilege must:
54 : * 1. Not be zero (zero doesn't map to any defined privilege)
55 : * 2. Contain only bits that match defined privileges (see kAllPrivilegeBits)
56 : * 3. Have exactly one bit set (it must be a single privilege, not a combination)
57 : *
58 : */
59 20414 : constexpr bool IsValidPrivilege(Access::Privilege privilege)
60 : {
61 20414 : uint8_t privilegeValue = to_underlying(privilege);
62 :
63 40828 : return (privilegeValue != 0) && ((privilegeValue & kAllPrivilegeBits) == privilegeValue) &&
64 40828 : ((privilegeValue & (privilegeValue - 1)) == 0);
65 : }
66 :
67 : static_assert(IsValidPrivilege(Privilege::kView));
68 : static_assert(IsValidPrivilege(Privilege::kProxyView));
69 : static_assert(IsValidPrivilege(Privilege::kOperate));
70 : static_assert(IsValidPrivilege(Privilege::kManage));
71 : static_assert(IsValidPrivilege(Privilege::kAdminister));
72 :
73 : } // namespace Access
74 : } // namespace chip
|