1 /* 2 * Copyright (C) 2017 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 INCLUDE_PERFETTO_BASE_UTILS_H_ 18 #define INCLUDE_PERFETTO_BASE_UTILS_H_ 19 20 #include <errno.h> 21 #include <stddef.h> 22 #include <stdlib.h> 23 24 #define PERFETTO_EINTR(x) \ 25 ({ \ 26 decltype(x) eintr_wrapper_result; \ 27 do { \ 28 eintr_wrapper_result = (x); \ 29 } while (eintr_wrapper_result == -1 && errno == EINTR); \ 30 eintr_wrapper_result; \ 31 }) 32 33 #define PERFETTO_LIKELY(_x) __builtin_expect(!!(_x), 1) 34 #define PERFETTO_UNLIKELY(_x) __builtin_expect(!!(_x), 0) 35 36 namespace perfetto { 37 namespace base { 38 39 constexpr size_t kPageSize = 4096; 40 41 template <typename T> 42 constexpr size_t ArraySize(const T& array) { 43 return sizeof(array) / sizeof(array[0]); 44 } 45 46 template <typename... T> 47 inline void ignore_result(const T&...) {} 48 49 // Function object which invokes 'free' on its parameter, which must be 50 // a pointer. Can be used to store malloc-allocated pointers in std::unique_ptr: 51 // 52 // std::unique_ptr<int, base::FreeDeleter> foo_ptr( 53 // static_cast<int*>(malloc(sizeof(int)))); 54 struct FreeDeleter { 55 inline void operator()(void* ptr) const { free(ptr); } 56 }; 57 58 template <typename T> 59 constexpr T AssumeLittleEndian(T value) { 60 static_assert(__BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__, 61 "Unimplemented on big-endian archs"); 62 return value; 63 } 64 65 // Round up |size| to a multiple of |alignment| (must be a power of two). 66 template <size_t alignment> 67 constexpr size_t AlignUp(size_t size) { 68 static_assert((alignment & (alignment - 1)) == 0, "alignment must be a pow2"); 69 return (size + alignment - 1) & ~(alignment - 1); 70 } 71 72 } // namespace base 73 } // namespace perfetto 74 75 #endif // INCLUDE_PERFETTO_BASE_UTILS_H_ 76