Bug 1642579 [wpt PR 23909] - [COOP access reporting] Preliminary WPT tests., a=testonly
[gecko.git] / mfbt / Maybe.h
blob4d26f7af91110b333af7d58cfa55c62df2dc99b8
1 /* -*- Mode: C++; tab-width: 2; 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 /* A class for optional values and in-place lazy construction. */
9 #ifndef mozilla_Maybe_h
10 #define mozilla_Maybe_h
12 #include <new> // for placement new
13 #include <ostream>
14 #include <type_traits>
15 #include <utility>
17 #include "mozilla/Alignment.h"
18 #include "mozilla/Assertions.h"
19 #include "mozilla/Attributes.h"
20 #include "mozilla/MemoryChecking.h"
21 #include "mozilla/OperatorNewExtensions.h"
22 #include "mozilla/Poison.h"
24 class nsCycleCollectionTraversalCallback;
26 template <typename T>
27 inline void CycleCollectionNoteChild(
28 nsCycleCollectionTraversalCallback& aCallback, T* aChild, const char* aName,
29 uint32_t aFlags);
31 namespace mozilla {
33 struct Nothing {};
35 inline constexpr bool operator==(const Nothing&, const Nothing&) {
36 return true;
39 template <class T>
40 class Maybe;
42 namespace detail {
44 // You would think that poisoning Maybe instances could just be a call
45 // to mozWritePoison. Unfortunately, using a simple call to
46 // mozWritePoison generates poor code on MSVC for small structures. The
47 // generated code contains (always not-taken) branches and does a bunch
48 // of setup for `rep stos{l,q}`, even though we know at compile time
49 // exactly how many words we're poisoning. Instead, we're going to
50 // force MSVC to generate the code we want via recursive templates.
52 // Write the given poisonValue into p at offset*sizeof(uintptr_t).
53 template <size_t offset>
54 inline void WritePoisonAtOffset(void* p, const uintptr_t poisonValue) {
55 memcpy(static_cast<char*>(p) + offset * sizeof(poisonValue), &poisonValue,
56 sizeof(poisonValue));
59 template <size_t Offset, size_t NOffsets>
60 struct InlinePoisoner {
61 static void poison(void* p, const uintptr_t poisonValue) {
62 WritePoisonAtOffset<Offset>(p, poisonValue);
63 InlinePoisoner<Offset + 1, NOffsets>::poison(p, poisonValue);
67 template <size_t N>
68 struct InlinePoisoner<N, N> {
69 static void poison(void*, const uintptr_t) {
70 // All done!
74 // We can't generate inline code for large structures, though, because we'll
75 // blow out recursive template instantiation limits, and the code would be
76 // bloated to boot. So provide a fallback to the out-of-line poisoner.
77 template <size_t ObjectSize>
78 struct OutOfLinePoisoner {
79 static MOZ_NEVER_INLINE void poison(void* p, const uintptr_t) {
80 mozWritePoison(p, ObjectSize);
84 template <typename T>
85 inline void PoisonObject(T* p) {
86 const uintptr_t POISON = mozPoisonValue();
87 std::conditional_t<(sizeof(T) <= 8 * sizeof(POISON)),
88 InlinePoisoner<0, sizeof(T) / sizeof(POISON)>,
89 OutOfLinePoisoner<sizeof(T)>>::poison(p, POISON);
92 template <typename T>
93 struct MaybePoisoner {
94 static const size_t N = sizeof(T);
96 static void poison(void* aPtr) {
97 #ifdef MOZ_DIAGNOSTIC_ASSERT_ENABLED
98 if (N >= sizeof(uintptr_t)) {
99 PoisonObject(static_cast<std::remove_cv_t<T>*>(aPtr));
101 #endif
102 MOZ_MAKE_MEM_UNDEFINED(aPtr, N);
106 template <typename T>
107 constexpr bool IsTriviallyDestructibleAndCopyable =
108 std::is_trivially_destructible_v<T> &&
109 (std::is_trivially_copy_constructible_v<T> ||
110 !std::is_copy_constructible_v<T>);
112 template <typename T,
113 bool TriviallyDestructibleAndCopyable =
114 IsTriviallyDestructibleAndCopyable<T>,
115 bool Copyable = std::is_copy_constructible_v<T>,
116 bool Movable = std::is_move_constructible_v<T>>
117 class Maybe_CopyMove_Enabler;
119 #define MOZ_MAYBE_COPY_OPS() \
120 Maybe_CopyMove_Enabler(const Maybe_CopyMove_Enabler& aOther) { \
121 if (downcast(aOther).isSome()) { \
122 downcast(*this).emplace(*downcast(aOther)); \
126 Maybe_CopyMove_Enabler& operator=(const Maybe_CopyMove_Enabler& aOther) { \
127 return downcast(*this).template operator=<T>(downcast(aOther)); \
130 #define MOZ_MAYBE_MOVE_OPS() \
131 constexpr Maybe_CopyMove_Enabler(Maybe_CopyMove_Enabler&& aOther) { \
132 if (downcast(aOther).isSome()) { \
133 downcast(*this).emplace(std::move(*downcast(aOther))); \
134 downcast(aOther).reset(); \
138 constexpr Maybe_CopyMove_Enabler& operator=( \
139 Maybe_CopyMove_Enabler&& aOther) { \
140 downcast(*this).template operator=<T>(std::move(downcast(aOther))); \
142 return *this; \
145 #define MOZ_MAYBE_DOWNCAST() \
146 static constexpr Maybe<T>& downcast(Maybe_CopyMove_Enabler& aObj) { \
147 return static_cast<Maybe<T>&>(aObj); \
149 static constexpr const Maybe<T>& downcast( \
150 const Maybe_CopyMove_Enabler& aObj) { \
151 return static_cast<const Maybe<T>&>(aObj); \
154 template <typename T>
155 class Maybe_CopyMove_Enabler<T, true, true, true> {
156 public:
157 Maybe_CopyMove_Enabler() = default;
159 Maybe_CopyMove_Enabler(const Maybe_CopyMove_Enabler&) = default;
160 Maybe_CopyMove_Enabler& operator=(const Maybe_CopyMove_Enabler&) = default;
161 constexpr Maybe_CopyMove_Enabler(Maybe_CopyMove_Enabler&& aOther) {
162 downcast(aOther).reset();
164 constexpr Maybe_CopyMove_Enabler& operator=(Maybe_CopyMove_Enabler&& aOther) {
165 downcast(aOther).reset();
166 return *this;
169 private:
170 MOZ_MAYBE_DOWNCAST()
173 template <typename T>
174 class Maybe_CopyMove_Enabler<T, true, false, true> {
175 public:
176 Maybe_CopyMove_Enabler() = default;
178 Maybe_CopyMove_Enabler(const Maybe_CopyMove_Enabler&) = delete;
179 Maybe_CopyMove_Enabler& operator=(const Maybe_CopyMove_Enabler&) = delete;
180 constexpr Maybe_CopyMove_Enabler(Maybe_CopyMove_Enabler&& aOther) {
181 downcast(aOther).reset();
183 constexpr Maybe_CopyMove_Enabler& operator=(Maybe_CopyMove_Enabler&& aOther) {
184 downcast(aOther).reset();
185 return *this;
188 private:
189 MOZ_MAYBE_DOWNCAST()
192 template <typename T>
193 class Maybe_CopyMove_Enabler<T, false, true, true> {
194 public:
195 Maybe_CopyMove_Enabler() = default;
197 MOZ_MAYBE_COPY_OPS()
198 MOZ_MAYBE_MOVE_OPS()
200 private:
201 MOZ_MAYBE_DOWNCAST()
204 template <typename T>
205 class Maybe_CopyMove_Enabler<T, false, false, true> {
206 public:
207 Maybe_CopyMove_Enabler() = default;
209 MOZ_MAYBE_MOVE_OPS()
211 private:
212 MOZ_MAYBE_DOWNCAST()
215 template <typename T>
216 class Maybe_CopyMove_Enabler<T, false, true, false> {
217 public:
218 Maybe_CopyMove_Enabler() = default;
220 MOZ_MAYBE_COPY_OPS()
222 private:
223 MOZ_MAYBE_DOWNCAST()
226 template <typename T, bool TriviallyDestructibleAndCopyable>
227 class Maybe_CopyMove_Enabler<T, TriviallyDestructibleAndCopyable, false,
228 false> {
229 public:
230 Maybe_CopyMove_Enabler() = default;
232 Maybe_CopyMove_Enabler(const Maybe_CopyMove_Enabler&) = delete;
233 Maybe_CopyMove_Enabler& operator=(const Maybe_CopyMove_Enabler&) = delete;
234 Maybe_CopyMove_Enabler(Maybe_CopyMove_Enabler&&) = delete;
235 Maybe_CopyMove_Enabler& operator=(Maybe_CopyMove_Enabler&&) = delete;
238 #undef MOZ_MAYBE_COPY_OPS
239 #undef MOZ_MAYBE_MOVE_OPS
240 #undef MOZ_MAYBE_DOWNCAST
242 template <typename T, bool TriviallyDestructibleAndCopyable =
243 IsTriviallyDestructibleAndCopyable<T>>
244 struct MaybeStorage;
246 template <typename T>
247 struct MaybeStorage<T, false> {
248 using NonConstT = std::remove_const_t<T>;
250 union Union {
251 Union() {}
252 constexpr explicit Union(const T& aVal) : val{aVal} {}
253 template <typename U,
254 typename = std::enable_if_t<std::is_move_constructible_v<U>>>
255 constexpr explicit Union(U&& aVal) : val{std::forward<U>(aVal)} {}
257 ~Union() {}
259 NonConstT val;
260 char dummy;
261 } mStorage;
262 char mIsSome = false; // not bool -- guarantees minimal space consumption
264 MaybeStorage() = default;
265 explicit MaybeStorage(const T& aVal) : mStorage{aVal}, mIsSome{true} {}
266 explicit MaybeStorage(T&& aVal) : mStorage{std::move(aVal)}, mIsSome{true} {}
268 // Copy and move operations are no-ops, since copying is moving is implemented
269 // by Maybe_CopyMove_Enabler.
271 MaybeStorage(const MaybeStorage&) {}
272 MaybeStorage& operator=(const MaybeStorage&) { return *this; }
273 MaybeStorage(MaybeStorage&&) {}
274 MaybeStorage& operator=(MaybeStorage&&) { return *this; }
276 ~MaybeStorage() {
277 if (mIsSome) {
278 mStorage.val.T::~T();
283 template <typename T>
284 struct MaybeStorage<T, true> {
285 using NonConstT = std::remove_const_t<T>;
287 union Union {
288 constexpr Union() : dummy() {}
289 constexpr explicit Union(const T& aVal) : val{aVal} {}
290 constexpr explicit Union(T&& aVal) : val{std::move(aVal)} {}
292 NonConstT val;
293 char dummy;
294 } mStorage;
295 char mIsSome = false; // not bool -- guarantees minimal space consumption
297 constexpr MaybeStorage() = default;
298 constexpr explicit MaybeStorage(const T& aVal)
299 : mStorage{aVal}, mIsSome{true} {}
300 constexpr explicit MaybeStorage(T&& aVal)
301 : mStorage{std::move(aVal)}, mIsSome{true} {}
304 } // namespace detail
306 template <typename T, typename U = typename std::remove_cv<
307 typename std::remove_reference<T>::type>::type>
308 constexpr Maybe<U> Some(T&& aValue);
311 * Maybe is a container class which contains either zero or one elements. It
312 * serves two roles. It can represent values which are *semantically* optional,
313 * augmenting a type with an explicit 'Nothing' value. In this role, it provides
314 * methods that make it easy to work with values that may be missing, along with
315 * equality and comparison operators so that Maybe values can be stored in
316 * containers. Maybe values can be constructed conveniently in expressions using
317 * type inference, as follows:
319 * void doSomething(Maybe<Foo> aFoo) {
320 * if (aFoo) // Make sure that aFoo contains a value...
321 * aFoo->takeAction(); // and then use |aFoo->| to access it.
322 * } // |*aFoo| also works!
324 * doSomething(Nothing()); // Passes a Maybe<Foo> containing no value.
325 * doSomething(Some(Foo(100))); // Passes a Maybe<Foo> containing |Foo(100)|.
327 * You'll note that it's important to check whether a Maybe contains a value
328 * before using it, using conversion to bool, |isSome()|, or |isNothing()|. You
329 * can avoid these checks, and sometimes write more readable code, using
330 * |valueOr()|, |ptrOr()|, and |refOr()|, which allow you to retrieve the value
331 * in the Maybe and provide a default for the 'Nothing' case. You can also use
332 * |apply()| to call a function only if the Maybe holds a value, and |map()| to
333 * transform the value in the Maybe, returning another Maybe with a possibly
334 * different type.
336 * Maybe's other role is to support lazily constructing objects without using
337 * dynamic storage. A Maybe directly contains storage for a value, but it's
338 * empty by default. |emplace()|, as mentioned above, can be used to construct a
339 * value in Maybe's storage. The value a Maybe contains can be destroyed by
340 * calling |reset()|; this will happen automatically if a Maybe is destroyed
341 * while holding a value.
343 * It's a common idiom in C++ to use a pointer as a 'Maybe' type, with a null
344 * value meaning 'Nothing' and any other value meaning 'Some'. You can convert
345 * from such a pointer to a Maybe value using 'ToMaybe()'.
347 * Maybe is inspired by similar types in the standard library of many other
348 * languages (e.g. Haskell's Maybe and Rust's Option). In the C++ world it's
349 * very similar to std::optional, which was proposed for C++14 and originated in
350 * Boost. The most important differences between Maybe and std::optional are:
352 * - std::optional<T> may be compared with T. We deliberately forbid that.
353 * - std::optional allows in-place construction without a separate call to
354 * |emplace()| by using a dummy |in_place_t| value to tag the appropriate
355 * constructor.
356 * - std::optional has |valueOr()|, equivalent to Maybe's |valueOr()|, but
357 * lacks corresponding methods for |refOr()| and |ptrOr()|.
358 * - std::optional lacks |map()| and |apply()|, making it less suitable for
359 * functional-style code.
360 * - std::optional lacks many convenience functions that Maybe has. Most
361 * unfortunately, it lacks equivalents of the type-inferred constructor
362 * functions |Some()| and |Nothing()|.
364 template <class T>
365 class MOZ_INHERIT_TYPE_ANNOTATIONS_FROM_TEMPLATE_ARGS Maybe
366 : private detail::MaybeStorage<T>,
367 public detail::Maybe_CopyMove_Enabler<T> {
368 template <typename, bool, bool, bool>
369 friend class detail::Maybe_CopyMove_Enabler;
371 template <typename U, typename V>
372 friend constexpr Maybe<V> Some(U&& aValue);
374 struct SomeGuard {};
376 template <typename U>
377 constexpr Maybe(U&& aValue, SomeGuard)
378 : detail::MaybeStorage<T>{std::forward<U>(aValue)} {}
380 using detail::MaybeStorage<T>::mIsSome;
381 using detail::MaybeStorage<T>::mStorage;
383 void poisonData() { detail::MaybePoisoner<T>::poison(&mStorage.val); }
385 public:
386 using ValueType = T;
388 MOZ_ALLOW_TEMPORARY constexpr Maybe() = default;
390 MOZ_ALLOW_TEMPORARY MOZ_IMPLICIT constexpr Maybe(Nothing) : Maybe{} {}
393 * Maybe<T> can be copy-constructed from a Maybe<U> if T is constructible from
394 * a const U&.
396 template <typename U,
397 typename = std::enable_if_t<std::is_constructible_v<T, const U&>>>
398 MOZ_IMPLICIT Maybe(const Maybe<U>& aOther) {
399 if (aOther.isSome()) {
400 emplace(*aOther);
405 * Maybe<T> can be move-constructed from a Maybe<U> if T is constructible from
406 * a U&&.
408 template <typename U,
409 typename = std::enable_if_t<std::is_constructible_v<T, U&&>>>
410 MOZ_IMPLICIT Maybe(Maybe<U>&& aOther) {
411 if (aOther.isSome()) {
412 emplace(std::move(*aOther));
413 aOther.reset();
417 template <typename U,
418 typename = std::enable_if_t<std::is_constructible_v<T, const U&>>>
419 Maybe& operator=(const Maybe<U>& aOther) {
420 if (aOther.isSome()) {
421 if (mIsSome) {
422 ref() = aOther.ref();
423 } else {
424 emplace(*aOther);
426 } else {
427 reset();
429 return *this;
432 template <typename U,
433 typename = std::enable_if_t<std::is_constructible_v<T, U&&>>>
434 Maybe& operator=(Maybe<U>&& aOther) {
435 if (aOther.isSome()) {
436 if (mIsSome) {
437 ref() = std::move(aOther.ref());
438 } else {
439 emplace(std::move(*aOther));
441 aOther.reset();
442 } else {
443 reset();
446 return *this;
449 constexpr Maybe& operator=(Nothing) {
450 reset();
451 return *this;
454 /* Methods that check whether this Maybe contains a value */
455 constexpr explicit operator bool() const { return isSome(); }
456 constexpr bool isSome() const { return mIsSome; }
457 constexpr bool isNothing() const { return !mIsSome; }
459 /* Returns the contents of this Maybe<T> by value. Unsafe unless |isSome()|.
461 constexpr T value() const;
464 * Move the contents of this Maybe<T> out of internal storage and return it
465 * without calling the destructor. The internal storage is also reset to
466 * avoid multiple calls. Unsafe unless |isSome()|.
468 T extract() {
469 MOZ_DIAGNOSTIC_ASSERT(isSome());
470 auto v = std::move(mStorage.val);
471 reset();
472 return v;
476 * Returns the value (possibly |Nothing()|) by moving it out of this Maybe<T>
477 * and leaving |Nothing()| in its place.
479 Maybe<T> take() { return std::exchange(*this, Nothing()); }
482 * Returns the contents of this Maybe<T> by value. If |isNothing()|, returns
483 * the default value provided.
485 template <typename V>
486 constexpr T valueOr(V&& aDefault) const {
487 if (isSome()) {
488 return ref();
490 return std::forward<V>(aDefault);
494 * Returns the contents of this Maybe<T> by value. If |isNothing()|, returns
495 * the value returned from the function or functor provided.
497 template <typename F>
498 constexpr T valueOrFrom(F&& aFunc) const {
499 if (isSome()) {
500 return ref();
502 return aFunc();
505 /* Returns the contents of this Maybe<T> by pointer. Unsafe unless |isSome()|.
507 T* ptr();
508 constexpr const T* ptr() const;
511 * Returns the contents of this Maybe<T> by pointer. If |isNothing()|,
512 * returns the default value provided.
514 T* ptrOr(T* aDefault) {
515 if (isSome()) {
516 return ptr();
518 return aDefault;
521 constexpr const T* ptrOr(const T* aDefault) const {
522 if (isSome()) {
523 return ptr();
525 return aDefault;
529 * Returns the contents of this Maybe<T> by pointer. If |isNothing()|,
530 * returns the value returned from the function or functor provided.
532 template <typename F>
533 T* ptrOrFrom(F&& aFunc) {
534 if (isSome()) {
535 return ptr();
537 return aFunc();
540 template <typename F>
541 const T* ptrOrFrom(F&& aFunc) const {
542 if (isSome()) {
543 return ptr();
545 return aFunc();
548 constexpr T* operator->();
549 constexpr const T* operator->() const;
551 /* Returns the contents of this Maybe<T> by ref. Unsafe unless |isSome()|. */
552 constexpr T& ref();
553 constexpr const T& ref() const;
556 * Returns the contents of this Maybe<T> by ref. If |isNothing()|, returns
557 * the default value provided.
559 constexpr T& refOr(T& aDefault) {
560 if (isSome()) {
561 return ref();
563 return aDefault;
566 constexpr const T& refOr(const T& aDefault) const {
567 if (isSome()) {
568 return ref();
570 return aDefault;
574 * Returns the contents of this Maybe<T> by ref. If |isNothing()|, returns the
575 * value returned from the function or functor provided.
577 template <typename F>
578 constexpr T& refOrFrom(F&& aFunc) {
579 if (isSome()) {
580 return ref();
582 return aFunc();
585 template <typename F>
586 constexpr const T& refOrFrom(F&& aFunc) const {
587 if (isSome()) {
588 return ref();
590 return aFunc();
593 constexpr T& operator*();
594 constexpr const T& operator*() const;
596 /* If |isSome()|, runs the provided function or functor on the contents of
597 * this Maybe. */
598 template <typename Func>
599 constexpr Maybe& apply(Func&& aFunc) {
600 if (isSome()) {
601 std::forward<Func>(aFunc)(ref());
603 return *this;
606 template <typename Func>
607 constexpr const Maybe& apply(Func&& aFunc) const {
608 if (isSome()) {
609 std::forward<Func>(aFunc)(ref());
611 return *this;
615 * If |isSome()|, runs the provided function and returns the result wrapped
616 * in a Maybe. If |isNothing()|, returns an empty Maybe value with the same
617 * value type as what the provided function would have returned.
619 template <typename Func>
620 constexpr auto map(Func&& aFunc) {
621 if (isSome()) {
622 return Some(std::forward<Func>(aFunc)(ref()));
624 return Maybe<decltype(std::forward<Func>(aFunc)(ref()))>{};
627 template <typename Func>
628 constexpr auto map(Func&& aFunc) const {
629 if (isSome()) {
630 return Some(std::forward<Func>(aFunc)(ref()));
632 return Maybe<decltype(std::forward<Func>(aFunc)(ref()))>{};
635 /* If |isSome()|, empties this Maybe and destroys its contents. */
636 constexpr void reset() {
637 if (isSome()) {
638 if constexpr (!std::is_trivially_destructible_v<T>) {
639 ref().T::~T();
640 poisonData();
642 mIsSome = false;
647 * Constructs a T value in-place in this empty Maybe<T>'s storage. The
648 * arguments to |emplace()| are the parameters to T's constructor.
650 template <typename... Args>
651 constexpr void emplace(Args&&... aArgs);
653 template <typename U>
654 constexpr std::enable_if_t<std::is_same_v<T, U> &&
655 std::is_copy_constructible_v<U> &&
656 !std::is_move_constructible_v<U>>
657 emplace(U&& aArgs) {
658 emplace(aArgs);
661 friend std::ostream& operator<<(std::ostream& aStream,
662 const Maybe<T>& aMaybe) {
663 if (aMaybe) {
664 aStream << aMaybe.ref();
665 } else {
666 aStream << "<Nothing>";
668 return aStream;
672 template <typename T>
673 class Maybe<T&> {
674 public:
675 constexpr Maybe() = default;
676 constexpr MOZ_IMPLICIT Maybe(Nothing) {}
678 void emplace(T& aRef) { mValue = &aRef; }
680 /* Methods that check whether this Maybe contains a value */
681 constexpr explicit operator bool() const { return isSome(); }
682 constexpr bool isSome() const { return mValue; }
683 constexpr bool isNothing() const { return !mValue; }
685 T& ref() const {
686 MOZ_DIAGNOSTIC_ASSERT(isSome());
687 return *mValue;
690 T* operator->() const { return &ref(); }
691 T& operator*() const { return ref(); }
693 // Deliberately not defining value and ptr accessors, as these may be
694 // confusing on a reference-typed Maybe.
696 // XXX Should we define refOr?
698 void reset() { mValue = nullptr; }
700 template <typename Func>
701 Maybe& apply(Func&& aFunc) {
702 if (isSome()) {
703 std::forward<Func>(aFunc)(ref());
705 return *this;
708 template <typename Func>
709 const Maybe& apply(Func&& aFunc) const {
710 if (isSome()) {
711 std::forward<Func>(aFunc)(ref());
713 return *this;
716 template <typename Func>
717 auto map(Func&& aFunc) {
718 Maybe<decltype(std::forward<Func>(aFunc)(ref()))> val;
719 if (isSome()) {
720 val.emplace(std::forward<Func>(aFunc)(ref()));
722 return val;
725 template <typename Func>
726 auto map(Func&& aFunc) const {
727 Maybe<decltype(std::forward<Func>(aFunc)(ref()))> val;
728 if (isSome()) {
729 val.emplace(std::forward<Func>(aFunc)(ref()));
731 return val;
734 private:
735 T* mValue = nullptr;
738 template <typename T>
739 constexpr T Maybe<T>::value() const {
740 MOZ_DIAGNOSTIC_ASSERT(isSome());
741 return ref();
744 template <typename T>
745 T* Maybe<T>::ptr() {
746 MOZ_DIAGNOSTIC_ASSERT(isSome());
747 return &ref();
750 template <typename T>
751 constexpr const T* Maybe<T>::ptr() const {
752 MOZ_DIAGNOSTIC_ASSERT(isSome());
753 return &ref();
756 template <typename T>
757 constexpr T* Maybe<T>::operator->() {
758 MOZ_DIAGNOSTIC_ASSERT(isSome());
759 return ptr();
762 template <typename T>
763 constexpr const T* Maybe<T>::operator->() const {
764 MOZ_DIAGNOSTIC_ASSERT(isSome());
765 return ptr();
768 template <typename T>
769 constexpr T& Maybe<T>::ref() {
770 MOZ_DIAGNOSTIC_ASSERT(isSome());
771 return mStorage.val;
774 template <typename T>
775 constexpr const T& Maybe<T>::ref() const {
776 MOZ_DIAGNOSTIC_ASSERT(isSome());
777 return mStorage.val;
780 template <typename T>
781 constexpr T& Maybe<T>::operator*() {
782 MOZ_DIAGNOSTIC_ASSERT(isSome());
783 return ref();
786 template <typename T>
787 constexpr const T& Maybe<T>::operator*() const {
788 MOZ_DIAGNOSTIC_ASSERT(isSome());
789 return ref();
792 template <typename T>
793 template <typename... Args>
794 constexpr void Maybe<T>::emplace(Args&&... aArgs) {
795 MOZ_DIAGNOSTIC_ASSERT(!isSome());
796 ::new (KnownNotNull, &mStorage.val) T(std::forward<Args>(aArgs)...);
797 mIsSome = true;
801 * Some() creates a Maybe<T> value containing the provided T value. If T has a
802 * move constructor, it's used to make this as efficient as possible.
804 * Some() selects the type of Maybe it returns by removing any const, volatile,
805 * or reference qualifiers from the type of the value you pass to it. This gives
806 * it more intuitive behavior when used in expressions, but it also means that
807 * if you need to construct a Maybe value that holds a const, volatile, or
808 * reference value, you need to use emplace() instead.
810 template <typename T, typename U>
811 constexpr Maybe<U> Some(T&& aValue) {
812 return {std::forward<T>(aValue), typename Maybe<U>::SomeGuard{}};
815 template <typename T>
816 constexpr Maybe<T&> SomeRef(T& aValue) {
817 Maybe<T&> value;
818 value.emplace(aValue);
819 return value;
822 template <typename T>
823 Maybe<std::remove_cv_t<std::remove_reference_t<T>>> ToMaybe(T* aPtr) {
824 if (aPtr) {
825 return Some(*aPtr);
827 return Nothing();
831 * Two Maybe<T> values are equal if
832 * - both are Nothing, or
833 * - both are Some, and the values they contain are equal.
835 template <typename T>
836 constexpr bool operator==(const Maybe<T>& aLHS, const Maybe<T>& aRHS) {
837 static_assert(!std::is_reference_v<T>,
838 "operator== is not defined for Maybe<T&>, compare values or "
839 "addresses explicitly instead");
840 if (aLHS.isNothing() != aRHS.isNothing()) {
841 return false;
843 return aLHS.isNothing() || *aLHS == *aRHS;
846 template <typename T>
847 constexpr bool operator!=(const Maybe<T>& aLHS, const Maybe<T>& aRHS) {
848 return !(aLHS == aRHS);
852 * We support comparison to Nothing to allow reasonable expressions like:
853 * if (maybeValue == Nothing()) { ... }
855 template <typename T>
856 constexpr bool operator==(const Maybe<T>& aLHS, const Nothing& aRHS) {
857 return aLHS.isNothing();
860 template <typename T>
861 constexpr bool operator!=(const Maybe<T>& aLHS, const Nothing& aRHS) {
862 return !(aLHS == aRHS);
865 template <typename T>
866 constexpr bool operator==(const Nothing& aLHS, const Maybe<T>& aRHS) {
867 return aRHS.isNothing();
870 template <typename T>
871 constexpr bool operator!=(const Nothing& aLHS, const Maybe<T>& aRHS) {
872 return !(aLHS == aRHS);
876 * Maybe<T> values are ordered in the same way T values are ordered, except that
877 * Nothing comes before anything else.
879 template <typename T>
880 constexpr bool operator<(const Maybe<T>& aLHS, const Maybe<T>& aRHS) {
881 if (aLHS.isNothing()) {
882 return aRHS.isSome();
884 if (aRHS.isNothing()) {
885 return false;
887 return *aLHS < *aRHS;
890 template <typename T>
891 constexpr bool operator>(const Maybe<T>& aLHS, const Maybe<T>& aRHS) {
892 return !(aLHS < aRHS || aLHS == aRHS);
895 template <typename T>
896 constexpr bool operator<=(const Maybe<T>& aLHS, const Maybe<T>& aRHS) {
897 return aLHS < aRHS || aLHS == aRHS;
900 template <typename T>
901 constexpr bool operator>=(const Maybe<T>& aLHS, const Maybe<T>& aRHS) {
902 return !(aLHS < aRHS);
905 template <typename T>
906 inline void ImplCycleCollectionTraverse(
907 nsCycleCollectionTraversalCallback& aCallback, mozilla::Maybe<T>& aField,
908 const char* aName, uint32_t aFlags = 0) {
909 if (aField) {
910 ImplCycleCollectionTraverse(aCallback, aField.ref(), aName, aFlags);
914 template <typename T>
915 inline void ImplCycleCollectionUnlink(mozilla::Maybe<T>& aField) {
916 if (aField) {
917 ImplCycleCollectionUnlink(aField.ref());
921 } // namespace mozilla
923 #endif /* mozilla_Maybe_h */