The Sparta Modeling Framework
Loading...
Searching...
No Matches
PointerUtils.hpp
1// <PointerUtils.hpp> -*- C++ -*-
2
3#pragma once
4
5#include <typeinfo>
6#include <cxxabi.h>
7#include <type_traits>
8#include <memory>
9
12
13namespace sparta {
14 namespace utils {
15
16#if !defined(__linux__)
17 // mac always has to use libc++
18#define SHARED_PTR_NAME "std::__1::shared_ptr"
19#else
20 // note that libc++ uses std::__1, so this will be the wrong name if you link against it
21#define SHARED_PTR_NAME "std::shared_ptr"
22#endif
27 template<class T, class U, bool Unsafe = false>
28 std::shared_ptr<T>
29 checked_dynamic_pointer_cast(const std::shared_ptr<U>& right)
30 {
31 if (Unsafe) {
32 return std::static_pointer_cast<T>(right);
33 } else {
34 std::shared_ptr<T> destination = std::dynamic_pointer_cast<T>(right);
35
36 if (__builtin_expect(!destination, false)) {
37 const auto td = typeid(right).name();
38 int sts;
39 const auto td2 = typeid(T).name();
40 std::unique_ptr<char, void(*)(void*)> not_type {abi::__cxa_demangle(td2, nullptr, nullptr, &sts), std::free};
41 std::unique_ptr<char, void(*)(void*)> is_type {abi::__cxa_demangle(td, nullptr, nullptr, &sts), std::free};
42
43 // note that libc++ uses std::__1, so this will be the wrong name if you link against it
44 sparta_assert2(destination != nullptr,
45 " dynamic_pointer_cast failed, this shared_ptr is of type " <<
46 is_type.get() << ", not of type " SHARED_PTR_NAME "<" <<
47 not_type.get() << ">");
48 }
49 return destination;
50 }
51 }
52
57 template<class T, class U, bool Unsafe = false>
58 T checked_dynamic_cast(const U right)
59 {
60 if (Unsafe) {
61 return static_cast<T>(right);
62 } else {
63 T destination = dynamic_cast<T>(right);
64
65 if (__builtin_expect(!destination, false)) {
66 const auto td = typeid(right).name();
67 int sts;
68 const auto td2 = typeid(T).name();
69 std::unique_ptr<char, void(*)(void*)> not_type {abi::__cxa_demangle(td2, nullptr, nullptr, &sts), std::free};
70 std::unique_ptr<char, void(*)(void*)> is_type {abi::__cxa_demangle(td, nullptr, nullptr, &sts), std::free};
71 sparta_assert2(destination != nullptr,
72 " dynamic_cast failed, this pointer is of type " <<
73 is_type.get() << ", not of type " << not_type.get());
74 }
75 return destination;
76 }
77 }
78
79 } // utils
80} // sparta
Set of macros for Sparta assertions. Caught by the framework.
Exception class for all of Sparta.
Macros for handling exponential backoff.