OLD | NEW |
(Empty) | |
| 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. |
| 4 |
| 5 #include "components/rappor/sample.h" |
| 6 |
| 7 #include <map> |
| 8 #include <string> |
| 9 |
| 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" |
| 16 |
| 17 namespace rappor { |
| 18 |
| 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); |
| 25 } |
| 26 |
| 27 Sample::~Sample() { |
| 28 } |
| 29 |
| 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, |
| 36 bloom_offset_, |
| 37 value); |
| 38 sizes_[field_name] = parameters_.bloom_filter_size_bytes; |
| 39 } |
| 40 |
| 41 void Sample::SetFlagsField(const std::string& field_name, |
| 42 uint64_t flags, |
| 43 size_t num_flags) { |
| 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; |
| 50 } |
| 51 |
| 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 uint64_t size = it->second; |
| 60 ByteVector value_bytes(size); |
| 61 for (size_t i = 0; i < size; i++) { |
| 62 // Get the value of the i-th smallest byte and copy it to the byte vector. |
| 63 uint64_t shift = i * 8; |
| 64 uint64_t byte_mask = 0xff << shift; |
| 65 value_bytes[i] = (value & byte_mask) >> shift; |
| 66 } |
| 67 ByteVector report_bytes = internal::GenerateReport( |
| 68 secret, parameters_, value_bytes); |
| 69 |
| 70 RapporReports::Report* report = reports->add_report(); |
| 71 report->set_name_hash(metrics::HashMetricName( |
| 72 metric_name + "." + kv.first)); |
| 73 report->set_bits(std::string(report_bytes.begin(), report_bytes.end())); |
| 74 } |
| 75 } |
| 76 |
| 77 } // namespace rappor |
OLD | NEW |