blob: efd26fa9ecd79e3d5433d4b86a6a3c7b0bd23b34 [file] [log] [blame]
Primiano Tucci4f9b6d72017-12-05 20:59:16 +00001/*
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
Primiano Tucci19318a72018-02-22 12:33:02 +000033#define PERFETTO_LIKELY(_x) __builtin_expect(!!(_x), 1)
34#define PERFETTO_UNLIKELY(_x) __builtin_expect(!!(_x), 0)
35
Primiano Tucci4f9b6d72017-12-05 20:59:16 +000036namespace perfetto {
37namespace base {
38
Anna Zappone30ba3042018-01-26 10:57:28 +000039constexpr size_t kPageSize = 4096;
Anna Zapponebba19412018-01-24 16:38:18 +000040
Primiano Tucci4f9b6d72017-12-05 20:59:16 +000041template <typename T>
42constexpr size_t ArraySize(const T& array) {
43 return sizeof(array) / sizeof(array[0]);
44}
45
46template <typename... T>
47inline 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))));
54struct FreeDeleter {
55 inline void operator()(void* ptr) const { free(ptr); }
56};
57
58template <typename T>
59constexpr T AssumeLittleEndian(T value) {
60 static_assert(__BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__,
61 "Unimplemented on big-endian archs");
62 return value;
63}
64
Primiano Tucci5c599012018-03-01 17:52:07 +000065// Round up |size| to a multiple of |alignment| (must be a power of two).
Primiano Tucci3cbb10a2018-04-10 17:52:40 +010066template <size_t alignment>
Primiano Tucci5c599012018-03-01 17:52:07 +000067constexpr 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
Primiano Tucci4f9b6d72017-12-05 20:59:16 +000072} // namespace base
73} // namespace perfetto
74
75#endif // INCLUDE_PERFETTO_BASE_UTILS_H_