Bug 1687556 [wpt PR 27245] - [TablesNG] Fix DCHECKs when painting rows/sections with...
[gecko.git] / mfbt / NotNull.h
blob6b1d2fe1c0338abd0b3f68898a981cd772bd4f09
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 <type_traits>
68 #include <utility>
70 #include "mozilla/Assertions.h"
72 namespace mozilla {
74 namespace detail {
75 template <typename T>
76 struct CopyablePtr {
77 T mPtr;
79 template <typename U>
80 explicit CopyablePtr(U aPtr) : mPtr{std::move(aPtr)} {}
82 } // namespace detail
84 template <typename T>
85 class MovingNotNull;
87 // NotNull can be used to wrap a "base" pointer (raw or smart) to indicate it
88 // is not null. Some examples:
90 // - NotNull<char*>
91 // - NotNull<RefPtr<Event>>
92 // - NotNull<nsCOMPtr<Event>>
93 // - NotNull<UniquePtr<Pointee>>
95 // NotNull has the following notable properties.
97 // - It has zero space overhead.
99 // - It must be initialized explicitly. There is no default initialization.
101 // - It auto-converts to the base pointer type.
103 // - It does not auto-convert from a base pointer. Implicit conversion from a
104 // less-constrained type (e.g. T*) to a more-constrained type (e.g.
105 // NotNull<T*>) is dangerous. Creation and assignment from a base pointer can
106 // only be done with WrapNotNull() or MakeNotNull<>(), which makes them
107 // impossible to overlook, both when writing and reading code.
109 // - When initialized (or assigned) it is checked, and if it is null we abort.
110 // This guarantees that it cannot be null.
112 // - |operator bool()| is deleted. This means you cannot check a NotNull in a
113 // boolean context, which eliminates the possibility of unnecessary null
114 // checks.
116 // - It is not movable, but copyable if the base pointer type is copyable. It
117 // may be used together with MovingNotNull to avoid unnecessary copies or when
118 // the base pointer type is not copyable (such as UniquePtr<T>).
120 template <typename T>
121 class NotNull {
122 template <typename U>
123 friend constexpr NotNull<U> WrapNotNull(U aBasePtr);
124 template <typename U>
125 friend constexpr NotNull<U> WrapNotNullUnchecked(U aBasePtr);
126 template <typename U, typename... Args>
127 friend constexpr NotNull<U> MakeNotNull(Args&&... aArgs);
128 template <typename U>
129 friend class NotNull;
131 detail::CopyablePtr<T> mBasePtr;
133 // This constructor is only used by WrapNotNull() and MakeNotNull<U>().
134 template <typename U>
135 constexpr explicit NotNull(U aBasePtr) : mBasePtr(T{std::move(aBasePtr)}) {
136 static_assert(sizeof(T) == sizeof(NotNull<T>),
137 "NotNull must have zero space overhead.");
138 static_assert(offsetof(NotNull<T>, mBasePtr) == 0,
139 "mBasePtr must have zero offset.");
142 public:
143 // Disallow default construction.
144 NotNull() = delete;
146 // Construct/assign from another NotNull with a compatible base pointer type.
147 template <typename U>
148 constexpr MOZ_IMPLICIT NotNull(const NotNull<U>& aOther)
149 : mBasePtr(aOther.mBasePtr) {}
151 template <typename U>
152 constexpr MOZ_IMPLICIT NotNull(MovingNotNull<U>&& aOther)
153 : mBasePtr(std::move(aOther).unwrapBasePtr()) {}
155 // Disallow null checks, which are unnecessary for this type.
156 explicit operator bool() const = delete;
158 // Explicit conversion to a base pointer. Use only to resolve ambiguity or to
159 // get a castable pointer.
160 constexpr const T& get() const { return mBasePtr.mPtr; }
162 // Implicit conversion to a base pointer. Preferable to get().
163 constexpr operator const T&() const { return get(); }
165 // Dereference operators.
166 constexpr auto* operator->() const MOZ_NONNULL_RETURN {
167 return mBasePtr.mPtr.operator->();
169 constexpr decltype(*mBasePtr.mPtr) operator*() const {
170 return *mBasePtr.mPtr;
173 // NotNull can be copied, but not moved. Moving a NotNull with a smart base
174 // pointer would leave a nullptr NotNull behind. The move operations must not
175 // be explicitly deleted though, since that would cause overload resolution to
176 // fail in situations where a copy is possible.
177 NotNull(const NotNull&) = default;
178 NotNull& operator=(const NotNull&) = default;
181 // Specialization for T* to allow adding MOZ_NONNULL_RETURN attributes.
182 template <typename T>
183 class NotNull<T*> {
184 template <typename U>
185 friend constexpr NotNull<U> WrapNotNull(U aBasePtr);
186 template <typename U>
187 friend constexpr NotNull<U*> WrapNotNullUnchecked(U* aBasePtr);
188 template <typename U, typename... Args>
189 friend constexpr NotNull<U> MakeNotNull(Args&&... aArgs);
190 template <typename U>
191 friend class NotNull;
193 T* mBasePtr;
195 // This constructor is only used by WrapNotNull() and MakeNotNull<U>().
196 template <typename U>
197 constexpr explicit NotNull(U* aBasePtr) : mBasePtr(aBasePtr) {}
199 public:
200 // Disallow default construction.
201 NotNull() = delete;
203 // Construct/assign from another NotNull with a compatible base pointer type.
204 template <typename U>
205 constexpr MOZ_IMPLICIT NotNull(const NotNull<U>& aOther)
206 : mBasePtr(aOther.get()) {
207 static_assert(sizeof(T*) == sizeof(NotNull<T*>),
208 "NotNull must have zero space overhead.");
209 static_assert(offsetof(NotNull<T*>, mBasePtr) == 0,
210 "mBasePtr must have zero offset.");
213 template <typename U>
214 constexpr MOZ_IMPLICIT NotNull(MovingNotNull<U>&& aOther)
215 : mBasePtr(NotNull{std::move(aOther)}) {}
217 // Disallow null checks, which are unnecessary for this type.
218 explicit operator bool() const = delete;
220 // Explicit conversion to a base pointer. Use only to resolve ambiguity or to
221 // get a castable pointer.
222 constexpr T* get() const MOZ_NONNULL_RETURN { return mBasePtr; }
224 // Implicit conversion to a base pointer. Preferable to get().
225 constexpr operator T*() const MOZ_NONNULL_RETURN { return get(); }
227 // Dereference operators.
228 constexpr T* operator->() const MOZ_NONNULL_RETURN { return get(); }
229 constexpr T& operator*() const { return *mBasePtr; }
232 template <typename T>
233 constexpr NotNull<T> WrapNotNull(T aBasePtr) {
234 MOZ_RELEASE_ASSERT(aBasePtr);
235 return NotNull<T>{std::move(aBasePtr)};
238 // WrapNotNullUnchecked should only be used in situations, where it is
239 // statically known that aBasePtr is non-null, and redundant release assertions
240 // should be avoided. It is only defined for raw base pointers, since it is only
241 // needed for those right now. There is no fundamental reason not to allow
242 // arbitrary base pointers here.
243 template <typename T>
244 constexpr NotNull<T> WrapNotNullUnchecked(T aBasePtr) {
245 return NotNull<T>{std::move(aBasePtr)};
248 template <typename T>
249 MOZ_NONNULL(1)
250 constexpr NotNull<T*> WrapNotNullUnchecked(T* const aBasePtr) {
251 #if defined(__clang__)
252 # pragma clang diagnostic push
253 # pragma clang diagnostic ignored "-Wpointer-bool-conversion"
254 #elif defined(__GNUC__)
255 # pragma GCC diagnostic push
256 # pragma GCC diagnostic ignored "-Wnonnull-compare"
257 #endif
258 MOZ_ASSERT(aBasePtr);
259 #if defined(__clang__)
260 # pragma clang diagnostic pop
261 #elif defined(__GNUC__)
262 # pragma GCC diagnostic pop
263 #endif
264 return NotNull<T*>{aBasePtr};
267 // A variant of NotNull that can be used as a return value or parameter type and
268 // moved into both NotNull and non-NotNull targets. This is not possible with
269 // NotNull, as it is not movable. MovingNotNull can therefore not guarantee it
270 // is always non-nullptr, but it can't be dereferenced, and there are debug
271 // assertions that ensure it is only moved once.
272 template <typename T>
273 class MOZ_NON_AUTOABLE MovingNotNull {
274 template <typename U>
275 friend constexpr MovingNotNull<U> WrapMovingNotNullUnchecked(U aBasePtr);
277 T mBasePtr;
278 #ifdef DEBUG
279 bool mConsumed = false;
280 #endif
282 // This constructor is only used by WrapNotNull() and MakeNotNull<U>().
283 template <typename U>
284 constexpr explicit MovingNotNull(U aBasePtr) : mBasePtr{std::move(aBasePtr)} {
285 #ifndef DEBUG
286 static_assert(sizeof(T) == sizeof(MovingNotNull<T>),
287 "NotNull must have zero space overhead.");
288 #endif
289 static_assert(offsetof(MovingNotNull<T>, mBasePtr) == 0,
290 "mBasePtr must have zero offset.");
293 public:
294 MovingNotNull() = delete;
296 MOZ_IMPLICIT MovingNotNull(const NotNull<T>& aSrc) : mBasePtr(aSrc) {}
298 template <typename U>
299 MOZ_IMPLICIT MovingNotNull(const NotNull<U>& aSrc) : mBasePtr(aSrc) {}
301 template <typename U>
302 MOZ_IMPLICIT MovingNotNull(MovingNotNull<U>&& aSrc)
303 : mBasePtr(std::move(aSrc).unwrapBasePtr()) {}
305 MOZ_IMPLICIT operator T() && { return std::move(*this).unwrapBasePtr(); }
307 MOZ_IMPLICIT operator NotNull<T>() && { return std::move(*this).unwrap(); }
309 NotNull<T> unwrap() && {
310 return WrapNotNullUnchecked(std::move(*this).unwrapBasePtr());
313 T unwrapBasePtr() && {
314 #ifdef DEBUG
315 MOZ_ASSERT(!mConsumed);
316 mConsumed = true;
317 #endif
318 return std::move(mBasePtr);
321 MovingNotNull(MovingNotNull&&) = default;
322 MovingNotNull& operator=(MovingNotNull&&) = default;
325 template <typename T>
326 constexpr MovingNotNull<T> WrapMovingNotNullUnchecked(T aBasePtr) {
327 return MovingNotNull<T>{std::move(aBasePtr)};
330 template <typename T>
331 constexpr MovingNotNull<T> WrapMovingNotNull(T aBasePtr) {
332 MOZ_RELEASE_ASSERT(aBasePtr);
333 return WrapMovingNotNullUnchecked(std::move(aBasePtr));
336 namespace detail {
338 // Extract the pointed-to type from a pointer type (be it raw or smart).
339 // The default implementation uses the dereferencing operator of the pointer
340 // type to find what it's pointing to.
341 template <typename Pointer>
342 struct PointedTo {
343 // Remove the reference that dereferencing operators may return.
344 using Type = std::remove_reference_t<decltype(*std::declval<Pointer>())>;
345 using NonConstType = std::remove_const_t<Type>;
348 // Specializations for raw pointers.
349 // This is especially required because VS 2017 15.6 (March 2018) started
350 // rejecting the above `decltype(*std::declval<Pointer>())` trick for raw
351 // pointers.
352 // See bug 1443367.
353 template <typename T>
354 struct PointedTo<T*> {
355 using Type = T;
356 using NonConstType = T;
359 template <typename T>
360 struct PointedTo<const T*> {
361 using Type = const T;
362 using NonConstType = T;
365 } // namespace detail
367 // Allocate an object with infallible new, and wrap its pointer in NotNull.
368 // |MakeNotNull<Ptr<Ob>>(args...)| will run |new Ob(args...)|
369 // and return NotNull<Ptr<Ob>>.
370 template <typename T, typename... Args>
371 constexpr NotNull<T> MakeNotNull(Args&&... aArgs) {
372 using Pointee = typename detail::PointedTo<T>::NonConstType;
373 static_assert(!std::is_array_v<Pointee>,
374 "MakeNotNull cannot construct an array");
375 return NotNull<T>(new Pointee(std::forward<Args>(aArgs)...));
378 // Compare two NotNulls.
379 template <typename T, typename U>
380 constexpr bool operator==(const NotNull<T>& aLhs, const NotNull<U>& aRhs) {
381 return aLhs.get() == aRhs.get();
383 template <typename T, typename U>
384 constexpr bool operator!=(const NotNull<T>& aLhs, const NotNull<U>& aRhs) {
385 return aLhs.get() != aRhs.get();
388 // Compare a NotNull to a base pointer.
389 template <typename T, typename U>
390 constexpr bool operator==(const NotNull<T>& aLhs, const U& aRhs) {
391 return aLhs.get() == aRhs;
393 template <typename T, typename U>
394 constexpr bool operator!=(const NotNull<T>& aLhs, const U& aRhs) {
395 return aLhs.get() != aRhs;
398 // Compare a base pointer to a NotNull.
399 template <typename T, typename U>
400 constexpr bool operator==(const T& aLhs, const NotNull<U>& aRhs) {
401 return aLhs == aRhs.get();
403 template <typename T, typename U>
404 constexpr bool operator!=(const T& aLhs, const NotNull<U>& aRhs) {
405 return aLhs != aRhs.get();
408 // Disallow comparing a NotNull to a nullptr.
409 template <typename T>
410 bool operator==(const NotNull<T>&, decltype(nullptr)) = delete;
411 template <typename T>
412 bool operator!=(const NotNull<T>&, decltype(nullptr)) = delete;
414 // Disallow comparing a nullptr to a NotNull.
415 template <typename T>
416 bool operator==(decltype(nullptr), const NotNull<T>&) = delete;
417 template <typename T>
418 bool operator!=(decltype(nullptr), const NotNull<T>&) = delete;
420 } // namespace mozilla
422 #endif /* mozilla_NotNull_h */