Bug 1613876 [wpt PR 21654] - Reland "Move SMIL events tests to WPT", a=testonly
[gecko.git] / mfbt / NotNull.h
blob208ce320e0ae87cb5d1a4a41842306126496f792
1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 /* vim: set ts=8 sts=2 et sw=2 tw=80: */
3 /* This Source Code Form is subject to the terms of the Mozilla Public
4 * License, v. 2.0. If a copy of the MPL was not distributed with this
5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
7 #ifndef mozilla_NotNull_h
8 #define mozilla_NotNull_h
10 // It's often unclear if a particular pointer, be it raw (T*) or smart
11 // (RefPtr<T>, nsCOMPtr<T>, etc.) can be null. This leads to missing null
12 // checks (which can cause crashes) and unnecessary null checks (which clutter
13 // the code).
15 // C++ has a built-in alternative that avoids these problems: references. This
16 // module defines another alternative, NotNull, which can be used in cases
17 // where references are not suitable.
19 // In the comments below we use the word "handle" to cover all varieties of
20 // pointers and references.
22 // References
23 // ----------
24 // References are always non-null. (You can do |T& r = *p;| where |p| is null,
25 // but that's undefined behaviour. C++ doesn't provide any built-in, ironclad
26 // guarantee of non-nullness.)
28 // A reference works well when you need a temporary handle to an existing
29 // single object, e.g. for passing a handle to a function, or as a local handle
30 // within another object. (In Rust parlance, this is a "borrow".)
32 // A reference is less appropriate in the following cases.
34 // - As a primary handle to an object. E.g. code such as this is possible but
35 // strange: |T& t = *new T(); ...; delete &t;|
37 // - As a handle to an array. It's common for |T*| to refer to either a single
38 // |T| or an array of |T|, but |T&| cannot refer to an array of |T| because
39 // you can't index off a reference (at least, not without first converting it
40 // to a pointer).
42 // - When the handle identity is meaningful, e.g. if you have a hashtable of
43 // handles, because you have to use |&| on the reference to convert it to a
44 // pointer.
46 // - Some people don't like using non-const references as function parameters,
47 // because it is not clear at the call site that the argument might be
48 // modified.
50 // - When you need "smart" behaviour. E.g. we lack reference equivalents to
51 // RefPtr and nsCOMPtr.
53 // - When interfacing with code that uses pointers a lot, sometimes using a
54 // reference just feels like an odd fit.
56 // Furthermore, a reference is impossible in the following cases.
58 // - When the handle is rebound to another object. References don't allow this.
60 // - When the handle has type |void|. |void&| is not allowed.
62 // NotNull is an alternative that can be used in any of the above cases except
63 // for the last one, where the handle type is |void|. See below.
65 #include <stddef.h>
67 #include <utility>
69 #include "mozilla/Assertions.h"
71 namespace mozilla {
73 // NotNull can be used to wrap a "base" pointer (raw or smart) to indicate it
74 // is not null. Some examples:
76 // - NotNull<char*>
77 // - NotNull<RefPtr<Event>>
78 // - NotNull<nsCOMPtr<Event>>
80 // NotNull has the following notable properties.
82 // - It has zero space overhead.
84 // - It must be initialized explicitly. There is no default initialization.
86 // - It auto-converts to the base pointer type.
88 // - It does not auto-convert from a base pointer. Implicit conversion from a
89 // less-constrained type (e.g. T*) to a more-constrained type (e.g.
90 // NotNull<T*>) is dangerous. Creation and assignment from a base pointer can
91 // only be done with WrapNotNull() or MakeNotNull<>(), which makes them
92 // impossible to overlook, both when writing and reading code.
94 // - When initialized (or assigned) it is checked, and if it is null we abort.
95 // This guarantees that it cannot be null.
97 // - |operator bool()| is deleted. This means you cannot check a NotNull in a
98 // boolean context, which eliminates the possibility of unnecessary null
99 // checks.
101 // NotNull currently doesn't work with UniquePtr. See
102 // https://github.com/Microsoft/GSL/issues/89 for some discussion.
104 template <typename T>
105 class NotNull {
106 template <typename U>
107 friend constexpr NotNull<U> WrapNotNull(U aBasePtr);
108 template <typename U, typename... Args>
109 friend constexpr NotNull<U> MakeNotNull(Args&&... aArgs);
111 T mBasePtr;
113 // This constructor is only used by WrapNotNull() and MakeNotNull<U>().
114 template <typename U>
115 constexpr explicit NotNull(U aBasePtr) : mBasePtr(aBasePtr) {}
117 public:
118 // Disallow default construction.
119 NotNull() = delete;
121 // Construct/assign from another NotNull with a compatible base pointer type.
122 template <typename U>
123 constexpr MOZ_IMPLICIT NotNull(const NotNull<U>& aOther)
124 : mBasePtr(aOther.get()) {
125 static_assert(sizeof(T) == sizeof(NotNull<T>),
126 "NotNull must have zero space overhead.");
127 static_assert(offsetof(NotNull<T>, mBasePtr) == 0,
128 "mBasePtr must have zero offset.");
131 // Default copy/move construction and assignment.
132 NotNull(const NotNull<T>&) = default;
133 NotNull<T>& operator=(const NotNull<T>&) = default;
134 NotNull(NotNull<T>&&) = default;
135 NotNull<T>& operator=(NotNull<T>&&) = default;
137 // Disallow null checks, which are unnecessary for this type.
138 explicit operator bool() const = delete;
140 // Explicit conversion to a base pointer. Use only to resolve ambiguity or to
141 // get a castable pointer.
142 constexpr const T& get() const { return mBasePtr; }
144 // Implicit conversion to a base pointer. Preferable to get().
145 constexpr operator const T&() const { return get(); }
147 // Dereference operators.
148 constexpr const T& operator->() const { return get(); }
149 constexpr decltype(*mBasePtr) operator*() const { return *mBasePtr; }
152 template <typename T>
153 constexpr NotNull<T> WrapNotNull(const T aBasePtr) {
154 NotNull<T> notNull(aBasePtr);
155 MOZ_RELEASE_ASSERT(aBasePtr);
156 return notNull;
159 namespace detail {
161 // Extract the pointed-to type from a pointer type (be it raw or smart).
162 // The default implementation uses the dereferencing operator of the pointer
163 // type to find what it's pointing to.
164 template <typename Pointer>
165 struct PointedTo {
166 // Remove the reference that dereferencing operators may return.
167 using Type = typename RemoveReference<decltype(*DeclVal<Pointer>())>::Type;
168 using NonConstType = typename RemoveConst<Type>::Type;
171 // Specializations for raw pointers.
172 // This is especially required because VS 2017 15.6 (March 2018) started
173 // rejecting the above `decltype(*DeclVal<Pointer>())` trick for raw pointers.
174 // See bug 1443367.
175 template <typename T>
176 struct PointedTo<T*> {
177 using Type = T;
178 using NonConstType = T;
181 template <typename T>
182 struct PointedTo<const T*> {
183 using Type = const T;
184 using NonConstType = T;
187 } // namespace detail
189 // Allocate an object with infallible new, and wrap its pointer in NotNull.
190 // |MakeNotNull<Ptr<Ob>>(args...)| will run |new Ob(args...)|
191 // and return NotNull<Ptr<Ob>>.
192 template <typename T, typename... Args>
193 constexpr NotNull<T> MakeNotNull(Args&&... aArgs) {
194 using Pointee = typename detail::PointedTo<T>::NonConstType;
195 static_assert(!IsArray<Pointee>::value,
196 "MakeNotNull cannot construct an array");
197 return NotNull<T>(new Pointee(std::forward<Args>(aArgs)...));
200 // Compare two NotNulls.
201 template <typename T, typename U>
202 constexpr bool operator==(const NotNull<T>& aLhs, const NotNull<U>& aRhs) {
203 return aLhs.get() == aRhs.get();
205 template <typename T, typename U>
206 constexpr bool operator!=(const NotNull<T>& aLhs, const NotNull<U>& aRhs) {
207 return aLhs.get() != aRhs.get();
210 // Compare a NotNull to a base pointer.
211 template <typename T, typename U>
212 constexpr bool operator==(const NotNull<T>& aLhs, const U& aRhs) {
213 return aLhs.get() == aRhs;
215 template <typename T, typename U>
216 constexpr bool operator!=(const NotNull<T>& aLhs, const U& aRhs) {
217 return aLhs.get() != aRhs;
220 // Compare a base pointer to a NotNull.
221 template <typename T, typename U>
222 constexpr bool operator==(const T& aLhs, const NotNull<U>& aRhs) {
223 return aLhs == aRhs.get();
225 template <typename T, typename U>
226 constexpr bool operator!=(const T& aLhs, const NotNull<U>& aRhs) {
227 return aLhs != aRhs.get();
230 // Disallow comparing a NotNull to a nullptr.
231 template <typename T>
232 bool operator==(const NotNull<T>&, decltype(nullptr)) = delete;
233 template <typename T>
234 bool operator!=(const NotNull<T>&, decltype(nullptr)) = delete;
236 // Disallow comparing a nullptr to a NotNull.
237 template <typename T>
238 bool operator==(decltype(nullptr), const NotNull<T>&) = delete;
239 template <typename T>
240 bool operator!=(decltype(nullptr), const NotNull<T>&) = delete;
242 } // namespace mozilla
244 #endif /* mozilla_NotNull_h */