1 /* 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> 19 #include <cutils/compiler.h> 20 #include <utils/Trace.h> 21 #include <cmath> 22 #include <string> 23 24 namespace android { 25 26 template <typename T> 27 class TracedOrdinal { 28 public: 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 TracedOrdinal(std::string name,T initialValue)33 TracedOrdinal(std::string name, T initialValue) 34 : mName(std::move(name)), 35 mHasGoneNegative(std::signbit(initialValue)), 36 mData(initialValue) { 37 trace(); 38 } 39 T()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 49 private: trace()50 void trace() { 51 if (CC_LIKELY(!ATRACE_ENABLED())) { 52 return; 53 } 54 55 if (mNameNegative.empty()) { 56 mNameNegative = base::StringPrintf("%sNegative", mName.c_str()); 57 } 58 59 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; 71 std::string mNameNegative; 72 bool mHasGoneNegative; 73 T mData; 74 }; 75 76 } // namespace android 77