File: bitset_unittest.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 (57 lines) | stat: -rw-r--r-- 1,967 bytes parent folder | download | duplicates (9)
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
// 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 "testing/gtest/include/gtest/gtest.h"

namespace ukm {

TEST(UkmBitSet, BitSet) {
  constexpr size_t kBitSetSize = 32;

  // Create a bitset and verify that it is initially empty.
  BitSet bitset1(kBitSetSize);
  for (size_t i = 0; i < kBitSetSize; ++i) {
    EXPECT_FALSE(bitset1.Contains(i));
  }
  EXPECT_TRUE(bitset1.Serialize().empty());

  // Add some elements to the bitset, and verify they can be looked up.
  bitset1.Add(0);
  bitset1.Add(14);
  for (size_t i = 0; i < kBitSetSize; ++i) {
    EXPECT_EQ(bitset1.Contains(i), i == 0 || i == 14);
  }

  // Serialize the bitset. The trailing zeros should be optimized away, and the
  // resulting output should fit in 2 bytes (0b01000000 and 0b00000001).
  std::string serialized = bitset1.Serialize();
  EXPECT_EQ(serialized.size(), 2U);
  EXPECT_EQ(static_cast<uint8_t>(serialized[0]), 0b01000000);
  EXPECT_EQ(static_cast<uint8_t>(serialized[1]), 0b00000001);

  // Create a new bitset using the serialized data and verify that it contains
  // the same data.
  BitSet bitset2(kBitSetSize, serialized);
  for (size_t i = 0; i < kBitSetSize; ++i) {
    EXPECT_EQ(bitset1.Contains(i), bitset2.Contains(i));
  }

  // Do some last few checks for good measure.
  bitset2.Add(31);
  // Adding the same element a second time should have no impact.
  bitset2.Add(31);
  for (size_t i = 0; i < kBitSetSize; ++i) {
    EXPECT_EQ(bitset2.Contains(i), i == 0 || i == 14 || i == 31);
  }
  serialized = bitset2.Serialize();
  EXPECT_EQ(serialized.size(), 4U);
  EXPECT_EQ(static_cast<uint8_t>(serialized[0]), 0b10000000);
  EXPECT_EQ(static_cast<uint8_t>(serialized[1]), 0b00000000);
  EXPECT_EQ(static_cast<uint8_t>(serialized[2]), 0b01000000);
  EXPECT_EQ(static_cast<uint8_t>(serialized[3]), 0b00000001);
}

}  // namespace ukm