Debian Codegraph @

mfbt/Maybe.h

raw
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/. */
6
7 /* A class for optional values and in-place lazy construction. */
8
9 #ifndef mozilla_Maybe_h
10 #define mozilla_Maybe_h
11
12 #include <functional>
13 #include <new> // for placement new
14 #include <ostream>
15 #include <type_traits>
16 #include <utility>
17
18 #include "mozilla/Alignment.h"
19 #include "mozilla/Assertions.h"
20 #include "mozilla/Attributes.h"
21 #include "mozilla/MaybeStorageBase.h"
22 #include "mozilla/MemoryChecking.h"
23 #include "mozilla/OperatorNewExtensions.h"
24 #include "mozilla/Poison.h"
25 #include "mozilla/ThreadSafety.h"
26
27 class nsCycleCollectionTraversalCallback;
28
29 template <typename T>
30 inline void CycleCollectionNoteChild(
31 nsCycleCollectionTraversalCallback& aCallback, T* aChild, const char* aName,
32 uint32_t aFlags);
33
34 namespace mozilla {
35
36 struct Nothing {};
37
38 inline constexpr bool operator==(const Nothing&, const Nothing&) {
39 return true;
40 }
41
42 template <class T>
43 class Maybe;
44
45 namespace detail {
46
47 // You would think that poisoning Maybe instances could just be a call
48 // to mozWritePoison. Unfortunately, using a simple call to
49 // mozWritePoison generates poor code on MSVC for small structures. The
50 // generated code contains (always not-taken) branches and does a bunch
51 // of setup for `rep stos{l,q}`, even though we know at compile time
52 // exactly how many words we're poisoning. Instead, we're going to
53 // force MSVC to generate the code we want via recursive templates.
54
55 // Write the given poisonValue into p at offset*sizeof(uintptr_t).
56 template <size_t offset>
57 inline void WritePoisonAtOffset(void* p, const uintptr_t poisonValue) {
58 memcpy(static_cast<char*>(p) + offset * sizeof(poisonValue), &poisonValue,
59 sizeof(poisonValue));
60 }
61
62 template <size_t Offset, size_t NOffsets>
63 struct InlinePoisoner {
64 static void poison(void* p, const uintptr_t poisonValue) {
65 WritePoisonAtOffset<Offset>(p, poisonValue);
66 InlinePoisoner<Offset + 1, NOffsets>::poison(p, poisonValue);
67 }
68 };
69
70 template <size_t N>
71 struct InlinePoisoner<N, N> {
72 static void poison(void*, const uintptr_t) {
73 // All done!
74 }
75 };
76
77 // We can't generate inline code for large structures, though, because we'll
78 // blow out recursive template instantiation limits, and the code would be
79 // bloated to boot. So provide a fallback to the out-of-line poisoner.
80 template <size_t ObjectSize>
81 struct OutOfLinePoisoner {
82 static MOZ_NEVER_INLINE void poison(void* p, const uintptr_t) {
83 mozWritePoison(p, ObjectSize);
84 }
85 };
86
87 template <typename T>
88 inline void PoisonObject(T* p) {
89 const uintptr_t POISON = mozPoisonValue();
90 std::conditional_t<(sizeof(T) <= 8 * sizeof(POISON)),
91 InlinePoisoner<0, sizeof(T) / sizeof(POISON)>,
92 OutOfLinePoisoner<sizeof(T)>>::poison(p, POISON);
93 }
94
95 template <typename T>
96 struct MaybePoisoner {
97 static const size_t N = sizeof(T);
98
99 static void poison(void* aPtr) {
100 #ifdef MOZ_DIAGNOSTIC_ASSERT_ENABLED
101 if (N >= sizeof(uintptr_t)) {
102 PoisonObject(static_cast<std::remove_cv_t<T>*>(aPtr));
103 }
104 #endif
105 MOZ_MAKE_MEM_UNDEFINED(aPtr, N);
106 }
107 };
108
109 template <typename T,
110 bool TriviallyDestructibleAndCopyable =
111 IsTriviallyDestructibleAndCopyable<T>,
112 bool Copyable = std::is_copy_constructible_v<T>,
113 bool Movable = std::is_move_constructible_v<T>>
114 class Maybe_CopyMove_Enabler;
115
116 #define MOZ_MAYBE_COPY_OPS() \
117 Maybe_CopyMove_Enabler(const Maybe_CopyMove_Enabler& aOther) { \
118 if (downcast(aOther).isSome()) { \
119 downcast(*this).emplace(*downcast(aOther)); \
120 } \
121 } \
122 \
123 Maybe_CopyMove_Enabler& operator=(const Maybe_CopyMove_Enabler& aOther) { \
124 return downcast(*this).template operator= <T>(downcast(aOther)); \
125 }
126
127 #define MOZ_MAYBE_MOVE_OPS() \
128 constexpr Maybe_CopyMove_Enabler(Maybe_CopyMove_Enabler&& aOther) { \
129 if (downcast(aOther).isSome()) { \
130 downcast(*this).emplace(std::move(*downcast(aOther))); \
131 downcast(aOther).reset(); \
132 } \
133 } \
134 \
135 constexpr Maybe_CopyMove_Enabler& operator=( \
136 Maybe_CopyMove_Enabler&& aOther) { \
137 downcast(*this).template operator= <T>(std::move(downcast(aOther))); \
138 \
139 return *this; \
140 }
141
142 #define MOZ_MAYBE_DOWNCAST() \
143 static constexpr Maybe<T>& downcast(Maybe_CopyMove_Enabler& aObj) { \
144 return static_cast<Maybe<T>&>(aObj); \
145 } \
146 static constexpr const Maybe<T>& downcast( \
147 const Maybe_CopyMove_Enabler& aObj) { \
148 return static_cast<const Maybe<T>&>(aObj); \
149 }
150
151 template <typename T>
152 class Maybe_CopyMove_Enabler<T, true, true, true> {
153 public:
154 Maybe_CopyMove_Enabler() = default;
155
156 Maybe_CopyMove_Enabler(const Maybe_CopyMove_Enabler&) = default;
157 Maybe_CopyMove_Enabler& operator=(const Maybe_CopyMove_Enabler&) = default;
158 constexpr Maybe_CopyMove_Enabler(Maybe_CopyMove_Enabler&& aOther) {
159 downcast(aOther).reset();
160 }
161 constexpr Maybe_CopyMove_Enabler& operator=(Maybe_CopyMove_Enabler&& aOther) {
162 downcast(aOther).reset();
163 return *this;
164 }
165
166 private:
167 MOZ_MAYBE_DOWNCAST()
168 };
169
170 template <typename T>
171 class Maybe_CopyMove_Enabler<T, true, false, true> {
172 public:
173 Maybe_CopyMove_Enabler() = default;
174
175 Maybe_CopyMove_Enabler(const Maybe_CopyMove_Enabler&) = delete;
176 Maybe_CopyMove_Enabler& operator=(const Maybe_CopyMove_Enabler&) = delete;
177 constexpr Maybe_CopyMove_Enabler(Maybe_CopyMove_Enabler&& aOther) {
178 downcast(aOther).reset();
179 }
180 constexpr Maybe_CopyMove_Enabler& operator=(Maybe_CopyMove_Enabler&& aOther) {
181 downcast(aOther).reset();
182 return *this;
183 }
184
185 private:
186 MOZ_MAYBE_DOWNCAST()
187 };
188
189 template <typename T>
190 class Maybe_CopyMove_Enabler<T, false, true, true> {
191 public:
192 Maybe_CopyMove_Enabler() = default;
193
194 MOZ_MAYBE_COPY_OPS()
195 MOZ_MAYBE_MOVE_OPS()
196
197 private:
198 MOZ_MAYBE_DOWNCAST()
199 };
200
201 template <typename T>
202 class Maybe_CopyMove_Enabler<T, false, false, true> {
203 public:
204 Maybe_CopyMove_Enabler() = default;
205
206 Maybe_CopyMove_Enabler(const Maybe_CopyMove_Enabler&) = delete;
207 Maybe_CopyMove_Enabler& operator=(const Maybe_CopyMove_Enabler&) = delete;
208 MOZ_MAYBE_MOVE_OPS()
209
210 private:
211 MOZ_MAYBE_DOWNCAST()
212 };
213
214 template <typename T>
215 class Maybe_CopyMove_Enabler<T, false, true, false> {
216 public:
217 Maybe_CopyMove_Enabler() = default;
218
219 MOZ_MAYBE_COPY_OPS()
220 Maybe_CopyMove_Enabler(Maybe_CopyMove_Enabler&&) = delete;
221 Maybe_CopyMove_Enabler& operator=(Maybe_CopyMove_Enabler&&) = delete;
222
223 private:
224 MOZ_MAYBE_DOWNCAST()
225 };
226
227 template <typename T, bool TriviallyDestructibleAndCopyable>
228 class Maybe_CopyMove_Enabler<T, TriviallyDestructibleAndCopyable, false,
229 false> {
230 public:
231 Maybe_CopyMove_Enabler() = default;
232
233 Maybe_CopyMove_Enabler(const Maybe_CopyMove_Enabler&) = delete;
234 Maybe_CopyMove_Enabler& operator=(const Maybe_CopyMove_Enabler&) = delete;
235 Maybe_CopyMove_Enabler(Maybe_CopyMove_Enabler&&) = delete;
236 Maybe_CopyMove_Enabler& operator=(Maybe_CopyMove_Enabler&&) = delete;
237 };
238
239 #undef MOZ_MAYBE_COPY_OPS
240 #undef MOZ_MAYBE_MOVE_OPS
241 #undef MOZ_MAYBE_DOWNCAST
242
243 template <typename T, bool TriviallyDestructibleAndCopyable =
244 IsTriviallyDestructibleAndCopyable<T>>
245 struct MaybeStorage;
246
247 template <typename T>
248 struct MaybeStorage<T, false> : MaybeStorageBase<T> {
249 protected:
250 char mIsSome = false; // not bool -- guarantees minimal space consumption
251
252 constexpr MaybeStorage() = default;
253 explicit MaybeStorage(const T& aVal)
254 : MaybeStorageBase<T>{aVal}, mIsSome{true} {}
255 explicit MaybeStorage(T&& aVal)
256 : MaybeStorageBase<T>{std::move(aVal)}, mIsSome{true} {}
257
258 template <typename... Args>
259 explicit MaybeStorage(std::in_place_t, Args&&... aArgs)
260 : MaybeStorageBase<T>{std::in_place, std::forward<Args>(aArgs)...},
261 mIsSome{true} {}
262
263 public:
264 // Copy and move operations are no-ops, since copying is moving is implemented
265 // by Maybe_CopyMove_Enabler.
266
267 MaybeStorage(const MaybeStorage&) : MaybeStorageBase<T>{} {}
268 MaybeStorage& operator=(const MaybeStorage&) { return *this; }
269 MaybeStorage(MaybeStorage&&) : MaybeStorageBase<T>{} {}
270 MaybeStorage& operator=(MaybeStorage&&) { return *this; }
271
272 ~MaybeStorage() {
273 if (mIsSome) {
274 this->addr()->T::~T();
275 }
276 }
277 };
278
279 template <typename T>
280 struct MaybeStorage<T, true> : MaybeStorageBase<T> {
281 protected:
282 char mIsSome = false; // not bool -- guarantees minimal space consumption
283
284 constexpr MaybeStorage() = default;
285 constexpr explicit MaybeStorage(const T& aVal)
286 : MaybeStorageBase<T>{aVal}, mIsSome{true} {}
287 constexpr explicit MaybeStorage(T&& aVal)
288 : MaybeStorageBase<T>{std::move(aVal)}, mIsSome{true} {}
289
290 template <typename... Args>
291 constexpr explicit MaybeStorage(std::in_place_t, Args&&... aArgs)
292 : MaybeStorageBase<T>{std::in_place, std::forward<Args>(aArgs)...},
293 mIsSome{true} {}
294 };
295
296 template <typename T>
297 struct IsMaybeImpl : std::false_type {};
298
299 template <typename T>
300 struct IsMaybeImpl<Maybe<T>> : std::true_type {};
301
302 template <typename T>
303 using IsMaybe = IsMaybeImpl<std::decay_t<T>>;
304
305 } // namespace detail
306
307 template <typename T, typename U = typename std::remove_cv<
308 typename std::remove_reference<T>::type>::type>
309 constexpr Maybe<U> Some(T&& aValue);
310
311 /*
312 * Maybe is a container class which contains either zero or one elements. It
313 * serves two roles. It can represent values which are *semantically* optional,
314 * augmenting a type with an explicit 'Nothing' value. In this role, it provides
315 * methods that make it easy to work with values that may be missing, along with
316 * equality and comparison operators so that Maybe values can be stored in
317 * containers. Maybe values can be constructed conveniently in expressions using
318 * type inference, as follows:
319 *
320 * void doSomething(Maybe<Foo> aFoo) {
321 * if (aFoo) // Make sure that aFoo contains a value...
322 * aFoo->takeAction(); // and then use |aFoo->| to access it.
323 * } // |*aFoo| also works!
324 *
325 * doSomething(Nothing()); // Passes a Maybe<Foo> containing no value.
326 * doSomething(Some(Foo(100))); // Passes a Maybe<Foo> containing |Foo(100)|.
327 *
328 * You'll note that it's important to check whether a Maybe contains a value
329 * before using it, using conversion to bool, |isSome()|, or |isNothing()|. You
330 * can avoid these checks, and sometimes write more readable code, using
331 * |valueOr()|, |ptrOr()|, and |refOr()|, which allow you to retrieve the value
332 * in the Maybe and provide a default for the 'Nothing' case. You can also use
333 * |apply()| to call a function only if the Maybe holds a value, and |map()| to
334 * transform the value in the Maybe, returning another Maybe with a possibly
335 * different type.
336 *
337 * Maybe's other role is to support lazily constructing objects without using
338 * dynamic storage. A Maybe directly contains storage for a value, but it's
339 * empty by default. |emplace()|, as mentioned above, can be used to construct a
340 * value in Maybe's storage. The value a Maybe contains can be destroyed by
341 * calling |reset()|; this will happen automatically if a Maybe is destroyed
342 * while holding a value.
343 *
344 * It's a common idiom in C++ to use a pointer as a 'Maybe' type, with a null
345 * value meaning 'Nothing' and any other value meaning 'Some'. You can convert
346 * from such a pointer to a Maybe value using 'ToMaybe()'.
347 *
348 * Maybe is inspired by similar types in the standard library of many other
349 * languages (e.g. Haskell's Maybe and Rust's Option). In the C++ world it's
350 * very similar to std::optional, which was proposed for C++14 and originated in
351 * Boost. The most important differences between Maybe and std::optional are:
352 *
353 * - std::optional<T> may be compared with T. We deliberately forbid that.
354 * - std::optional has |valueOr()|, equivalent to Maybe's |valueOr()|, but
355 * lacks corresponding methods for |refOr()| and |ptrOr()|.
356 * - std::optional lacks |map()| and |apply()|, making it less suitable for
357 * functional-style code.
358 * - std::optional lacks many convenience functions that Maybe has. Most
359 * unfortunately, it lacks equivalents of the type-inferred constructor
360 * functions |Some()| and |Nothing()|.
361 */
362 template <class T>
363 class MOZ_INHERIT_TYPE_ANNOTATIONS_FROM_TEMPLATE_ARGS MOZ_GSL_OWNER Maybe
364 : private detail::MaybeStorage<T>,
365 public detail::Maybe_CopyMove_Enabler<T> {
366 template <typename, bool, bool, bool>
367 friend class detail::Maybe_CopyMove_Enabler;
368
369 template <typename U, typename V>
370 friend constexpr Maybe<V> Some(U&& aValue);
371
372 struct SomeGuard {};
373
374 template <typename U>
375 constexpr Maybe(U&& aValue, SomeGuard)
376 : detail::MaybeStorage<T>{std::forward<U>(aValue)} {}
377
378 using detail::MaybeStorage<T>::mIsSome;
379 using detail::MaybeStorage<T>::mStorage;
380
381 void poisonData() { detail::MaybePoisoner<T>::poison(&mStorage.val); }
382
383 public:
384 using ValueType = T;
385
386 MOZ_ALLOW_TEMPORARY constexpr Maybe() = default;
387
388 MOZ_ALLOW_TEMPORARY MOZ_IMPLICIT constexpr Maybe(Nothing) : Maybe{} {}
389
390 template <typename... Args>
391 constexpr explicit Maybe(std::in_place_t, Args&&... aArgs)
392 : detail::MaybeStorage<T>{std::in_place, std::forward<Args>(aArgs)...} {}
393
394 /**
395 * Maybe<T> can be copy-constructed from a Maybe<U> if T is constructible from
396 * a const U&.
397 */
398 template <typename U,
399 std::enable_if_t<std::is_constructible_v<T, const U&>, bool> = true>
400 MOZ_IMPLICIT Maybe(const Maybe<U>& aOther) {
401 if (aOther.isSome()) {
402 emplace(*aOther);
403 }
404 }
405
406 template <typename U, std::enable_if_t<!std::is_constructible_v<T, const U&>,
407 bool> = true>
408 explicit Maybe(const Maybe<U>& aOther) = delete;
409
410 /**
411 * Maybe<T> can be move-constructed from a Maybe<U> if T is constructible from
412 * a U&&.
413 */
414 template <typename U,
415 std::enable_if_t<std::is_constructible_v<T, U&&>, bool> = true>
416 MOZ_IMPLICIT Maybe(Maybe<U>&& aOther) {
417 if (aOther.isSome()) {
418 emplace(std::move(*aOther));
419 aOther.reset();
420 }
421 }
422 template <typename U,
423 std::enable_if_t<!std::is_constructible_v<T, U&&>, bool> = true>
424 explicit Maybe(Maybe<U>&& aOther) = delete;
425
426 template <typename U,
427 std::enable_if_t<std::is_constructible_v<T, const U&>, bool> = true>
428 Maybe& operator=(const Maybe<U>& aOther) {
429 if (aOther.isSome()) {
430 if (mIsSome) {
431 ref() = aOther.ref();
432 } else {
433 emplace(*aOther);
434 }
435 } else {
436 reset();
437 }
438 return *this;
439 }
440
441 template <typename U, std::enable_if_t<!std::is_constructible_v<T, const U&>,
442 bool> = true>
443 Maybe& operator=(const Maybe<U>& aOther) = delete;
444
445 template <typename U,
446 std::enable_if_t<std::is_constructible_v<T, U&&>, bool> = true>
447 Maybe& operator=(Maybe<U>&& aOther) {
448 if (aOther.isSome()) {
449 if (mIsSome) {
450 ref() = std::move(aOther.ref());
451 } else {
452 emplace(std::move(*aOther));
453 }
454 aOther.reset();
455 } else {
456 reset();
457 }
458
459 return *this;
460 }
461
462 template <typename U,
463 std::enable_if_t<!std::is_constructible_v<T, U&&>, bool> = true>
464 Maybe& operator=(Maybe<U>&& aOther) = delete;
465
466 constexpr Maybe& operator=(Nothing) {
467 reset();
468 return *this;
469 }
470
471 /* Methods that check whether this Maybe contains a value */
472 constexpr explicit operator bool() const { return isSome(); }
473 constexpr bool isSome() const { return mIsSome; }
474 constexpr bool isNothing() const { return !mIsSome; }
475
476 /* Returns the contents of this Maybe<T> by value. Unsafe unless |isSome()|.
477 */
478 constexpr T value() const&;
479 constexpr T value() &&;
480 constexpr T value() const&&;
481
482 /**
483 * Move the contents of this Maybe<T> out of internal storage and return it
484 * without calling the destructor. The internal storage is also reset to
485 * avoid multiple calls. Unsafe unless |isSome()|.
486 */
487 constexpr T extract() {
488 MOZ_RELEASE_ASSERT(isSome());
489 T v = std::move(mStorage.val);
490 reset();
491 return v;
492 }
493
494 /**
495 * Returns the value (possibly |Nothing()|) by moving it out of this Maybe<T>
496 * and leaving |Nothing()| in its place.
497 */
498 Maybe<T> take() { return std::exchange(*this, Nothing()); }
499
500 /*
501 * Returns the contents of this Maybe<T> by value. If |isNothing()|, returns
502 * the default value provided.
503 *
504 * Note: If the value passed to aDefault is not the result of a trivial
505 * expression, but expensive to evaluate, e.g. |valueOr(ExpensiveFunction())|,
506 * use |valueOrFrom| instead, e.g.
507 * |valueOrFrom([arg] { return ExpensiveFunction(arg); })|. This ensures
508 * that the expensive expression is only evaluated when its result will
509 * actually be used.
510 */
511 template <typename V>
512 constexpr T valueOr(V&& aDefault) const {
513 if (isSome()) {
514 return ref();
515 }
516 return std::forward<V>(aDefault);
517 }
518
519 /*
520 * Returns the contents of this Maybe<T> by value. If |isNothing()|, returns
521 * the value returned from the function or functor provided.
522 */
523 template <typename F>
524 constexpr T valueOrFrom(F&& aFunc) const {
525 if (isSome()) {
526 return ref();
527 }
528 return aFunc();
529 }
530
531 /* Returns the contents of this Maybe<T> by pointer. Unsafe unless |isSome()|.
532 */
533 T* ptr();
534 constexpr const T* ptr() const;
535
536 /*
537 * Returns the contents of this Maybe<T> by pointer. If |isNothing()|,
538 * returns the default value provided.
539 */
540 T* ptrOr(T* aDefault) {
541 if (isSome()) {
542 return ptr();
543 }
544 return aDefault;
545 }
546
547 constexpr const T* ptrOr(const T* aDefault) const {
548 if (isSome()) {
549 return ptr();
550 }
551 return aDefault;
552 }
553
554 /*
555 * Returns the contents of this Maybe<T> by pointer. If |isNothing()|,
556 * returns the value returned from the function or functor provided.
557 */
558 template <typename F>
559 T* ptrOrFrom(F&& aFunc) {
560 if (isSome()) {
561 return ptr();
562 }
563 return aFunc();
564 }
565
566 template <typename F>
567 const T* ptrOrFrom(F&& aFunc) const {
568 if (isSome()) {
569 return ptr();
570 }
571 return aFunc();
572 }
573
574 constexpr T* operator->();
575 constexpr const T* operator->() const;
576
577 /* Returns the contents of this Maybe<T> by ref. Unsafe unless |isSome()|. */
578 constexpr T& ref() & MOZ_LIFETIME_BOUND;
579 constexpr const T& ref() const& MOZ_LIFETIME_BOUND;
580 constexpr T&& ref() && MOZ_LIFETIME_BOUND;
581 constexpr const T&& ref() const&& MOZ_LIFETIME_BOUND;
582
583 /*
584 * Returns the contents of this Maybe<T> by ref. If |isNothing()|, returns
585 * the default value provided.
586 */
587 constexpr T& refOr(T& aDefault MOZ_LIFETIME_BOUND) MOZ_LIFETIME_BOUND {
588 if (isSome()) {
589 return ref();
590 }
591 return aDefault;
592 }
593
594 constexpr const T& refOr(const T& aDefault MOZ_LIFETIME_BOUND) const
595 MOZ_LIFETIME_BOUND {
596 if (isSome()) {
597 return ref();
598 }
599 return aDefault;
600 }
601
602 /*
603 * Returns the contents of this Maybe<T> by ref. If |isNothing()|, returns the
604 * value returned from the function or functor provided.
605 */
606 template <typename F>
607 constexpr T& refOrFrom(F&& aFunc) {
608 if (isSome()) {
609 return ref();
610 }
611 return aFunc();
612 }
613
614 template <typename F>
615 constexpr const T& refOrFrom(F&& aFunc) const {
616 if (isSome()) {
617 return ref();
618 }
619 return aFunc();
620 }
621
622 constexpr T& operator*() & MOZ_LIFETIME_BOUND;
623 constexpr const T& operator*() const& MOZ_LIFETIME_BOUND;
624 constexpr T&& operator*() && MOZ_LIFETIME_BOUND;
625 constexpr const T&& operator*() const&& MOZ_LIFETIME_BOUND;
626
627 /* If |isSome()|, runs the provided function or functor on the contents of
628 * this Maybe. */
629 template <typename Func>
630 constexpr Maybe& apply(Func&& aFunc) & {
631 if (isSome()) {
632 std::forward<Func>(aFunc)(ref());
633 }
634 return *this;
635 }
636
637 template <typename Func>
638 constexpr const Maybe& apply(Func&& aFunc) const& {
639 if (isSome()) {
640 std::forward<Func>(aFunc)(ref());
641 }
642 return *this;
643 }
644
645 template <typename Func>
646 constexpr Maybe& apply(Func&& aFunc) && {
647 if (isSome()) {
648 std::forward<Func>(aFunc)(extract());
649 }
650 return *this;
651 }
652
653 template <typename Func>
654 constexpr Maybe& apply(Func&& aFunc) const&& {
655 if (isSome()) {
656 std::forward<Func>(aFunc)(extract());
657 }
658 return *this;
659 }
660
661 /*
662 * If |isSome()|, runs the provided function and returns the result wrapped
663 * in a Maybe. If |isNothing()|, returns an empty Maybe value with the same
664 * value type as what the provided function would have returned.
665 */
666 template <typename Func>
667 constexpr auto map(Func&& aFunc) & {
668 if (isSome()) {
669 return Some(std::forward<Func>(aFunc)(ref()));
670 }
671 return Maybe<decltype(std::forward<Func>(aFunc)(ref()))>{};
672 }
673
674 template <typename Func>
675 constexpr auto map(Func&& aFunc) const& {
676 if (isSome()) {
677 return Some(std::forward<Func>(aFunc)(ref()));
678 }
679 return Maybe<decltype(std::forward<Func>(aFunc)(ref()))>{};
680 }
681
682 template <typename Func>
683 constexpr auto map(Func&& aFunc) && {
684 if (isSome()) {
685 return Some(std::forward<Func>(aFunc)(extract()));
686 }
687 return Maybe<decltype(std::forward<Func>(aFunc)(extract()))>{};
688 }
689
690 template <typename Func>
691 constexpr auto map(Func&& aFunc) const&& {
692 if (isSome()) {
693 return Some(std::forward<Func>(aFunc)(extract()));
694 }
695 return Maybe<decltype(std::forward<Func>(aFunc)(extract()))>{};
696 }
697
698 /*
699 * If |isSome()|, runs the provided function or functor on the contents of
700 * this Maybe and returns the result. Note that the provided function or
701 * functor must return a Maybe<U> of any type U.
702 * If |isNothing()|, returns an empty Maybe value with the same type as what
703 * the provided function would have returned.
704 */
705 template <typename Func>
706 constexpr auto andThen(Func&& aFunc) & {
707 static_assert(std::is_invocable_v<Func, T&>);
708 using U = std::invoke_result_t<Func, T&>;
709 static_assert(detail::IsMaybe<U>::value);
710 if (isSome()) {
711 return std::invoke(std::forward<Func>(aFunc), ref());
712 }
713 return std::remove_cv_t<std::remove_reference_t<U>>{};
714 }
715
716 template <typename Func>
717 constexpr auto andThen(Func&& aFunc) const& {
718 static_assert(std::is_invocable_v<Func, const T&>);
719 using U = std::invoke_result_t<Func, const T&>;
720 static_assert(detail::IsMaybe<U>::value);
721 if (isSome()) {
722 return std::invoke(std::forward<Func>(aFunc), ref());
723 }
724 return std::remove_cv_t<std::remove_reference_t<U>>{};
725 }
726
727 template <typename Func>
728 constexpr auto andThen(Func&& aFunc) && {
729 static_assert(std::is_invocable_v<Func, T&&>);
730 using U = std::invoke_result_t<Func, T&&>;
731 static_assert(detail::IsMaybe<U>::value);
732 if (isSome()) {
733 return std::invoke(std::forward<Func>(aFunc), extract());
734 }
735 return std::remove_cv_t<std::remove_reference_t<U>>{};
736 }
737
738 template <typename Func>
739 constexpr auto andThen(Func&& aFunc) const&& {
740 static_assert(std::is_invocable_v<Func, const T&&>);
741 using U = std::invoke_result_t<Func, const T&&>;
742 static_assert(detail::IsMaybe<U>::value);
743 if (isSome()) {
744 return std::invoke(std::forward<Func>(aFunc), extract());
745 }
746 return std::remove_cv_t<std::remove_reference_t<U>>{};
747 }
748
749 /*
750 * If |isNothing()|, runs the provided function or functor and returns its
751 * result. If |isSome()|, returns the contained value wrapped in a Maybe.
752 */
753 template <typename Func>
754 constexpr Maybe orElse(Func&& aFunc) & {
755 static_assert(std::is_invocable_v<Func>);
756 using U = std::invoke_result_t<Func>;
757 static_assert(
758 std::is_same_v<Maybe, std::remove_cv_t<std::remove_reference_t<U>>>);
759 if (isSome()) {
760 return *this;
761 }
762 return std::invoke(std::forward<Func>(aFunc));
763 }
764
765 template <typename Func>
766 constexpr Maybe orElse(Func&& aFunc) const& {
767 static_assert(std::is_invocable_v<Func>);
768 using U = std::invoke_result_t<Func>;
769 static_assert(
770 std::is_same_v<Maybe, std::remove_cv_t<std::remove_reference_t<U>>>);
771 if (isSome()) {
772 return *this;
773 }
774 return std::invoke(std::forward<Func>(aFunc));
775 }
776
777 template <typename Func>
778 constexpr Maybe orElse(Func&& aFunc) && {
779 static_assert(std::is_invocable_v<Func>);
780 using U = std::invoke_result_t<Func>;
781 static_assert(
782 std::is_same_v<Maybe, std::remove_cv_t<std::remove_reference_t<U>>>);
783 if (isSome()) {
784 return std::move(*this);
785 }
786 return std::invoke(std::forward<Func>(aFunc));
787 }
788
789 template <typename Func>
790 constexpr Maybe orElse(Func&& aFunc) const&& {
791 static_assert(std::is_invocable_v<Func>);
792 using U = std::invoke_result_t<Func>;
793 static_assert(
794 std::is_same_v<Maybe, std::remove_cv_t<std::remove_reference_t<U>>>);
795 if (isSome()) {
796 return std::move(*this);
797 }
798 return std::invoke(std::forward<Func>(aFunc));
799 }
800
801 /* If |isSome()|, empties this Maybe and destroys its contents. */
802 constexpr void reset() {
803 if (isSome()) {
804 if constexpr (!std::is_trivially_destructible_v<T>) {
805 /*
806 * Static analyzer gets confused if we have Maybe<MutexAutoLock>,
807 * so we suppress thread-safety warnings here
808 */
809 MOZ_PUSH_IGNORE_THREAD_SAFETY
810 ref().T::~T();
811 MOZ_POP_THREAD_SAFETY
812 poisonData();
813 }
814 mIsSome = false;
815 }
816 }
817
818 /*
819 * Constructs a T value in-place in this empty Maybe<T>'s storage. The
820 * arguments to |emplace()| are the parameters to T's constructor.
821 */
822 template <typename... Args>
823 constexpr void emplace(Args&&... aArgs);
824
825 template <typename U>
826 constexpr std::enable_if_t<std::is_same_v<T, U> &&
827 std::is_copy_constructible_v<U> &&
828 !std::is_move_constructible_v<U>>
829 emplace(U&& aArgs) {
830 emplace(aArgs);
831 }
832
833 friend std::ostream& operator<<(std::ostream& aStream,
834 const Maybe<T>& aMaybe) {
835 if (aMaybe) {
836 aStream << aMaybe.ref();
837 } else {
838 aStream << "<Nothing>";
839 }
840 return aStream;
841 }
842 };
843
844 template <typename T>
845 class Maybe<T&> {
846 public:
847 constexpr Maybe() = default;
848 constexpr MOZ_IMPLICIT Maybe(Nothing) {}
849
850 void emplace(T& aRef) { mValue = &aRef; }
851
852 /* Methods that check whether this Maybe contains a value */
853 constexpr explicit operator bool() const { return isSome(); }
854 constexpr bool isSome() const { return mValue; }
855 constexpr bool isNothing() const { return !mValue; }
856
857 T& ref() const {
858 MOZ_RELEASE_ASSERT(isSome());
859 return *mValue;
860 }
861
862 T* operator->() const { return &ref(); }
863 T& operator*() const { return ref(); }
864
865 // Deliberately not defining value and ptr accessors, as these may be
866 // confusing on a reference-typed Maybe.
867
868 // XXX Should we define refOr?
869
870 void reset() { mValue = nullptr; }
871
872 template <typename Func>
873 const Maybe& apply(Func&& aFunc) const {
874 if (isSome()) {
875 std::forward<Func>(aFunc)(ref());
876 }
877 return *this;
878 }
879
880 template <typename Func>
881 auto map(Func&& aFunc) const {
882 Maybe<decltype(std::forward<Func>(aFunc)(ref()))> val;
883 if (isSome()) {
884 val.emplace(std::forward<Func>(aFunc)(ref()));
885 }
886 return val;
887 }
888
889 template <typename Func>
890 constexpr auto andThen(Func&& aFunc) const {
891 static_assert(std::is_invocable_v<Func, T&>);
892 using U = std::invoke_result_t<Func, T&>;
893 static_assert(detail::IsMaybe<U>::value);
894 if (isSome()) {
895 return std::invoke(std::forward<Func>(aFunc), ref());
896 }
897 return std::remove_cv_t<std::remove_reference_t<U>>{};
898 }
899
900 template <typename Func>
901 constexpr Maybe orElse(Func&& aFunc) const {
902 static_assert(std::is_invocable_v<Func>);
903 using U = std::invoke_result_t<Func>;
904 static_assert(
905 std::is_same_v<Maybe, std::remove_cv_t<std::remove_reference_t<U>>>);
906 if (isSome()) {
907 return *this;
908 }
909 return std::invoke(std::forward<Func>(aFunc));
910 }
911
912 bool refEquals(const Maybe<T&>& aOther) const {
913 return mValue == aOther.mValue;
914 }
915
916 bool refEquals(const T& aOther) const { return mValue == &aOther; }
917
918 private:
919 T* mValue = nullptr;
920 };
921
922 template <typename T>
923 constexpr T Maybe<T>::value() const& {
924 MOZ_RELEASE_ASSERT(isSome());
925 return ref();
926 }
927
928 template <typename T>
929 constexpr T Maybe<T>::value() && {
930 MOZ_RELEASE_ASSERT(isSome());
931 return std::move(ref());
932 }
933
934 template <typename T>
935 constexpr T Maybe<T>::value() const&& {
936 MOZ_RELEASE_ASSERT(isSome());
937 return std::move(ref());
938 }
939
940 template <typename T>
941 T* Maybe<T>::ptr() {
942 MOZ_RELEASE_ASSERT(isSome());
943 return &ref();
944 }
945
946 template <typename T>
947 constexpr const T* Maybe<T>::ptr() const {
948 MOZ_RELEASE_ASSERT(isSome());
949 return &ref();
950 }
951
952 template <typename T>
953 constexpr T* Maybe<T>::operator->() {
954 MOZ_RELEASE_ASSERT(isSome());
955 return ptr();
956 }
957
958 template <typename T>
959 constexpr const T* Maybe<T>::operator->() const {
960 MOZ_RELEASE_ASSERT(isSome());
961 return ptr();
962 }
963
964 template <typename T>
965 constexpr T& Maybe<T>::ref() & {
966 MOZ_RELEASE_ASSERT(isSome());
967 return mStorage.val;
968 }
969
970 template <typename T>
971 constexpr const T& Maybe<T>::ref() const& {
972 MOZ_RELEASE_ASSERT(isSome());
973 return mStorage.val;
974 }
975
976 template <typename T>
977 constexpr T&& Maybe<T>::ref() && {
978 MOZ_RELEASE_ASSERT(isSome());
979 return std::move(mStorage.val);
980 }
981
982 template <typename T>
983 constexpr const T&& Maybe<T>::ref() const&& {
984 MOZ_RELEASE_ASSERT(isSome());
985 return std::move(mStorage.val);
986 }
987
988 template <typename T>
989 constexpr T& Maybe<T>::operator*() & {
990 MOZ_RELEASE_ASSERT(isSome());
991 return ref();
992 }
993
994 template <typename T>
995 constexpr const T& Maybe<T>::operator*() const& {
996 MOZ_RELEASE_ASSERT(isSome());
997 return ref();
998 }
999
1000 template <typename T>
1001 constexpr T&& Maybe<T>::operator*() && {
1002 MOZ_RELEASE_ASSERT(isSome());
1003 return std::move(ref());
1004 }
1005
1006 template <typename T>
1007 constexpr const T&& Maybe<T>::operator*() const&& {
1008 MOZ_RELEASE_ASSERT(isSome());
1009 return std::move(ref());
1010 }
1011
1012 template <typename T>
1013 template <typename... Args>
1014 constexpr void Maybe<T>::emplace(Args&&... aArgs) {
1015 MOZ_RELEASE_ASSERT(!isSome());
1016 ::new (KnownNotNull, &mStorage.val) T(std::forward<Args>(aArgs)...);
1017 mIsSome = true;
1018 }
1019
1020 /*
1021 * Some() creates a Maybe<T> value containing the provided T value. If T has a
1022 * move constructor, it's used to make this as efficient as possible.
1023 *
1024 * Some() selects the type of Maybe it returns by removing any const, volatile,
1025 * or reference qualifiers from the type of the value you pass to it. This gives
1026 * it more intuitive behavior when used in expressions, but it also means that
1027 * if you need to construct a Maybe value that holds a const, volatile, or
1028 * reference value, you need to use emplace() instead.
1029 */
1030 template <typename T, typename U>
1031 constexpr Maybe<U> Some(T&& aValue) {
1032 return {std::forward<T>(aValue), typename Maybe<U>::SomeGuard{}};
1033 }
1034
1035 template <typename T>
1036 constexpr Maybe<T&> SomeRef(T& aValue) {
1037 Maybe<T&> value;
1038 value.emplace(aValue);
1039 return value;
1040 }
1041
1042 template <typename T>
1043 constexpr Maybe<T&> ToMaybeRef(T* const aPtr) {
1044 return aPtr ? SomeRef(*aPtr) : Nothing{};
1045 }
1046
1047 template <typename T>
1048 Maybe<std::remove_cv_t<std::remove_reference_t<T>>> ToMaybe(T* aPtr) {
1049 if (aPtr) {
1050 return Some(*aPtr);
1051 }
1052 return Nothing();
1053 }
1054
1055 /*
1056 * Two Maybe<T> values are equal if
1057 * - both are Nothing, or
1058 * - both are Some, and the values they contain are equal.
1059 */
1060 template <typename T>
1061 constexpr bool operator==(const Maybe<T>& aLHS, const Maybe<T>& aRHS) {
1062 static_assert(!std::is_reference_v<T>,
1063 "operator== is not defined for Maybe<T&>, compare values or "
1064 "addresses explicitly instead");
1065 if (aLHS.isNothing() != aRHS.isNothing()) {
1066 return false;
1067 }
1068 return aLHS.isNothing() || *aLHS == *aRHS;
1069 }
1070
1071 template <typename T>
1072 constexpr bool operator!=(const Maybe<T>& aLHS, const Maybe<T>& aRHS) {
1073 return !(aLHS == aRHS);
1074 }
1075
1076 /*
1077 * We support comparison to Nothing to allow reasonable expressions like:
1078 * if (maybeValue == Nothing()) { ... }
1079 */
1080 template <typename T>
1081 constexpr bool operator==(const Maybe<T>& aLHS, const Nothing& aRHS) {
1082 return aLHS.isNothing();
1083 }
1084
1085 template <typename T>
1086 constexpr bool operator!=(const Maybe<T>& aLHS, const Nothing& aRHS) {
1087 return !(aLHS == aRHS);
1088 }
1089
1090 template <typename T>
1091 constexpr bool operator==(const Nothing& aLHS, const Maybe<T>& aRHS) {
1092 return aRHS.isNothing();
1093 }
1094
1095 template <typename T>
1096 constexpr bool operator!=(const Nothing& aLHS, const Maybe<T>& aRHS) {
1097 return !(aLHS == aRHS);
1098 }
1099
1100 /*
1101 * Maybe<T> values are ordered in the same way T values are ordered, except that
1102 * Nothing comes before anything else.
1103 */
1104 template <typename T>
1105 constexpr bool operator<(const Maybe<T>& aLHS, const Maybe<T>& aRHS) {
1106 if (aLHS.isNothing()) {
1107 return aRHS.isSome();
1108 }
1109 if (aRHS.isNothing()) {
1110 return false;
1111 }
1112 return *aLHS < *aRHS;
1113 }
1114
1115 template <typename T>
1116 constexpr bool operator>(const Maybe<T>& aLHS, const Maybe<T>& aRHS) {
1117 return !(aLHS < aRHS || aLHS == aRHS);
1118 }
1119
1120 template <typename T>
1121 constexpr bool operator<=(const Maybe<T>& aLHS, const Maybe<T>& aRHS) {
1122 return aLHS < aRHS || aLHS == aRHS;
1123 }
1124
1125 template <typename T>
1126 constexpr bool operator>=(const Maybe<T>& aLHS, const Maybe<T>& aRHS) {
1127 return !(aLHS < aRHS);
1128 }
1129
1130 template <typename T>
1131 inline void ImplCycleCollectionTraverse(
1132 nsCycleCollectionTraversalCallback& aCallback, mozilla::Maybe<T>& aField,
1133 const char* aName, uint32_t aFlags = 0) {
1134 if (aField) {
1135 ImplCycleCollectionTraverse(aCallback, aField.ref(), aName, aFlags);
1136 }
1137 }
1138
1139 template <typename T>
1140 inline void ImplCycleCollectionUnlink(mozilla::Maybe<T>& aField) {
1141 if (aField) {
1142 ImplCycleCollectionUnlink(aField.ref());
1143 }
1144 }
1145
1146 } // namespace mozilla
1147
1148 #endif /* mozilla_Maybe_h */