1 /*
2 * Copyright (c) 2025 Huawei Device Co., Ltd.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16 #ifndef COMMON_COMPONENTS_BASE_GLOBALS_H
17 #define COMMON_COMPONENTS_BASE_GLOBALS_H
18
19 #include <cstddef>
20
21 #include "common_components/base/ark_sanitizer.h"
22 #include "common_interfaces/base/common.h"
23
24 namespace common {
25 // Time Factors
26 constexpr uint64_t TIME_FACTOR = 1000LL;
27 constexpr uint64_t SECOND_TO_NANO_SECOND = TIME_FACTOR * TIME_FACTOR * TIME_FACTOR;
28 constexpr uint64_t MICRO_SECOND_TO_NANO_SECOND = TIME_FACTOR;
29 constexpr uint64_t MILLI_SECOND_TO_NANO_SECOND = TIME_FACTOR * TIME_FACTOR;
30
31 constexpr size_t KB = 1024;
32 constexpr size_t MB = KB * KB;
33 constexpr size_t GB = KB * KB * KB;
34
35 constexpr size_t ALIGN_OBJECT = 8;
36
37 template<typename T>
38 struct Identity {
39 using type = T;
40 };
41
42 extern const size_t COMMON_PAGE_SIZE;
43
44 template<typename T>
IsPowerOfTwo(T x)45 constexpr bool IsPowerOfTwo(T x)
46 {
47 static_assert(std::is_integral<T>::value, "T must be integral");
48 bool ret = false;
49 if (x != 0) {
50 ret = (x & (x - 1)) == 0;
51 }
52 return ret;
53 }
54
55 template<typename T>
RoundDown(T x,typename Identity<T>::type n)56 T RoundDown(T x, typename Identity<T>::type n)
57 {
58 DCHECK_CC(IsPowerOfTwo(n));
59 return (x & -n);
60 }
61
62 template<class T>
AlignUp(T size,T alignment)63 constexpr T AlignUp(T size, T alignment)
64 {
65 return ((size + alignment - 1) & ~static_cast<T>(alignment - 1));
66 }
67
68 template<typename T>
RoundUp(T x,typename std::remove_reference<T>::type n)69 constexpr T RoundUp(T x, typename std::remove_reference<T>::type n)
70 {
71 return RoundDown(x + n - 1, n);
72 }
73
74 template<typename T>
AlignUp(T * x,uintptr_t n)75 inline T* AlignUp(T* x, uintptr_t n)
76 {
77 return reinterpret_cast<T*>(RoundUp(reinterpret_cast<uintptr_t>(x), n));
78 }
79
80 template<class T>
AlignDown(T size,T alignment)81 constexpr T AlignDown(T size, T alignment)
82 {
83 return (size & ~static_cast<T>(alignment - 1));
84 }
85 } // namespace common
86
87 #endif // COMMON_COMPONENTS_BASE_GLOBALS_H
88