1 //
2 // Copyright (C) 2023 The Android Open Source Project
3 //
4 // Licensed under the Apache License, Version 2.0 (the "License");
5 // you may not use this file except in compliance with the License.
6 // You may obtain a copy of the License at
7 //
8 //      http://www.apache.org/licenses/LICENSE-2.0
9 //
10 // Unless required by applicable law or agreed to in writing, software
11 // distributed under the License is distributed on an "AS IS" BASIS,
12 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 // See the License for the specific language governing permissions and
14 // limitations under the License.
15 //
16 
17 #pragma once
18 #include <stdint.h>
19 
20 #include <memory>
21 
22 namespace android {
23 namespace expresslog {
24 
25 /** Histogram encapsulates StatsD write API calls */
26 class Histogram final {
27 public:
28     class BinOptions {
29     public:
30         virtual ~BinOptions() = default;
31         /**
32          * Returns bins count to be used by a Histogram
33          *
34          * @return bins count used to initialize Options, including overflow & underflow bins
35          */
36         virtual int getBinsCount() const = 0;
37 
38         /**
39          * @return zero based index
40          * Calculates bin index for the input sample value
41          * index == 0 stands for underflow
42          * index == getBinsCount() - 1 stands for overflow
43          */
44         virtual int getBinForSample(float sample) const = 0;
45     };
46 
47     /** Used by Histogram to map data sample to corresponding bin for uniform bins */
48     class UniformOptions : public BinOptions {
49     public:
50         static std::shared_ptr<UniformOptions> create(int binCount, float minValue,
51                                                       float exclusiveMaxValue);
52 
getBinsCount()53         int getBinsCount() const override {
54             return mBinCount;
55         }
56 
57         int getBinForSample(float sample) const override;
58 
59     private:
60         UniformOptions(int binCount, float minValue, float exclusiveMaxValue);
61 
62         const int mBinCount;
63         const float mMinValue;
64         const float mExclusiveMaxValue;
65         const float mBinSize;
66     };
67 
68     Histogram(const char* metricName, std::shared_ptr<BinOptions> binOptions);
69 
70     /**
71      * Logs increment sample count for automatically calculated bin
72      */
73     void logSample(float sample) const;
74 
75     /**
76      * Logs increment sample count for automatically calculated bin with uid
77      */
78     void logSampleWithUid(int32_t uid, float sample) const;
79 
80 private:
81     const int64_t mMetricIdHash;
82     const std::shared_ptr<BinOptions> mBinOptions;
83 };
84 
85 }  // namespace expresslog
86 }  // namespace android
87