1 /**
2  * Copyright (c) 2021-2024 Huawei Device Co., Ltd.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at
6  *
7  * http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15 
16 #include "bitset.h"
17 #include "securec.h"
18 
19 #include "macros.h"
20 
21 #include <cstring>
22 #include <utility>
23 
24 namespace ark::es2panda::util {
BitSet(size_t size)25 BitSet::BitSet(size_t size) : size_(size)
26 {
27     size_t dataSize = DataSize();
28     data_ = new uint8_t[dataSize];
29     memset_s(data_, dataSize, 0, dataSize);
30 }
31 
~BitSet()32 BitSet::~BitSet()
33 {
34     delete[] data_;
35 }
36 
37 size_t BitSet::DataSize() const noexcept
38 {
39     return (size_ >> SHIFT_OFFSET) + 1;
40 }
41 
42 void BitSet::Clear(bool value) noexcept
43 {
44     memset_s(data_, DataSize(), value ? ((sizeof(uint8_t) << 8U) - 1) : 0, DataSize());
45 }
46 
47 void BitSet::Set(size_t pos) noexcept
48 {
49     Set(pos, true);
50 }
51 
52 void BitSet::Set(size_t pos, bool value) noexcept
53 {
54     ASSERT(pos < size_);
55     size_t idx = pos >> SHIFT_OFFSET;
56     size_t slot = pos & SHIFT_MASK;
57 
58     if (value) {
59         data_[idx] |= 1U << slot;  // NOLINT(cppcoreguidelines-pro-bounds-pointer-arithmetic)
60     } else {
61         data_[idx] &= ~(1U << slot);  // NOLINT(cppcoreguidelines-pro-bounds-pointer-arithmetic)
62     }
63 }
64 
65 bool BitSet::Test(size_t pos) const noexcept
66 {
67     ASSERT(pos < size_);
68     size_t idx = pos >> SHIFT_OFFSET;
69     size_t slot = pos & SHIFT_MASK;
70 
71     return (data_[idx] & (1U << slot)) != 0;  // NOLINT(cppcoreguidelines-pro-bounds-pointer-arithmetic)
72 }
73 
74 bool BitSet::Any(bool value) const noexcept
75 {
76     for (uint32_t i = 0; i < size_; i++) {
77         if (Test(i) == value) {
78             return true;
79         }
80     }
81 
82     return false;
83 }
84 
85 bool BitSet::All(bool value) const noexcept
86 {
87     for (uint32_t i = 0; i < size_; i++) {
88         if (Test(i) != value) {
89             return false;
90         }
91     }
92 
93     return true;
94 }
95 }  // namespace ark::es2panda::util
96