2 * Copyright 2012 Facebook, Inc.
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
17 #ifndef FOLLY_DETAIL_STATS_H_
18 #define FOLLY_DETAIL_STATS_H_
22 namespace folly { namespace detail {
25 * Helper functions for how to perform division based on the desired
29 // For floating point input types, do floating point division
30 template <typename ReturnType, typename ValueType>
31 typename std::enable_if<std::is_floating_point<ValueType>::value,
33 avgHelper(ValueType sum, uint64_t count) {
34 if (count == 0) { return ReturnType(0); }
35 return static_cast<ReturnType>(sum / count);
38 // For floating point return types, do floating point division
39 template <typename ReturnType, typename ValueType>
40 typename std::enable_if<std::is_floating_point<ReturnType>::value &&
41 !std::is_floating_point<ValueType>::value,
43 avgHelper(ValueType sum, uint64_t count) {
44 if (count == 0) { return ReturnType(0); }
45 return static_cast<ReturnType>(sum) / count;
48 // For signed integer input types, do signed division
49 template <typename ReturnType, typename ValueType>
50 typename std::enable_if<!std::is_floating_point<ReturnType>::value &&
51 !std::is_floating_point<ValueType>::value &&
52 std::is_signed<ValueType>::value,
54 avgHelper(ValueType sum, uint64_t count) {
55 if (count == 0) { return ReturnType(0); }
56 return sum / static_cast<int64_t>(count);
59 // For unsigned integer input types, do unsigned division
60 template <typename ReturnType, typename ValueType>
61 typename std::enable_if<!std::is_floating_point<ReturnType>::value &&
62 !std::is_floating_point<ValueType>::value &&
63 std::is_unsigned<ValueType>::value,
65 avgHelper(ValueType sum, uint64_t count) {
66 if (count == 0) { return ReturnType(0); }
85 void add(const ValueType& s, uint64_t c) {
86 // TODO: It would be nice to handle overflow here.
91 Bucket& operator+=(const Bucket& o) {
96 Bucket& operator-=(const Bucket& o) {
97 // TODO: It would be nice to handle overflow here.
103 template <typename ReturnType>
104 ReturnType avg() const {
105 return avgHelper<ReturnType>(sum, count);
114 #endif // FOLLY_DETAIL_STATS_H_