single_sample_metrics.cc 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. // Copyright 2017 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. #include "base/metrics/single_sample_metrics.h"
  5. #include "base/memory/ptr_util.h"
  6. #include "base/metrics/histogram.h"
  7. namespace base {
  8. static SingleSampleMetricsFactory* g_factory = nullptr;
  9. // static
  10. SingleSampleMetricsFactory* SingleSampleMetricsFactory::Get() {
  11. if (!g_factory)
  12. g_factory = new DefaultSingleSampleMetricsFactory();
  13. return g_factory;
  14. }
  15. // static
  16. void SingleSampleMetricsFactory::SetFactory(
  17. std::unique_ptr<SingleSampleMetricsFactory> factory) {
  18. DCHECK(!g_factory);
  19. g_factory = factory.release();
  20. }
  21. // static
  22. void SingleSampleMetricsFactory::DeleteFactoryForTesting() {
  23. DCHECK(g_factory);
  24. delete g_factory;
  25. g_factory = nullptr;
  26. }
  27. std::unique_ptr<SingleSampleMetric>
  28. DefaultSingleSampleMetricsFactory::CreateCustomCountsMetric(
  29. const std::string& histogram_name,
  30. HistogramBase::Sample min,
  31. HistogramBase::Sample max,
  32. uint32_t bucket_count) {
  33. return std::make_unique<DefaultSingleSampleMetric>(
  34. histogram_name, min, max, bucket_count,
  35. HistogramBase::kUmaTargetedHistogramFlag);
  36. }
  37. DefaultSingleSampleMetric::DefaultSingleSampleMetric(
  38. const std::string& histogram_name,
  39. HistogramBase::Sample min,
  40. HistogramBase::Sample max,
  41. uint32_t bucket_count,
  42. int32_t flags)
  43. : histogram_(Histogram::FactoryGet(histogram_name,
  44. min,
  45. max,
  46. bucket_count,
  47. flags)) {
  48. // Bad construction parameters may lead to |histogram_| being null; DCHECK to
  49. // find accidental errors in production. We must still handle the nullptr in
  50. // destruction though since this construction may come from another untrusted
  51. // process.
  52. DCHECK(histogram_);
  53. }
  54. DefaultSingleSampleMetric::~DefaultSingleSampleMetric() {
  55. // |histogram_| may be nullptr if bad construction parameters are given.
  56. if (sample_ < 0 || !histogram_)
  57. return;
  58. histogram_->Add(sample_);
  59. }
  60. void DefaultSingleSampleMetric::SetSample(HistogramBase::Sample sample) {
  61. DCHECK_GE(sample, 0);
  62. sample_ = sample;
  63. }
  64. } // namespace base