1 /*
2 * Copyright (C) 2024 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 #ifndef SRC_TRACE_PROCESSOR_IMPORTERS_PERF_UTIL_H_
18 #define SRC_TRACE_PROCESSOR_IMPORTERS_PERF_UTIL_H_
19
20 #include <cstddef>
21 #include <cstdint>
22 #include <type_traits>
23
24 namespace perfetto::trace_processor::perf_importer {
25
26 template <typename A, typename B, typename Res>
SafeAdd(A a,B b,Res * result)27 inline bool SafeAdd(A a, B b, Res* result) {
28 return !__builtin_add_overflow(a, b, result);
29 }
30
31 template <typename A, typename B, typename Res>
SafeMultiply(A a,B b,Res * result)32 inline bool SafeMultiply(A a, B b, Res* result) {
33 return !__builtin_mul_overflow(a, b, result);
34 }
35
36 template <typename A,
37 typename Res,
38 typename = std::enable_if_t<std::is_integral<A>::value &&
39 std::is_integral<Res>::value>>
SafeCast(A a,Res * res)40 bool SafeCast(A a, Res* res) {
41 *res = static_cast<Res>(a);
42
43 // Was the value clamped?
44 if (static_cast<A>(*res) != a) {
45 return false;
46 }
47
48 // Did the sign change?
49 if ((a < 0) != (*res < 0)) {
50 return false;
51 }
52
53 return true;
54 }
55
56 } // namespace perfetto::trace_processor::perf_importer
57
58 #endif // SRC_TRACE_PROCESSOR_IMPORTERS_PERF_UTIL_H_
59