blob: 005ce6e329db282c2432b952d6e6143925836f7a [file] [log] [blame]
Luc Nguyen2e41b682024-03-13 22:43:301// 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 Pazdf291ec52024-03-20 12:38:048#include <cstdint>
Luc Nguyen2e41b682024-03-13 22:43:309#include <string>
10#include <vector>
11
12#include "base/component_export.h"
13
14namespace 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.
20class 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_