1 // Copyright 2012 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 #include "base/metrics/bucket_ranges.h" 6 7 #include <cmath> 8 9 #include "base/containers/span.h" 10 #include "base/metrics/crc32.h" 11 12 namespace base { 13 BucketRanges(size_t num_ranges)14BucketRanges::BucketRanges(size_t num_ranges) 15 : ranges_(num_ranges, 0), 16 checksum_(0) {} 17 18 BucketRanges::~BucketRanges() = default; 19 CalculateChecksum() const20uint32_t BucketRanges::CalculateChecksum() const { 21 // Crc of empty ranges_ happens to be 0. This early exit prevents trying to 22 // take the address of ranges_[0] which will fail for an empty vector even 23 // if that address is never used. 24 const size_t ranges_size = ranges_.size(); 25 if (ranges_size == 0) 26 return 0; 27 28 // Checksum is seeded with the ranges "size". 29 return Crc32(static_cast<uint32_t>(ranges_size), base::as_byte_span(ranges_)); 30 } 31 HasValidChecksum() const32bool BucketRanges::HasValidChecksum() const { 33 return CalculateChecksum() == checksum_; 34 } 35 ResetChecksum()36void BucketRanges::ResetChecksum() { 37 checksum_ = CalculateChecksum(); 38 } 39 Equals(const BucketRanges * other) const40bool BucketRanges::Equals(const BucketRanges* other) const { 41 if (checksum_ != other->checksum_) 42 return false; 43 if (ranges_.size() != other->ranges_.size()) 44 return false; 45 for (size_t index = 0; index < ranges_.size(); ++index) { 46 if (ranges_[index] != other->ranges_[index]) 47 return false; 48 } 49 return true; 50 } 51 52 } // namespace base 53