File: bitset.cc

package info (click to toggle)
chromium 139.0.7258.127-1
  • links: PTS, VCS
  • area: main
  • in suites:
  • size: 6,122,068 kB
  • sloc: cpp: 35,100,771; ansic: 7,163,530; javascript: 4,103,002; python: 1,436,920; asm: 946,517; xml: 746,709; pascal: 187,653; perl: 88,691; sh: 88,436; objc: 79,953; sql: 51,488; cs: 44,583; fortran: 24,137; makefile: 22,147; tcl: 15,277; php: 13,980; yacc: 8,984; ruby: 7,485; awk: 3,720; lisp: 3,096; lex: 1,327; ada: 727; jsp: 228; sed: 36
file content (67 lines) | stat: -rw-r--r-- 2,002 bytes parent folder | download | duplicates (6)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
// Copyright 2024 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "components/ukm/bitset.h"

#include <cstring>

#include "base/check_op.h"
#include "base/containers/span.h"

namespace ukm {

BitSet::BitSet(size_t set_size) : set_size_(set_size) {
  CHECK_GT(set_size_, 0U);
  bitset_.resize(1 + (set_size_ - 1) / 8);
}

BitSet::BitSet(size_t set_size, std::string_view data) : BitSet(set_size) {
  // Copy the passed `data` to the end of the internal `bitset_`. For example,
  // if `data` is {0xAA, 0xBB}, and set_size is 32 (so `bitset_` is a vector of
  // 4 uint8_t's), then the final `bitset_` should be {0x00, 0x00, 0xAA, 0xBB}.
  base::span(bitset_).last(data.size()).copy_from(base::as_byte_span((data)));
}

BitSet::~BitSet() = default;

void BitSet::Add(size_t index) {
  CHECK_LT(index, set_size_);
  size_t internal_index = ToInternalIndex(index);
  uint8_t bitmask = ToBitmask(index);
  bitset_[internal_index] |= bitmask;
}

bool BitSet::Contains(size_t index) const {
  CHECK_LT(index, set_size_);
  size_t internal_index = ToInternalIndex(index);
  uint8_t bitmask = ToBitmask(index);
  return (bitset_[internal_index] & bitmask) != 0;
}

std::string BitSet::Serialize() const {
  // Since the bitset is stored from right to left, as an optimization, omit all
  // the leftmost 0's.
  size_t offset;
  for (offset = 0; offset < bitset_.size(); ++offset) {
    if (bitset_[offset] != 0) {
      break;
    }
  }

  base::span<const char> s =
      base::as_chars(base::span(bitset_).subspan(offset));
  return std::string(s.begin(), s.end());
}

size_t BitSet::ToInternalIndex(size_t index) const {
  // Note: internally, the bitset is stored from right to left. For example,
  // index 0 maps to the least significant bit of the last element of `bitset_`.
  return bitset_.size() - 1 - index / 8;
}

uint8_t BitSet::ToBitmask(size_t index) const {
  return 1 << (index % 8);
}

}  // namespace ukm