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"
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"
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);
30 void Sample::SetStringField(const std::string
& field_name
,
31 const std::string
& value
) {
32 DCHECK_EQ(0u, sizes_
[field_name
]);
33 fields_
[field_name
] = internal::GetBloomBits(
34 parameters_
.bloom_filter_size_bytes
,
35 parameters_
.bloom_filter_hash_function_count
,
38 sizes_
[field_name
] = parameters_
.bloom_filter_size_bytes
;
41 void Sample::SetFlagsField(const std::string
& field_name
,
44 DCHECK_EQ(0u, sizes_
[field_name
]);
45 DCHECK_GT(num_flags
, 0u);
46 DCHECK_LE(num_flags
, 64u);
47 DCHECK(num_flags
== 64u || flags
>> num_flags
== 0);
48 fields_
[field_name
] = flags
;
49 sizes_
[field_name
] = (num_flags
+ 7) / 8;
52 void Sample::ExportMetrics(const std::string
& secret
,
53 const std::string
& metric_name
,
54 RapporReports
* reports
) const {
55 for (const auto& kv
: fields_
) {
56 uint64_t value
= kv
.second
;
57 const auto it
= sizes_
.find(kv
.first
);
58 DCHECK(it
!= sizes_
.end());
59 size_t size
= it
->second
;
60 ByteVector
value_bytes(size
);
61 Uint64ToByteVector(value
, size
, &value_bytes
);
62 ByteVector report_bytes
= internal::GenerateReport(
63 secret
, parameters_
, value_bytes
);
65 RapporReports::Report
* report
= reports
->add_report();
66 report
->set_name_hash(metrics::HashMetricName(
67 metric_name
+ "." + kv
.first
));
68 report
->set_bits(std::string(report_bytes
.begin(), report_bytes
.end()));