blob: 4e7f67d5ac6534c5e43bbf91dfa8e77bb9af84c3 [file] [log] [blame]
Ady Abraham50204dd2019-07-19 15:47:11 -07001/*
2 * Copyright 2019 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 <android-base/stringprintf.h>
Dan Stoza8ea808c2020-04-01 13:58:56 -070019#include <cutils/compiler.h>
Ady Abraham50204dd2019-07-19 15:47:11 -070020#include <utils/Trace.h>
21#include <cmath>
22#include <string>
23
Dan Stoza8ea808c2020-04-01 13:58:56 -070024namespace android {
25
Ady Abraham50204dd2019-07-19 15:47:11 -070026template <typename T>
27class TracedOrdinal {
28public:
29 static_assert(std::is_same<bool, T>() || (std::is_signed<T>() && std::is_integral<T>()),
30 "Type is not supported. Please test it with systrace before adding "
31 "it to the list.");
32
Dan Stoza8ea808c2020-04-01 13:58:56 -070033 TracedOrdinal(std::string name, T initialValue)
34 : mName(std::move(name)),
Ady Abraham50204dd2019-07-19 15:47:11 -070035 mHasGoneNegative(std::signbit(initialValue)),
36 mData(initialValue) {
37 trace();
38 }
39
40 operator T() const { return mData; }
41
42 TracedOrdinal& operator=(T other) {
43 mData = other;
44 mHasGoneNegative = mHasGoneNegative || std::signbit(mData);
45 trace();
46 return *this;
47 }
48
49private:
50 void trace() {
Dan Stoza8ea808c2020-04-01 13:58:56 -070051 if (CC_LIKELY(!ATRACE_ENABLED())) {
52 return;
53 }
54
55 if (mNameNegative.empty()) {
56 mNameNegative = base::StringPrintf("%sNegative", mName.c_str());
57 }
58
Ady Abraham50204dd2019-07-19 15:47:11 -070059 if (!std::signbit(mData)) {
60 ATRACE_INT64(mName.c_str(), int64_t(mData));
61 if (mHasGoneNegative) {
62 ATRACE_INT64(mNameNegative.c_str(), 0);
63 }
64 } else {
65 ATRACE_INT64(mNameNegative.c_str(), -int64_t(mData));
66 ATRACE_INT64(mName.c_str(), 0);
67 }
68 }
69
70 const std::string mName;
Dan Stoza8ea808c2020-04-01 13:58:56 -070071 std::string mNameNegative;
Ady Abraham50204dd2019-07-19 15:47:11 -070072 bool mHasGoneNegative;
73 T mData;
74};
Dan Stoza8ea808c2020-04-01 13:58:56 -070075
76} // namespace android