summaryrefslogtreecommitdiff
path: root/libc/src/__support/CPP/bitset.h
diff options
context:
space:
mode:
authorGuillaume Chatelet <gchatelet@google.com>2022-08-19 21:39:02 +0000
committerGuillaume Chatelet <gchatelet@google.com>2022-08-19 21:39:14 +0000
commite2d79758436b690d3cc5c3bf79cba2c2b280ce80 (patch)
treef1258621f0fd43f92bf4747153d43ebeb4e5480e /libc/src/__support/CPP/bitset.h
parent9e1a4ce0b55db1388351550497e5ce43b588f71c (diff)
[libc][NFC] Use STL case for bitset and simplify implementation
Diffstat (limited to 'libc/src/__support/CPP/bitset.h')
-rw-r--r--libc/src/__support/CPP/bitset.h40
1 files changed, 40 insertions, 0 deletions
diff --git a/libc/src/__support/CPP/bitset.h b/libc/src/__support/CPP/bitset.h
new file mode 100644
index 000000000000..0791e26d2c90
--- /dev/null
+++ b/libc/src/__support/CPP/bitset.h
@@ -0,0 +1,40 @@
+//===-- A self contained equivalent of std::bitset --------------*- C++ -*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_LIBC_SRC_SUPPORT_CPP_BITSET_H
+#define LLVM_LIBC_SRC_SUPPORT_CPP_BITSET_H
+
+#include <stddef.h> // For size_t.
+
+namespace __llvm_libc::cpp {
+
+template <size_t NumberOfBits> struct bitset {
+ static_assert(NumberOfBits != 0,
+ "Cannot create a __llvm_libc::cpp::bitset of size 0.");
+
+ constexpr void set(size_t Index) {
+ Data[Index / BITS_PER_UNIT] |= mask(Index);
+ }
+
+ constexpr bool test(size_t Index) const {
+ return Data[Index / BITS_PER_UNIT] & mask(Index);
+ }
+
+private:
+ static constexpr size_t BITS_PER_BYTE = 8;
+ static constexpr size_t BITS_PER_UNIT = BITS_PER_BYTE * sizeof(size_t);
+
+ static inline size_t mask(size_t Index) {
+ return size_t{1} << (Index % BITS_PER_UNIT);
+ }
+ size_t Data[(NumberOfBits + BITS_PER_UNIT - 1) / BITS_PER_UNIT] = {0};
+};
+
+} // namespace __llvm_libc::cpp
+
+#endif // LLVM_LIBC_SRC_SUPPORT_CPP_BITSET_H