nngn
Loading...
Searching...
No Matches
pointer_flag.h
Go to the documentation of this file.
1#ifndef NNGN_UTILS_POINTER_FLAG_H
2#define NNGN_UTILS_POINTER_FLAG_H
3
4#include <cassert>
5#include <cstdint>
6
7namespace nngn {
8
9template<typename T> class pointer_flag {
10 static constexpr uintptr_t MASK = 0b1;
11 T *p = nullptr;
12 auto to_uint() const { return reinterpret_cast<uintptr_t>(this->p); }
13public:
14 pointer_flag() = default;
15 explicit constexpr pointer_flag(T *p);
16 T *get();
17 bool flag() { return this->to_uint() & pointer_flag::MASK; }
18 void set_flag(bool b);
19};
20
21template<typename T>
22inline constexpr pointer_flag<T>::pointer_flag(T *p_p)
23 : p(p_p) { assert(!this->flag()); }
24
25template<typename T>
27 const auto u = this->to_uint();
28 const auto off = u - (u & ~MASK);
29 auto *const cp = static_cast<char*>(static_cast<void*>(this->p));
30 return static_cast<T*>(static_cast<void*>(cp - off));
31}
32
33template<typename T>
34inline void pointer_flag<T>::set_flag(bool b) {
35 if(!b) {
36 this->p = this->get();
37 return;
38 }
39 const auto u = this->to_uint();
40 const auto off = (u | pointer_flag::MASK) - u;
41 auto *const cp = static_cast<char*>(static_cast<void*>(this->p));
42 this->p = static_cast<T*>(static_cast<void*>(cp + off));
43}
44
45}
46
47#endif
pointer_flag()=default
bool flag()
Definition: pointer_flag.h:17
T * p
Definition: pointer_flag.h:11
auto to_uint() const
Definition: pointer_flag.h:12
void set_flag(bool b)
constexpr pointer_flag(T *p)
static constexpr uintptr_t MASK
Definition: pointer_flag.h:10
assert
Definition: debug.lua:3
get
Definition: camera.lua:39
p
Definition: input.lua:29
#define T(f0, f1, f2)
Definition: audio.cpp:7