Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
Roblox
GitHub Repository: Roblox/luau
Path: blob/master/Analysis/include/Luau/NotNull.h
2727 views
1
// This file is part of the Luau programming language and is licensed under MIT License; see LICENSE.txt for details
2
#pragma once
3
4
#include "Luau/Common.h"
5
6
#include <functional>
7
8
namespace Luau
9
{
10
11
/** A non-owning, non-null pointer to a T.
12
*
13
* A NotNull<T> is notionally identical to a T* with the added restriction that
14
* it can never store nullptr.
15
*
16
* The sole conversion rule from T* to NotNull<T> is the single-argument
17
* constructor, which is intentionally marked explicit. This constructor
18
* performs a runtime test to verify that the passed pointer is never nullptr.
19
*
20
* Pointer arithmetic, increment, decrement, and array indexing are all
21
* forbidden.
22
*
23
* An implicit coercion from NotNull<T> to T* is afforded, as are the pointer
24
* indirection and member access operators. (*p and p->prop)
25
*
26
* The explicit delete statement is permitted (but not recommended) on a
27
* NotNull<T> through this implicit conversion.
28
*/
29
template<typename T>
30
struct NotNull
31
{
32
explicit NotNull(T* t)
33
: ptr(t)
34
{
35
LUAU_ASSERT(t);
36
}
37
38
explicit NotNull(std::nullptr_t) = delete;
39
void operator=(std::nullptr_t) = delete;
40
41
template<typename U>
42
NotNull(NotNull<U> other)
43
: ptr(other.get())
44
{
45
}
46
47
operator T*() const noexcept
48
{
49
return ptr;
50
}
51
52
T& operator*() const noexcept
53
{
54
return *ptr;
55
}
56
57
T* operator->() const noexcept
58
{
59
return ptr;
60
}
61
62
template<typename U>
63
bool operator==(NotNull<U> other) const noexcept
64
{
65
return get() == other.get();
66
}
67
68
template<typename U>
69
bool operator!=(NotNull<U> other) const noexcept
70
{
71
return get() != other.get();
72
}
73
74
operator bool() const noexcept = delete;
75
76
T& operator[](int) = delete;
77
78
T& operator+(int) = delete;
79
T& operator-(int) = delete;
80
81
T* get() const noexcept
82
{
83
return ptr;
84
}
85
86
private:
87
T* ptr;
88
};
89
90
} // namespace Luau
91
92
namespace std
93
{
94
95
template<typename T>
96
struct hash<Luau::NotNull<T>>
97
{
98
size_t operator()(const Luau::NotNull<T>& p) const
99
{
100
return std::hash<T*>()(p.get());
101
}
102
};
103
104
} // namespace std
105
106