Source code

Revision control

Other Tools

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/. */
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 "mozilla/Alignment.h"
13
#include "mozilla/Assertions.h"
14
#include "mozilla/Attributes.h"
15
#include "mozilla/MemoryChecking.h"
16
#include "mozilla/Move.h"
17
#include "mozilla/OperatorNewExtensions.h"
18
#include "mozilla/Poison.h"
19
#include "mozilla/TypeTraits.h"
20
21
#include <new> // for placement new
22
#include <ostream>
23
#include <type_traits>
24
25
class nsCycleCollectionTraversalCallback;
26
27
template <typename T>
28
inline void CycleCollectionNoteChild(
29
nsCycleCollectionTraversalCallback& aCallback, T* aChild, const char* aName,
30
uint32_t aFlags);
31
32
namespace mozilla {
33
34
struct Nothing {};
35
36
namespace detail {
37
38
// You would think that poisoning Maybe instances could just be a call
39
// to mozWritePoison. Unfortunately, using a simple call to
40
// mozWritePoison generates poor code on MSVC for small structures. The
41
// generated code contains (always not-taken) branches and does a bunch
42
// of setup for `rep stos{l,q}`, even though we know at compile time
43
// exactly how many words we're poisoning. Instead, we're going to
44
// force MSVC to generate the code we want via recursive templates.
45
46
// Write the given poisonValue into p at offset*sizeof(uintptr_t).
47
template <size_t offset>
48
inline void WritePoisonAtOffset(void* p, const uintptr_t poisonValue) {
49
memcpy(static_cast<char*>(p) + offset * sizeof(poisonValue), &poisonValue,
50
sizeof(poisonValue));
51
}
52
53
template <size_t Offset, size_t NOffsets>
54
struct InlinePoisoner {
55
static void poison(void* p, const uintptr_t poisonValue) {
56
WritePoisonAtOffset<Offset>(p, poisonValue);
57
InlinePoisoner<Offset + 1, NOffsets>::poison(p, poisonValue);
58
}
59
};
60
61
template <size_t N>
62
struct InlinePoisoner<N, N> {
63
static void poison(void*, const uintptr_t) {
64
// All done!
65
}
66
};
67
68
// We can't generate inline code for large structures, though, because we'll
69
// blow out recursive template instantiation limits, and the code would be
70
// bloated to boot. So provide a fallback to the out-of-line poisoner.
71
template <size_t ObjectSize>
72
struct OutOfLinePoisoner {
73
static void poison(void* p, const uintptr_t) {
74
mozWritePoison(p, ObjectSize);
75
}
76
};
77
78
template <typename T>
79
inline void PoisonObject(T* p) {
80
const uintptr_t POISON = mozPoisonValue();
81
Conditional<(sizeof(T) <= 8 * sizeof(POISON)),
82
InlinePoisoner<0, sizeof(T) / sizeof(POISON)>,
83
OutOfLinePoisoner<sizeof(T)>>::Type::poison(p, POISON);
84
}
85
86
template <typename T>
87
struct MaybePoisoner {
88
static const size_t N = sizeof(T);
89
90
static void poison(void* aPtr) {
91
#ifdef MOZ_DIAGNOSTIC_ASSERT_ENABLED
92
if (N >= sizeof(uintptr_t)) {
93
PoisonObject(static_cast<typename RemoveCV<T>::Type*>(aPtr));
94
}
95
#endif
96
MOZ_MAKE_MEM_UNDEFINED(aPtr, N);
97
}
98
};
99
100
} // namespace detail
101
102
/*
103
* Maybe is a container class which contains either zero or one elements. It
104
* serves two roles. It can represent values which are *semantically* optional,
105
* augmenting a type with an explicit 'Nothing' value. In this role, it provides
106
* methods that make it easy to work with values that may be missing, along with
107
* equality and comparison operators so that Maybe values can be stored in
108
* containers. Maybe values can be constructed conveniently in expressions using
109
* type inference, as follows:
110
*
111
* void doSomething(Maybe<Foo> aFoo) {
112
* if (aFoo) // Make sure that aFoo contains a value...
113
* aFoo->takeAction(); // and then use |aFoo->| to access it.
114
* } // |*aFoo| also works!
115
*
116
* doSomething(Nothing()); // Passes a Maybe<Foo> containing no value.
117
* doSomething(Some(Foo(100))); // Passes a Maybe<Foo> containing |Foo(100)|.
118
*
119
* You'll note that it's important to check whether a Maybe contains a value
120
* before using it, using conversion to bool, |isSome()|, or |isNothing()|. You
121
* can avoid these checks, and sometimes write more readable code, using
122
* |valueOr()|, |ptrOr()|, and |refOr()|, which allow you to retrieve the value
123
* in the Maybe and provide a default for the 'Nothing' case. You can also use
124
* |apply()| to call a function only if the Maybe holds a value, and |map()| to
125
* transform the value in the Maybe, returning another Maybe with a possibly
126
* different type.
127
*
128
* Maybe's other role is to support lazily constructing objects without using
129
* dynamic storage. A Maybe directly contains storage for a value, but it's
130
* empty by default. |emplace()|, as mentioned above, can be used to construct a
131
* value in Maybe's storage. The value a Maybe contains can be destroyed by
132
* calling |reset()|; this will happen automatically if a Maybe is destroyed
133
* while holding a value.
134
*
135
* It's a common idiom in C++ to use a pointer as a 'Maybe' type, with a null
136
* value meaning 'Nothing' and any other value meaning 'Some'. You can convert
137
* from such a pointer to a Maybe value using 'ToMaybe()'.
138
*
139
* Maybe is inspired by similar types in the standard library of many other
140
* languages (e.g. Haskell's Maybe and Rust's Option). In the C++ world it's
141
* very similar to std::optional, which was proposed for C++14 and originated in
142
* Boost. The most important differences between Maybe and std::optional are:
143
*
144
* - std::optional<T> may be compared with T. We deliberately forbid that.
145
* - std::optional allows in-place construction without a separate call to
146
* |emplace()| by using a dummy |in_place_t| value to tag the appropriate
147
* constructor.
148
* - std::optional has |valueOr()|, equivalent to Maybe's |valueOr()|, but
149
* lacks corresponding methods for |refOr()| and |ptrOr()|.
150
* - std::optional lacks |map()| and |apply()|, making it less suitable for
151
* functional-style code.
152
* - std::optional lacks many convenience functions that Maybe has. Most
153
* unfortunately, it lacks equivalents of the type-inferred constructor
154
* functions |Some()| and |Nothing()|.
155
*/
156
template <class T>
157
class MOZ_NON_PARAM MOZ_INHERIT_TYPE_ANNOTATIONS_FROM_TEMPLATE_ARGS Maybe {
158
MOZ_ALIGNAS_IN_STRUCT(T) unsigned char mStorage[sizeof(T)];
159
char mIsSome; // not bool -- guarantees minimal space consumption
160
161
// GCC fails due to -Werror=strict-aliasing if |mStorage| is directly cast to
162
// T*. Indirecting through these functions addresses the problem.
163
void* data() { return mStorage; }
164
const void* data() const { return mStorage; }
165
166
void poisonData() { detail::MaybePoisoner<T>::poison(data()); }
167
168
public:
169
using ValueType = T;
170
171
MOZ_ALLOW_TEMPORARY Maybe() : mIsSome(false) {}
172
~Maybe() { reset(); }
173
174
MOZ_ALLOW_TEMPORARY MOZ_IMPLICIT Maybe(Nothing) : mIsSome(false) {}
175
176
Maybe(const Maybe& aOther) : mIsSome(false) {
177
if (aOther.mIsSome) {
178
emplace(*aOther);
179
}
180
}
181
182
/**
183
* Maybe<T> can be copy-constructed from a Maybe<U> if U is convertible to T.
184
*/
185
template <typename U, typename = typename std::enable_if<
186
std::is_convertible<U, T>::value>::type>
187
MOZ_IMPLICIT Maybe(const Maybe<U>& aOther) : mIsSome(false) {
188
if (aOther.isSome()) {
189
emplace(*aOther);
190
}
191
}
192
193
Maybe(Maybe&& aOther) : mIsSome(false) {
194
if (aOther.mIsSome) {
195
emplace(std::move(*aOther));
196
aOther.reset();
197
}
198
}
199
200
/**
201
* Maybe<T> can be move-constructed from a Maybe<U> if U is convertible to T.
202
*/
203
template <typename U, typename = typename std::enable_if<
204
std::is_convertible<U, T>::value>::type>
205
MOZ_IMPLICIT Maybe(Maybe<U>&& aOther) : mIsSome(false) {
206
if (aOther.isSome()) {
207
emplace(std::move(*aOther));
208
aOther.reset();
209
}
210
}
211
212
Maybe& operator=(const Maybe& aOther) {
213
if (&aOther != this) {
214
if (aOther.mIsSome) {
215
if (mIsSome) {
216
ref() = aOther.ref();
217
} else {
218
emplace(*aOther);
219
}
220
} else {
221
reset();
222
}
223
}
224
return *this;
225
}
226
227
template <typename U, typename = typename std::enable_if<
228
std::is_convertible<U, T>::value>::type>
229
Maybe& operator=(const Maybe<U>& aOther) {
230
if (aOther.isSome()) {
231
if (mIsSome) {
232
ref() = aOther.ref();
233
} else {
234
emplace(*aOther);
235
}
236
} else {
237
reset();
238
}
239
return *this;
240
}
241
242
Maybe& operator=(Maybe&& aOther) {
243
MOZ_ASSERT(this != &aOther, "Self-moves are prohibited");
244
245
if (aOther.mIsSome) {
246
if (mIsSome) {
247
ref() = std::move(aOther.ref());
248
} else {
249
emplace(std::move(*aOther));
250
}
251
aOther.reset();
252
} else {
253
reset();
254
}
255
256
return *this;
257
}
258
259
template <typename U, typename = typename std::enable_if<
260
std::is_convertible<U, T>::value>::type>
261
Maybe&