Update mojo sdk to rev c02a28868825edfa57ab77947b8cb15e741c5598
[chromium-blink-merge.git] / components / rappor / sample.cc
blobf72ba2842269c66858d6b090a344cc4211091cb7
1 // Copyright 2015 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "components/rappor/sample.h"
7 #include <map>
8 #include <string>
10 #include "base/logging.h"
11 #include "components/metrics/metrics_hashes.h"
12 #include "components/rappor/bloom_filter.h"
13 #include "components/rappor/byte_vector_utils.h"
14 #include "components/rappor/proto/rappor_metric.pb.h"
15 #include "components/rappor/reports.h"
17 namespace rappor {
19 Sample::Sample(int32_t cohort_seed, const RapporParameters& parameters)
20 : parameters_(parameters),
21 bloom_offset_((cohort_seed % parameters_.num_cohorts) *
22 parameters_.bloom_filter_hash_function_count) {
23 // Must use bloom filter size that fits in uint64.
24 DCHECK_LE(parameters_.bloom_filter_size_bytes, 8);
27 Sample::~Sample() {
30 void Sample::SetStringField(const std::string& field_name,
31 const std::string& value) {
32 DVLOG(2) << "Recording sample \"" << value
33 << "\" for sample metric field \"" << field_name << "\"";
34 DCHECK_EQ(0u, sizes_[field_name]);
35 fields_[field_name] = internal::GetBloomBits(
36 parameters_.bloom_filter_size_bytes,
37 parameters_.bloom_filter_hash_function_count,
38 bloom_offset_,
39 value);
40 sizes_[field_name] = parameters_.bloom_filter_size_bytes;
43 void Sample::SetFlagsField(const std::string& field_name,
44 uint64_t flags,
45 size_t num_flags) {
46 DVLOG(2) << "Recording flags " << flags
47 << " for sample metric field \"" << field_name << "\"";
48 DCHECK_EQ(0u, sizes_[field_name]);
49 DCHECK_GT(num_flags, 0u);
50 DCHECK_LE(num_flags, 64u);
51 DCHECK(num_flags == 64u || flags >> num_flags == 0);
52 fields_[field_name] = flags;
53 sizes_[field_name] = (num_flags + 7) / 8;
56 void Sample::ExportMetrics(const std::string& secret,
57 const std::string& metric_name,
58 RapporReports* reports) const {
59 for (const auto& kv : fields_) {
60 uint64_t value = kv.second;
61 const auto it = sizes_.find(kv.first);
62 DCHECK(it != sizes_.end());
63 size_t size = it->second;
64 ByteVector value_bytes(size);
65 Uint64ToByteVector(value, size, &value_bytes);
66 ByteVector report_bytes = internal::GenerateReport(
67 secret, parameters_, value_bytes);
69 RapporReports::Report* report = reports->add_report();
70 report->set_name_hash(metrics::HashMetricName(
71 metric_name + "." + kv.first));
72 report->set_bits(std::string(report_bytes.begin(), report_bytes.end()));
73 DVLOG(2) << "Exporting sample " << metric_name << "." << kv.first;
77 } // namespace rappor