Luc Nguyen | 2e41b68 | 2024-03-13 22:43:30 | [diff] [blame] | 1 | // Copyright 2024 The Chromium Authors |
| 2 | // Use of this source code is governed by a BSD-style license that can be |
| 3 | // found in the LICENSE file. |
| 4 | |
| 5 | #ifndef COMPONENTS_UKM_BITSET_H_ |
| 6 | #define COMPONENTS_UKM_BITSET_H_ |
| 7 | |
Jose Dapena Paz | df291ec5 | 2024-03-20 12:38:04 | [diff] [blame] | 8 | #include <cstdint> |
Luc Nguyen | 2e41b68 | 2024-03-13 22:43:30 | [diff] [blame] | 9 | #include <string> |
| 10 | #include <vector> |
| 11 | |
| 12 | #include "base/component_export.h" |
| 13 | |
| 14 | namespace ukm { |
| 15 | |
| 16 | // A custom bitset class used to keep track of web feature usage across |
| 17 | // sources in UKM. `std::bitset<>` and `base::EnumSet<>` are intentionally not |
| 18 | // used because they do not provide the flexibility needed to efficiently |
| 19 | // serialize/deserialize the set. |
| 20 | class COMPONENT_EXPORT(UKM_RECORDER) BitSet { |
| 21 | public: |
| 22 | // Creates an empty BitSet with specified `set_size`. |
| 23 | explicit BitSet(size_t set_size); |
| 24 | // Constructor to recreate a serialized bitset (provided as `data`). |
| 25 | BitSet(size_t set_size, std::string_view data); |
| 26 | |
| 27 | BitSet(const BitSet&) = delete; |
| 28 | BitSet& operator=(const BitSet&) = delete; |
| 29 | |
| 30 | ~BitSet(); |
| 31 | |
| 32 | // Adds the given `index` to the bitset. |
| 33 | void Add(size_t index); |
| 34 | // Returns whether the given `index` is present in the bitset. |
| 35 | bool Contains(size_t index) const; |
| 36 | |
| 37 | // Serializes `this` and returns the compressed value. The bitset can be |
| 38 | // recreated with the `BitSet(size_t, std::string_view)` constructor. |
| 39 | std::string Serialize() const; |
| 40 | |
| 41 | private: |
| 42 | // Returns which element `index` maps to in `bitset_`. |
| 43 | size_t ToInternalIndex(size_t index) const; |
| 44 | // Returns which bit `index` maps to given a certain `bitset_` element. |
| 45 | uint8_t ToBitmask(size_t index) const; |
| 46 | |
| 47 | const size_t set_size_; |
| 48 | std::vector<uint8_t> bitset_; |
| 49 | }; |
| 50 | |
| 51 | } // namespace ukm |
| 52 | |
| 53 | #endif // COMPONENTS_UKM_BITSET_H_ |