Apollo 11.0
自动驾驶开放平台
macros.h
浏览该文件的文档.
1/******************************************************************************
2 * Copyright 2018 The Apollo Authors. All Rights Reserved.
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 CYBER_BASE_MACROS_H_
18#define CYBER_BASE_MACROS_H_
19
20#include <cstdlib>
21#include <new>
22
23#if __GNUC__ >= 3
24#define cyber_likely(x) (__builtin_expect((x), 1))
25#define cyber_unlikely(x) (__builtin_expect((x), 0))
26#else
27#define cyber_likely(x) (x)
28#define cyber_unlikely(x) (x)
29#endif
30
31#define CACHELINE_SIZE 64
32
33#define DEFINE_TYPE_TRAIT(name, func) \
34 template <typename T> \
35 struct name { \
36 template <typename Class> \
37 static constexpr bool Test(decltype(&Class::func)*) { \
38 return true; \
39 } \
40 template <typename> \
41 static constexpr bool Test(...) { \
42 return false; \
43 } \
44 \
45 static constexpr bool value = Test<T>(nullptr); \
46 }; \
47 \
48 template <typename T> \
49 constexpr bool name<T>::value;
50
51inline void cpu_relax() {
52#if defined(__aarch64__)
53 asm volatile("yield" ::: "memory");
54#else
55 asm volatile("rep; nop" ::: "memory");
56#endif
57}
58
59inline void* CheckedMalloc(size_t size) {
60 void* ptr = std::malloc(size);
61 if (!ptr) {
62 throw std::bad_alloc();
63 }
64 return ptr;
65}
66
67inline void* CheckedCalloc(size_t num, size_t size) {
68 void* ptr = std::calloc(num, size);
69 if (!ptr) {
70 throw std::bad_alloc();
71 }
72 return ptr;
73}
74
75#endif // CYBER_BASE_MACROS_H_
void * CheckedMalloc(size_t size)
Definition macros.h:59
void cpu_relax()
Definition macros.h:51
void * CheckedCalloc(size_t num, size_t size)
Definition macros.h:67