XenevaOS
Loading...
Searching...
No Matches
Common.hpp
Go to the documentation of this file.
1#ifndef __COMMON_HPP__
2#define __COMMON_HPP__
3
4#include <type_traits>
5#include <cstddef>
6#include <cstdint>
7#ifdef _MSC_VER
8 #include <Uefi/UefiBaseType.h>
9#elif __GNUC__
10 #include <efi/efi.h>
11#endif
12
13// We need UINT64 handling because of use cases
14// like EFI_PHYSICAL_ADDRESS
15
16// Helper trait: true if T is pointer or uint64_t
17template <typename T>
18struct is_ptr_or_uint64 : std::disjunction<
19 std::is_pointer<T>,
20 std::is_same<UINT64, std::remove_cv_t<T>>
21> {};
22
23// raw_diff for pointers and uint64_t
24template <typename T,
25 std::enable_if_t<is_ptr_or_uint64<T>::value, int> = 0>
26std::ptrdiff_t raw_diff(T p1, T p2)
27{
28 if constexpr (std::is_pointer<T>::value)
29 {
30 return reinterpret_cast<std::byte*>(p1) - reinterpret_cast<std::byte*>(p2);
31 }
32 else
33 {
34 return static_cast<std::ptrdiff_t>(p1 - p2);
35 }
36}
37
38// raw_offset: add byte offset to pointer or integer address
39template <typename T, typename U,
40 std::enable_if_t<is_ptr_or_uint64<T>::value && is_ptr_or_uint64<U>::value, int> = 0>
41T raw_offset(U p1, std::ptrdiff_t offset)
42{
43 if constexpr (std::is_pointer<T>::value)
44 {
45 return reinterpret_cast<T>(
46 reinterpret_cast<std::byte*>(p1) + offset
47 );
48 }
49 else
50 {
51 return static_cast<T>(p1 + offset);
52 }
53}
54
55// mem_after: get next element
56template <typename T,
57 std::enable_if_t<is_ptr_or_uint64<T>::value, int> = 0>
58T mem_after(T p1)
59{
60 if constexpr (std::is_pointer<T>::value)
61 {
62 return p1 + 1;
63 }
64 else
65 {
66 return p1 + 1;
67 }
68}
69
70// Macros for the same
71#define RAW_OFFSET(type, x, offset) (type)((size_t)x + offset)
72#define RAW_DIFF(p1,p2) ((intptr_t)p1 - (intptr_t)p2)
73#define MEM_AFTER(type, p) ((type)(&(p)[1]))
74
75#define DIV_ROUND_UP(x, y) \
76 ((x + y - 1) / y)
77
78#define ALIGN_UP(x, y) (DIV_ROUND_UP(x,y)*y)
79
80#endif // __COMMON_HPP__
std::ptrdiff_t raw_diff(T p1, T p2)
Definition Common.hpp:26
T raw_offset(U p1, std::ptrdiff_t offset)
Definition Common.hpp:41
T mem_after(T p1)
Definition Common.hpp:58
Definition Common.hpp:21