cannam@147
|
1 // Copyright (c) 2013-2014 Sandstorm Development Group, Inc. and contributors
|
cannam@147
|
2 // Licensed under the MIT License:
|
cannam@147
|
3 //
|
cannam@147
|
4 // Permission is hereby granted, free of charge, to any person obtaining a copy
|
cannam@147
|
5 // of this software and associated documentation files (the "Software"), to deal
|
cannam@147
|
6 // in the Software without restriction, including without limitation the rights
|
cannam@147
|
7 // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
cannam@147
|
8 // copies of the Software, and to permit persons to whom the Software is
|
cannam@147
|
9 // furnished to do so, subject to the following conditions:
|
cannam@147
|
10 //
|
cannam@147
|
11 // The above copyright notice and this permission notice shall be included in
|
cannam@147
|
12 // all copies or substantial portions of the Software.
|
cannam@147
|
13 //
|
cannam@147
|
14 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
cannam@147
|
15 // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
cannam@147
|
16 // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
cannam@147
|
17 // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
cannam@147
|
18 // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
cannam@147
|
19 // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
cannam@147
|
20 // THE SOFTWARE.
|
cannam@147
|
21
|
cannam@147
|
22 // Header that should be #included by everyone.
|
cannam@147
|
23 //
|
cannam@147
|
24 // This defines very simple utilities that are widely applicable.
|
cannam@147
|
25
|
cannam@147
|
26 #ifndef KJ_COMMON_H_
|
cannam@147
|
27 #define KJ_COMMON_H_
|
cannam@147
|
28
|
cannam@147
|
29 #if defined(__GNUC__) && !KJ_HEADER_WARNINGS
|
cannam@147
|
30 #pragma GCC system_header
|
cannam@147
|
31 #endif
|
cannam@147
|
32
|
cannam@147
|
33 #ifndef KJ_NO_COMPILER_CHECK
|
cannam@147
|
34 #if __cplusplus < 201103L && !__CDT_PARSER__ && !_MSC_VER
|
cannam@147
|
35 #error "This code requires C++11. Either your compiler does not support it or it is not enabled."
|
cannam@147
|
36 #ifdef __GNUC__
|
cannam@147
|
37 // Compiler claims compatibility with GCC, so presumably supports -std.
|
cannam@147
|
38 #error "Pass -std=c++11 on the compiler command line to enable C++11."
|
cannam@147
|
39 #endif
|
cannam@147
|
40 #endif
|
cannam@147
|
41
|
cannam@147
|
42 #ifdef __GNUC__
|
cannam@147
|
43 #if __clang__
|
cannam@147
|
44 #if __clang_major__ < 3 || (__clang_major__ == 3 && __clang_minor__ < 2)
|
cannam@147
|
45 #warning "This library requires at least Clang 3.2."
|
cannam@147
|
46 #elif defined(__apple_build_version__) && __apple_build_version__ <= 4250028
|
cannam@147
|
47 #warning "This library requires at least Clang 3.2. XCode 4.6's Clang, which claims to be "\
|
cannam@147
|
48 "version 4.2 (wat?), is actually built from some random SVN revision between 3.1 "\
|
cannam@147
|
49 "and 3.2. Unfortunately, it is insufficient for compiling this library. You can "\
|
cannam@147
|
50 "download the real Clang 3.2 (or newer) from the Clang web site. Step-by-step "\
|
cannam@147
|
51 "instructions can be found in Cap'n Proto's documentation: "\
|
cannam@147
|
52 "http://kentonv.github.io/capnproto/install.html#clang_32_on_mac_osx"
|
cannam@147
|
53 #elif __cplusplus >= 201103L && !__has_include(<initializer_list>)
|
cannam@147
|
54 #warning "Your compiler supports C++11 but your C++ standard library does not. If your "\
|
cannam@147
|
55 "system has libc++ installed (as should be the case on e.g. Mac OSX), try adding "\
|
cannam@147
|
56 "-stdlib=libc++ to your CXXFLAGS."
|
cannam@147
|
57 #endif
|
cannam@147
|
58 #else
|
cannam@147
|
59 #if __GNUC__ < 4 || (__GNUC__ == 4 && __GNUC_MINOR__ < 7)
|
cannam@147
|
60 #warning "This library requires at least GCC 4.7."
|
cannam@147
|
61 #endif
|
cannam@147
|
62 #endif
|
cannam@147
|
63 #elif defined(_MSC_VER)
|
cannam@147
|
64 #if _MSC_VER < 1900
|
cannam@147
|
65 #error "You need Visual Studio 2015 or better to compile this code."
|
cannam@147
|
66 #endif
|
cannam@147
|
67 #else
|
cannam@147
|
68 #warning "I don't recognize your compiler. As of this writing, Clang and GCC are the only "\
|
cannam@147
|
69 "known compilers with enough C++11 support for this library. "\
|
cannam@147
|
70 "#define KJ_NO_COMPILER_CHECK to make this warning go away."
|
cannam@147
|
71 #endif
|
cannam@147
|
72 #endif
|
cannam@147
|
73
|
cannam@147
|
74 #include <stddef.h>
|
cannam@147
|
75 #include <initializer_list>
|
cannam@147
|
76
|
cannam@147
|
77 #if __linux__ && __cplusplus > 201200L
|
cannam@147
|
78 // Hack around stdlib bug with C++14 that exists on some Linux systems.
|
cannam@147
|
79 // Apparently in this mode the C library decides not to define gets() but the C++ library still
|
cannam@147
|
80 // tries to import it into the std namespace. This bug has been fixed at the source but is still
|
cannam@147
|
81 // widely present in the wild e.g. on Ubuntu 14.04.
|
cannam@147
|
82 #undef _GLIBCXX_HAVE_GETS
|
cannam@147
|
83 #endif
|
cannam@147
|
84
|
cannam@147
|
85 #if defined(_MSC_VER)
|
cannam@147
|
86 #ifndef NOMINMAX
|
cannam@147
|
87 #define NOMINMAX 1
|
cannam@147
|
88 #endif
|
cannam@147
|
89 #include <intrin.h> // __popcnt
|
cannam@147
|
90 #endif
|
cannam@147
|
91
|
cannam@147
|
92 // =======================================================================================
|
cannam@147
|
93
|
cannam@147
|
94 namespace kj {
|
cannam@147
|
95
|
cannam@147
|
96 typedef unsigned int uint;
|
cannam@147
|
97 typedef unsigned char byte;
|
cannam@147
|
98
|
cannam@147
|
99 // =======================================================================================
|
cannam@147
|
100 // Common macros, especially for common yet compiler-specific features.
|
cannam@147
|
101
|
cannam@147
|
102 // Detect whether RTTI and exceptions are enabled, assuming they are unless we have specific
|
cannam@147
|
103 // evidence to the contrary. Clients can always define KJ_NO_RTTI or KJ_NO_EXCEPTIONS explicitly
|
cannam@147
|
104 // to override these checks.
|
cannam@147
|
105 #ifdef __GNUC__
|
cannam@147
|
106 #if !defined(KJ_NO_RTTI) && !__GXX_RTTI
|
cannam@147
|
107 #define KJ_NO_RTTI 1
|
cannam@147
|
108 #endif
|
cannam@147
|
109 #if !defined(KJ_NO_EXCEPTIONS) && !__EXCEPTIONS
|
cannam@147
|
110 #define KJ_NO_EXCEPTIONS 1
|
cannam@147
|
111 #endif
|
cannam@147
|
112 #elif defined(_MSC_VER)
|
cannam@147
|
113 #if !defined(KJ_NO_RTTI) && !defined(_CPPRTTI)
|
cannam@147
|
114 #define KJ_NO_RTTI 1
|
cannam@147
|
115 #endif
|
cannam@147
|
116 #if !defined(KJ_NO_EXCEPTIONS) && !defined(_CPPUNWIND)
|
cannam@147
|
117 #define KJ_NO_EXCEPTIONS 1
|
cannam@147
|
118 #endif
|
cannam@147
|
119 #endif
|
cannam@147
|
120
|
cannam@147
|
121 #if !defined(KJ_DEBUG) && !defined(KJ_NDEBUG)
|
cannam@147
|
122 // Heuristically decide whether to enable debug mode. If DEBUG or NDEBUG is defined, use that.
|
cannam@147
|
123 // Otherwise, fall back to checking whether optimization is enabled.
|
cannam@147
|
124 #if defined(DEBUG) || defined(_DEBUG)
|
cannam@147
|
125 #define KJ_DEBUG
|
cannam@147
|
126 #elif defined(NDEBUG)
|
cannam@147
|
127 #define KJ_NDEBUG
|
cannam@147
|
128 #elif __OPTIMIZE__
|
cannam@147
|
129 #define KJ_NDEBUG
|
cannam@147
|
130 #else
|
cannam@147
|
131 #define KJ_DEBUG
|
cannam@147
|
132 #endif
|
cannam@147
|
133 #endif
|
cannam@147
|
134
|
cannam@147
|
135 #define KJ_DISALLOW_COPY(classname) \
|
cannam@147
|
136 classname(const classname&) = delete; \
|
cannam@147
|
137 classname& operator=(const classname&) = delete
|
cannam@147
|
138 // Deletes the implicit copy constructor and assignment operator.
|
cannam@147
|
139
|
cannam@147
|
140 #ifdef __GNUC__
|
cannam@147
|
141 #define KJ_LIKELY(condition) __builtin_expect(condition, true)
|
cannam@147
|
142 #define KJ_UNLIKELY(condition) __builtin_expect(condition, false)
|
cannam@147
|
143 // Branch prediction macros. Evaluates to the condition given, but also tells the compiler that we
|
cannam@147
|
144 // expect the condition to be true/false enough of the time that it's worth hard-coding branch
|
cannam@147
|
145 // prediction.
|
cannam@147
|
146 #else
|
cannam@147
|
147 #define KJ_LIKELY(condition) (condition)
|
cannam@147
|
148 #define KJ_UNLIKELY(condition) (condition)
|
cannam@147
|
149 #endif
|
cannam@147
|
150
|
cannam@147
|
151 #if defined(KJ_DEBUG) || __NO_INLINE__
|
cannam@147
|
152 #define KJ_ALWAYS_INLINE(...) inline __VA_ARGS__
|
cannam@147
|
153 // Don't force inline in debug mode.
|
cannam@147
|
154 #else
|
cannam@147
|
155 #if defined(_MSC_VER)
|
cannam@147
|
156 #define KJ_ALWAYS_INLINE(...) __forceinline __VA_ARGS__
|
cannam@147
|
157 #else
|
cannam@147
|
158 #define KJ_ALWAYS_INLINE(...) inline __VA_ARGS__ __attribute__((always_inline))
|
cannam@147
|
159 #endif
|
cannam@147
|
160 // Force a function to always be inlined. Apply only to the prototype, not to the definition.
|
cannam@147
|
161 #endif
|
cannam@147
|
162
|
cannam@147
|
163 #if defined(_MSC_VER)
|
cannam@147
|
164 #define KJ_NOINLINE __declspec(noinline)
|
cannam@147
|
165 #else
|
cannam@147
|
166 #define KJ_NOINLINE __attribute__((noinline))
|
cannam@147
|
167 #endif
|
cannam@147
|
168
|
cannam@147
|
169 #if defined(_MSC_VER)
|
cannam@147
|
170 #define KJ_NORETURN(prototype) __declspec(noreturn) prototype
|
cannam@147
|
171 #define KJ_UNUSED
|
cannam@147
|
172 #define KJ_WARN_UNUSED_RESULT
|
cannam@147
|
173 // TODO(msvc): KJ_WARN_UNUSED_RESULT can use _Check_return_ on MSVC, but it's a prefix, so
|
cannam@147
|
174 // wrapping the whole prototype is needed. http://msdn.microsoft.com/en-us/library/jj159529.aspx
|
cannam@147
|
175 // Similarly, KJ_UNUSED could use __pragma(warning(suppress:...)), but again that's a prefix.
|
cannam@147
|
176 #else
|
cannam@147
|
177 #define KJ_NORETURN(prototype) prototype __attribute__((noreturn))
|
cannam@147
|
178 #define KJ_UNUSED __attribute__((unused))
|
cannam@147
|
179 #define KJ_WARN_UNUSED_RESULT __attribute__((warn_unused_result))
|
cannam@147
|
180 #endif
|
cannam@147
|
181
|
cannam@147
|
182 #if __clang__
|
cannam@147
|
183 #define KJ_UNUSED_MEMBER __attribute__((unused))
|
cannam@147
|
184 // Inhibits "unused" warning for member variables. Only Clang produces such a warning, while GCC
|
cannam@147
|
185 // complains if the attribute is set on members.
|
cannam@147
|
186 #else
|
cannam@147
|
187 #define KJ_UNUSED_MEMBER
|
cannam@147
|
188 #endif
|
cannam@147
|
189
|
cannam@147
|
190 #if __clang__
|
cannam@147
|
191 #define KJ_DEPRECATED(reason) \
|
cannam@147
|
192 __attribute__((deprecated(reason)))
|
cannam@147
|
193 #define KJ_UNAVAILABLE(reason) \
|
cannam@147
|
194 __attribute__((unavailable(reason)))
|
cannam@147
|
195 #elif __GNUC__
|
cannam@147
|
196 #define KJ_DEPRECATED(reason) \
|
cannam@147
|
197 __attribute__((deprecated))
|
cannam@147
|
198 #define KJ_UNAVAILABLE(reason)
|
cannam@147
|
199 #else
|
cannam@147
|
200 #define KJ_DEPRECATED(reason)
|
cannam@147
|
201 #define KJ_UNAVAILABLE(reason)
|
cannam@147
|
202 // TODO(msvc): Again, here, MSVC prefers a prefix, __declspec(deprecated).
|
cannam@147
|
203 #endif
|
cannam@147
|
204
|
cannam@147
|
205 namespace _ { // private
|
cannam@147
|
206
|
cannam@147
|
207 KJ_NORETURN(void inlineRequireFailure(
|
cannam@147
|
208 const char* file, int line, const char* expectation, const char* macroArgs,
|
cannam@147
|
209 const char* message = nullptr));
|
cannam@147
|
210
|
cannam@147
|
211 KJ_NORETURN(void unreachable());
|
cannam@147
|
212
|
cannam@147
|
213 } // namespace _ (private)
|
cannam@147
|
214
|
cannam@147
|
215 #ifdef KJ_DEBUG
|
cannam@147
|
216 #if _MSC_VER
|
cannam@147
|
217 #define KJ_IREQUIRE(condition, ...) \
|
cannam@147
|
218 if (KJ_LIKELY(condition)); else ::kj::_::inlineRequireFailure( \
|
cannam@147
|
219 __FILE__, __LINE__, #condition, "" #__VA_ARGS__, __VA_ARGS__)
|
cannam@147
|
220 // Version of KJ_DREQUIRE() which is safe to use in headers that are #included by users. Used to
|
cannam@147
|
221 // check preconditions inside inline methods. KJ_IREQUIRE is particularly useful in that
|
cannam@147
|
222 // it will be enabled depending on whether the application is compiled in debug mode rather than
|
cannam@147
|
223 // whether libkj is.
|
cannam@147
|
224 #else
|
cannam@147
|
225 #define KJ_IREQUIRE(condition, ...) \
|
cannam@147
|
226 if (KJ_LIKELY(condition)); else ::kj::_::inlineRequireFailure( \
|
cannam@147
|
227 __FILE__, __LINE__, #condition, #__VA_ARGS__, ##__VA_ARGS__)
|
cannam@147
|
228 // Version of KJ_DREQUIRE() which is safe to use in headers that are #included by users. Used to
|
cannam@147
|
229 // check preconditions inside inline methods. KJ_IREQUIRE is particularly useful in that
|
cannam@147
|
230 // it will be enabled depending on whether the application is compiled in debug mode rather than
|
cannam@147
|
231 // whether libkj is.
|
cannam@147
|
232 #endif
|
cannam@147
|
233 #else
|
cannam@147
|
234 #define KJ_IREQUIRE(condition, ...)
|
cannam@147
|
235 #endif
|
cannam@147
|
236
|
cannam@147
|
237 #define KJ_IASSERT KJ_IREQUIRE
|
cannam@147
|
238
|
cannam@147
|
239 #define KJ_UNREACHABLE ::kj::_::unreachable();
|
cannam@147
|
240 // Put this on code paths that cannot be reached to suppress compiler warnings about missing
|
cannam@147
|
241 // returns.
|
cannam@147
|
242
|
cannam@147
|
243 #if __clang__
|
cannam@147
|
244 #define KJ_CLANG_KNOWS_THIS_IS_UNREACHABLE_BUT_GCC_DOESNT
|
cannam@147
|
245 #else
|
cannam@147
|
246 #define KJ_CLANG_KNOWS_THIS_IS_UNREACHABLE_BUT_GCC_DOESNT KJ_UNREACHABLE
|
cannam@147
|
247 #endif
|
cannam@147
|
248
|
cannam@147
|
249 // #define KJ_STACK_ARRAY(type, name, size, minStack, maxStack)
|
cannam@147
|
250 //
|
cannam@147
|
251 // Allocate an array, preferably on the stack, unless it is too big. On GCC this will use
|
cannam@147
|
252 // variable-sized arrays. For other compilers we could just use a fixed-size array. `minStack`
|
cannam@147
|
253 // is the stack array size to use if variable-width arrays are not supported. `maxStack` is the
|
cannam@147
|
254 // maximum stack array size if variable-width arrays *are* supported.
|
cannam@147
|
255 #if __GNUC__ && !__clang__
|
cannam@147
|
256 #define KJ_STACK_ARRAY(type, name, size, minStack, maxStack) \
|
cannam@147
|
257 size_t name##_size = (size); \
|
cannam@147
|
258 bool name##_isOnStack = name##_size <= (maxStack); \
|
cannam@147
|
259 type name##_stack[name##_isOnStack ? size : 0]; \
|
cannam@147
|
260 ::kj::Array<type> name##_heap = name##_isOnStack ? \
|
cannam@147
|
261 nullptr : kj::heapArray<type>(name##_size); \
|
cannam@147
|
262 ::kj::ArrayPtr<type> name = name##_isOnStack ? \
|
cannam@147
|
263 kj::arrayPtr(name##_stack, name##_size) : name##_heap
|
cannam@147
|
264 #else
|
cannam@147
|
265 #define KJ_STACK_ARRAY(type, name, size, minStack, maxStack) \
|
cannam@147
|
266 size_t name##_size = (size); \
|
cannam@147
|
267 bool name##_isOnStack = name##_size <= (minStack); \
|
cannam@147
|
268 type name##_stack[minStack]; \
|
cannam@147
|
269 ::kj::Array<type> name##_heap = name##_isOnStack ? \
|
cannam@147
|
270 nullptr : kj::heapArray<type>(name##_size); \
|
cannam@147
|
271 ::kj::ArrayPtr<type> name = name##_isOnStack ? \
|
cannam@147
|
272 kj::arrayPtr(name##_stack, name##_size) : name##_heap
|
cannam@147
|
273 #endif
|
cannam@147
|
274
|
cannam@147
|
275 #define KJ_CONCAT_(x, y) x##y
|
cannam@147
|
276 #define KJ_CONCAT(x, y) KJ_CONCAT_(x, y)
|
cannam@147
|
277 #define KJ_UNIQUE_NAME(prefix) KJ_CONCAT(prefix, __LINE__)
|
cannam@147
|
278 // Create a unique identifier name. We use concatenate __LINE__ rather than __COUNTER__ so that
|
cannam@147
|
279 // the name can be used multiple times in the same macro.
|
cannam@147
|
280
|
cannam@147
|
281 #if _MSC_VER
|
cannam@147
|
282
|
cannam@147
|
283 #define KJ_CONSTEXPR(...) __VA_ARGS__
|
cannam@147
|
284 // Use in cases where MSVC barfs on constexpr. A replacement keyword (e.g. "const") can be
|
cannam@147
|
285 // provided, or just leave blank to remove the keyword entirely.
|
cannam@147
|
286 //
|
cannam@147
|
287 // TODO(msvc): Remove this hack once MSVC fully supports constexpr.
|
cannam@147
|
288
|
cannam@147
|
289 #ifndef __restrict__
|
cannam@147
|
290 #define __restrict__ __restrict
|
cannam@147
|
291 // TODO(msvc): Would it be better to define a KJ_RESTRICT macro?
|
cannam@147
|
292 #endif
|
cannam@147
|
293
|
cannam@147
|
294 #pragma warning(disable: 4521 4522)
|
cannam@147
|
295 // This warning complains when there are two copy constructors, one for a const reference and
|
cannam@147
|
296 // one for a non-const reference. It is often quite necessary to do this in wrapper templates,
|
cannam@147
|
297 // therefore this warning is dumb and we disable it.
|
cannam@147
|
298
|
cannam@147
|
299 #pragma warning(disable: 4458)
|
cannam@147
|
300 // Warns when a parameter name shadows a class member. Unfortunately my code does this a lot,
|
cannam@147
|
301 // since I don't use a special name format for members.
|
cannam@147
|
302
|
cannam@147
|
303 #else // _MSC_VER
|
cannam@147
|
304 #define KJ_CONSTEXPR(...) constexpr
|
cannam@147
|
305 #endif
|
cannam@147
|
306
|
cannam@147
|
307 // =======================================================================================
|
cannam@147
|
308 // Template metaprogramming helpers.
|
cannam@147
|
309
|
cannam@147
|
310 template <typename T> struct NoInfer_ { typedef T Type; };
|
cannam@147
|
311 template <typename T> using NoInfer = typename NoInfer_<T>::Type;
|
cannam@147
|
312 // Use NoInfer<T>::Type in place of T for a template function parameter to prevent inference of
|
cannam@147
|
313 // the type based on the parameter value.
|
cannam@147
|
314
|
cannam@147
|
315 template <typename T> struct RemoveConst_ { typedef T Type; };
|
cannam@147
|
316 template <typename T> struct RemoveConst_<const T> { typedef T Type; };
|
cannam@147
|
317 template <typename T> using RemoveConst = typename RemoveConst_<T>::Type;
|
cannam@147
|
318
|
cannam@147
|
319 template <typename> struct IsLvalueReference_ { static constexpr bool value = false; };
|
cannam@147
|
320 template <typename T> struct IsLvalueReference_<T&> { static constexpr bool value = true; };
|
cannam@147
|
321 template <typename T>
|
cannam@147
|
322 inline constexpr bool isLvalueReference() { return IsLvalueReference_<T>::value; }
|
cannam@147
|
323
|
cannam@147
|
324 template <typename T> struct Decay_ { typedef T Type; };
|
cannam@147
|
325 template <typename T> struct Decay_<T&> { typedef typename Decay_<T>::Type Type; };
|
cannam@147
|
326 template <typename T> struct Decay_<T&&> { typedef typename Decay_<T>::Type Type; };
|
cannam@147
|
327 template <typename T> struct Decay_<T[]> { typedef typename Decay_<T*>::Type Type; };
|
cannam@147
|
328 template <typename T> struct Decay_<const T[]> { typedef typename Decay_<const T*>::Type Type; };
|
cannam@147
|
329 template <typename T, size_t s> struct Decay_<T[s]> { typedef typename Decay_<T*>::Type Type; };
|
cannam@147
|
330 template <typename T, size_t s> struct Decay_<const T[s]> { typedef typename Decay_<const T*>::Type Type; };
|
cannam@147
|
331 template <typename T> struct Decay_<const T> { typedef typename Decay_<T>::Type Type; };
|
cannam@147
|
332 template <typename T> struct Decay_<volatile T> { typedef typename Decay_<T>::Type Type; };
|
cannam@147
|
333 template <typename T> using Decay = typename Decay_<T>::Type;
|
cannam@147
|
334
|
cannam@147
|
335 template <bool b> struct EnableIf_;
|
cannam@147
|
336 template <> struct EnableIf_<true> { typedef void Type; };
|
cannam@147
|
337 template <bool b> using EnableIf = typename EnableIf_<b>::Type;
|
cannam@147
|
338 // Use like:
|
cannam@147
|
339 //
|
cannam@147
|
340 // template <typename T, typename = EnableIf<isValid<T>()>
|
cannam@147
|
341 // void func(T&& t);
|
cannam@147
|
342
|
cannam@147
|
343 template <typename...> struct VoidSfinae_ { using Type = void; };
|
cannam@147
|
344 template <typename... Ts> using VoidSfinae = typename VoidSfinae_<Ts...>::Type;
|
cannam@147
|
345 // Note: VoidSfinae is std::void_t from C++17.
|
cannam@147
|
346
|
cannam@147
|
347 template <typename T>
|
cannam@147
|
348 T instance() noexcept;
|
cannam@147
|
349 // Like std::declval, but doesn't transform T into an rvalue reference. If you want that, specify
|
cannam@147
|
350 // instance<T&&>().
|
cannam@147
|
351
|
cannam@147
|
352 struct DisallowConstCopy {
|
cannam@147
|
353 // Inherit from this, or declare a member variable of this type, to prevent the class from being
|
cannam@147
|
354 // copyable from a const reference -- instead, it will only be copyable from non-const references.
|
cannam@147
|
355 // This is useful for enforcing transitive constness of contained pointers.
|
cannam@147
|
356 //
|
cannam@147
|
357 // For example, say you have a type T which contains a pointer. T has non-const methods which
|
cannam@147
|
358 // modify the value at that pointer, but T's const methods are designed to allow reading only.
|
cannam@147
|
359 // Unfortunately, if T has a regular copy constructor, someone can simply make a copy of T and
|
cannam@147
|
360 // then use it to modify the pointed-to value. However, if T inherits DisallowConstCopy, then
|
cannam@147
|
361 // callers will only be able to copy non-const instances of T. Ideally, there is some
|
cannam@147
|
362 // parallel type ImmutableT which is like a version of T that only has const methods, and can
|
cannam@147
|
363 // be copied from a const T.
|
cannam@147
|
364 //
|
cannam@147
|
365 // Note that due to C++ rules about implicit copy constructors and assignment operators, any
|
cannam@147
|
366 // type that contains or inherits from a type that disallows const copies will also automatically
|
cannam@147
|
367 // disallow const copies. Hey, cool, that's exactly what we want.
|
cannam@147
|
368
|
cannam@147
|
369 #if CAPNP_DEBUG_TYPES
|
cannam@147
|
370 // Alas! Declaring a defaulted non-const copy constructor tickles a bug which causes GCC and
|
cannam@147
|
371 // Clang to disagree on ABI, using different calling conventions to pass this type, leading to
|
cannam@147
|
372 // immediate segfaults. See:
|
cannam@147
|
373 // https://bugs.llvm.org/show_bug.cgi?id=23764
|
cannam@147
|
374 // https://gcc.gnu.org/bugzilla/show_bug.cgi?id=58074
|
cannam@147
|
375 //
|
cannam@147
|
376 // Because of this, we can't use this technique. We guard it by CAPNP_DEBUG_TYPES so that it
|
cannam@147
|
377 // still applies to the Cap'n Proto developers during internal testing.
|
cannam@147
|
378
|
cannam@147
|
379 DisallowConstCopy() = default;
|
cannam@147
|
380 DisallowConstCopy(DisallowConstCopy&) = default;
|
cannam@147
|
381 DisallowConstCopy(DisallowConstCopy&&) = default;
|
cannam@147
|
382 DisallowConstCopy& operator=(DisallowConstCopy&) = default;
|
cannam@147
|
383 DisallowConstCopy& operator=(DisallowConstCopy&&) = default;
|
cannam@147
|
384 #endif
|
cannam@147
|
385 };
|
cannam@147
|
386
|
cannam@147
|
387 #if _MSC_VER
|
cannam@147
|
388
|
cannam@147
|
389 #define KJ_CPCAP(obj) obj=::kj::cp(obj)
|
cannam@147
|
390 // TODO(msvc): MSVC refuses to invoke non-const versions of copy constructors in by-value lambda
|
cannam@147
|
391 // captures. Wrap your captured object in this macro to force the compiler to perform a copy.
|
cannam@147
|
392 // Example:
|
cannam@147
|
393 //
|
cannam@147
|
394 // struct Foo: DisallowConstCopy {};
|
cannam@147
|
395 // Foo foo;
|
cannam@147
|
396 // auto lambda = [KJ_CPCAP(foo)] {};
|
cannam@147
|
397
|
cannam@147
|
398 #else
|
cannam@147
|
399
|
cannam@147
|
400 #define KJ_CPCAP(obj) obj
|
cannam@147
|
401 // Clang and gcc both already perform copy capturing correctly with non-const copy constructors.
|
cannam@147
|
402
|
cannam@147
|
403 #endif
|
cannam@147
|
404
|
cannam@147
|
405 template <typename T>
|
cannam@147
|
406 struct DisallowConstCopyIfNotConst: public DisallowConstCopy {
|
cannam@147
|
407 // Inherit from this when implementing a template that contains a pointer to T and which should
|
cannam@147
|
408 // enforce transitive constness. If T is a const type, this has no effect. Otherwise, it is
|
cannam@147
|
409 // an alias for DisallowConstCopy.
|
cannam@147
|
410 };
|
cannam@147
|
411
|
cannam@147
|
412 template <typename T>
|
cannam@147
|
413 struct DisallowConstCopyIfNotConst<const T> {};
|
cannam@147
|
414
|
cannam@147
|
415 template <typename T> struct IsConst_ { static constexpr bool value = false; };
|
cannam@147
|
416 template <typename T> struct IsConst_<const T> { static constexpr bool value = true; };
|
cannam@147
|
417 template <typename T> constexpr bool isConst() { return IsConst_<T>::value; }
|
cannam@147
|
418
|
cannam@147
|
419 template <typename T> struct EnableIfNotConst_ { typedef T Type; };
|
cannam@147
|
420 template <typename T> struct EnableIfNotConst_<const T>;
|
cannam@147
|
421 template <typename T> using EnableIfNotConst = typename EnableIfNotConst_<T>::Type;
|
cannam@147
|
422
|
cannam@147
|
423 template <typename T> struct EnableIfConst_;
|
cannam@147
|
424 template <typename T> struct EnableIfConst_<const T> { typedef T Type; };
|
cannam@147
|
425 template <typename T> using EnableIfConst = typename EnableIfConst_<T>::Type;
|
cannam@147
|
426
|
cannam@147
|
427 template <typename T> struct RemoveConstOrDisable_ { struct Type; };
|
cannam@147
|
428 template <typename T> struct RemoveConstOrDisable_<const T> { typedef T Type; };
|
cannam@147
|
429 template <typename T> using RemoveConstOrDisable = typename RemoveConstOrDisable_<T>::Type;
|
cannam@147
|
430
|
cannam@147
|
431 template <typename T> struct IsReference_ { static constexpr bool value = false; };
|
cannam@147
|
432 template <typename T> struct IsReference_<T&> { static constexpr bool value = true; };
|
cannam@147
|
433 template <typename T> constexpr bool isReference() { return IsReference_<T>::value; }
|
cannam@147
|
434
|
cannam@147
|
435 template <typename From, typename To>
|
cannam@147
|
436 struct PropagateConst_ { typedef To Type; };
|
cannam@147
|
437 template <typename From, typename To>
|
cannam@147
|
438 struct PropagateConst_<const From, To> { typedef const To Type; };
|
cannam@147
|
439 template <typename From, typename To>
|
cannam@147
|
440 using PropagateConst = typename PropagateConst_<From, To>::Type;
|
cannam@147
|
441
|
cannam@147
|
442 namespace _ { // private
|
cannam@147
|
443
|
cannam@147
|
444 template <typename T>
|
cannam@147
|
445 T refIfLvalue(T&&);
|
cannam@147
|
446
|
cannam@147
|
447 } // namespace _ (private)
|
cannam@147
|
448
|
cannam@147
|
449 #define KJ_DECLTYPE_REF(exp) decltype(::kj::_::refIfLvalue(exp))
|
cannam@147
|
450 // Like decltype(exp), but if exp is an lvalue, produces a reference type.
|
cannam@147
|
451 //
|
cannam@147
|
452 // int i;
|
cannam@147
|
453 // decltype(i) i1(i); // i1 has type int.
|
cannam@147
|
454 // KJ_DECLTYPE_REF(i + 1) i2(i + 1); // i2 has type int.
|
cannam@147
|
455 // KJ_DECLTYPE_REF(i) i3(i); // i3 has type int&.
|
cannam@147
|
456 // KJ_DECLTYPE_REF(kj::mv(i)) i4(kj::mv(i)); // i4 has type int.
|
cannam@147
|
457
|
cannam@147
|
458 template <typename T>
|
cannam@147
|
459 struct CanConvert_ {
|
cannam@147
|
460 static int sfinae(T);
|
cannam@147
|
461 static bool sfinae(...);
|
cannam@147
|
462 };
|
cannam@147
|
463
|
cannam@147
|
464 template <typename T, typename U>
|
cannam@147
|
465 constexpr bool canConvert() {
|
cannam@147
|
466 return sizeof(CanConvert_<U>::sfinae(instance<T>())) == sizeof(int);
|
cannam@147
|
467 }
|
cannam@147
|
468
|
cannam@147
|
469 #if __GNUC__ && !__clang__ && __GNUC__ < 5
|
cannam@147
|
470 template <typename T>
|
cannam@147
|
471 constexpr bool canMemcpy() {
|
cannam@147
|
472 // Returns true if T can be copied using memcpy instead of using the copy constructor or
|
cannam@147
|
473 // assignment operator.
|
cannam@147
|
474
|
cannam@147
|
475 // GCC 4 does not have __is_trivially_constructible and friends, and there doesn't seem to be
|
cannam@147
|
476 // any reliable alternative. __has_trivial_copy() and __has_trivial_assign() return the right
|
cannam@147
|
477 // thing at one point but later on they changed such that a deleted copy constructor was
|
cannam@147
|
478 // considered "trivial" (apparently technically correct, though useless). So, on GCC 4 we give up
|
cannam@147
|
479 // and assume we can't memcpy() at all, and must explicitly copy-construct everything.
|
cannam@147
|
480 return false;
|
cannam@147
|
481 }
|
cannam@147
|
482 #define KJ_ASSERT_CAN_MEMCPY(T)
|
cannam@147
|
483 #else
|
cannam@147
|
484 template <typename T>
|
cannam@147
|
485 constexpr bool canMemcpy() {
|
cannam@147
|
486 // Returns true if T can be copied using memcpy instead of using the copy constructor or
|
cannam@147
|
487 // assignment operator.
|
cannam@147
|
488
|
cannam@147
|
489 return __is_trivially_constructible(T, const T&) && __is_trivially_assignable(T, const T&);
|
cannam@147
|
490 }
|
cannam@147
|
491 #define KJ_ASSERT_CAN_MEMCPY(T) \
|
cannam@147
|
492 static_assert(kj::canMemcpy<T>(), "this code expects this type to be memcpy()-able");
|
cannam@147
|
493 #endif
|
cannam@147
|
494
|
cannam@147
|
495 // =======================================================================================
|
cannam@147
|
496 // Equivalents to std::move() and std::forward(), since these are very commonly needed and the
|
cannam@147
|
497 // std header <utility> pulls in lots of other stuff.
|
cannam@147
|
498 //
|
cannam@147
|
499 // We use abbreviated names mv and fwd because these helpers (especially mv) are so commonly used
|
cannam@147
|
500 // that the cost of typing more letters outweighs the cost of being slightly harder to understand
|
cannam@147
|
501 // when first encountered.
|
cannam@147
|
502
|
cannam@147
|
503 template<typename T> constexpr T&& mv(T& t) noexcept { return static_cast<T&&>(t); }
|
cannam@147
|
504 template<typename T> constexpr T&& fwd(NoInfer<T>& t) noexcept { return static_cast<T&&>(t); }
|
cannam@147
|
505
|
cannam@147
|
506 template<typename T> constexpr T cp(T& t) noexcept { return t; }
|
cannam@147
|
507 template<typename T> constexpr T cp(const T& t) noexcept { return t; }
|
cannam@147
|
508 // Useful to force a copy, particularly to pass into a function that expects T&&.
|
cannam@147
|
509
|
cannam@147
|
510 template <typename T, typename U, bool takeT, bool uOK = true> struct ChooseType_;
|
cannam@147
|
511 template <typename T, typename U> struct ChooseType_<T, U, true, true> { typedef T Type; };
|
cannam@147
|
512 template <typename T, typename U> struct ChooseType_<T, U, true, false> { typedef T Type; };
|
cannam@147
|
513 template <typename T, typename U> struct ChooseType_<T, U, false, true> { typedef U Type; };
|
cannam@147
|
514
|
cannam@147
|
515 template <typename T, typename U>
|
cannam@147
|
516 using WiderType = typename ChooseType_<T, U, sizeof(T) >= sizeof(U)>::Type;
|
cannam@147
|
517
|
cannam@147
|
518 template <typename T, typename U>
|
cannam@147
|
519 inline constexpr auto min(T&& a, U&& b) -> WiderType<Decay<T>, Decay<U>> {
|
cannam@147
|
520 return a < b ? WiderType<Decay<T>, Decay<U>>(a) : WiderType<Decay<T>, Decay<U>>(b);
|
cannam@147
|
521 }
|
cannam@147
|
522
|
cannam@147
|
523 template <typename T, typename U>
|
cannam@147
|
524 inline constexpr auto max(T&& a, U&& b) -> WiderType<Decay<T>, Decay<U>> {
|
cannam@147
|
525 return a > b ? WiderType<Decay<T>, Decay<U>>(a) : WiderType<Decay<T>, Decay<U>>(b);
|
cannam@147
|
526 }
|
cannam@147
|
527
|
cannam@147
|
528 template <typename T, size_t s>
|
cannam@147
|
529 inline constexpr size_t size(T (&arr)[s]) { return s; }
|
cannam@147
|
530 template <typename T>
|
cannam@147
|
531 inline constexpr size_t size(T&& arr) { return arr.size(); }
|
cannam@147
|
532 // Returns the size of the parameter, whether the parameter is a regular C array or a container
|
cannam@147
|
533 // with a `.size()` method.
|
cannam@147
|
534
|
cannam@147
|
535 class MaxValue_ {
|
cannam@147
|
536 private:
|
cannam@147
|
537 template <typename T>
|
cannam@147
|
538 inline constexpr T maxSigned() const {
|
cannam@147
|
539 return (1ull << (sizeof(T) * 8 - 1)) - 1;
|
cannam@147
|
540 }
|
cannam@147
|
541 template <typename T>
|
cannam@147
|
542 inline constexpr T maxUnsigned() const {
|
cannam@147
|
543 return ~static_cast<T>(0u);
|
cannam@147
|
544 }
|
cannam@147
|
545
|
cannam@147
|
546 public:
|
cannam@147
|
547 #define _kJ_HANDLE_TYPE(T) \
|
cannam@147
|
548 inline constexpr operator signed T() const { return MaxValue_::maxSigned < signed T>(); } \
|
cannam@147
|
549 inline constexpr operator unsigned T() const { return MaxValue_::maxUnsigned<unsigned T>(); }
|
cannam@147
|
550 _kJ_HANDLE_TYPE(char)
|
cannam@147
|
551 _kJ_HANDLE_TYPE(short)
|
cannam@147
|
552 _kJ_HANDLE_TYPE(int)
|
cannam@147
|
553 _kJ_HANDLE_TYPE(long)
|
cannam@147
|
554 _kJ_HANDLE_TYPE(long long)
|
cannam@147
|
555 #undef _kJ_HANDLE_TYPE
|
cannam@147
|
556
|
cannam@147
|
557 inline constexpr operator char() const {
|
cannam@147
|
558 // `char` is different from both `signed char` and `unsigned char`, and may be signed or
|
cannam@147
|
559 // unsigned on different platforms. Ugh.
|
cannam@147
|
560 return char(-1) < 0 ? MaxValue_::maxSigned<char>()
|
cannam@147
|
561 : MaxValue_::maxUnsigned<char>();
|
cannam@147
|
562 }
|
cannam@147
|
563 };
|
cannam@147
|
564
|
cannam@147
|
565 class MinValue_ {
|
cannam@147
|
566 private:
|
cannam@147
|
567 template <typename T>
|
cannam@147
|
568 inline constexpr T minSigned() const {
|
cannam@147
|
569 return 1ull << (sizeof(T) * 8 - 1);
|
cannam@147
|
570 }
|
cannam@147
|
571 template <typename T>
|
cannam@147
|
572 inline constexpr T minUnsigned() const {
|
cannam@147
|
573 return 0u;
|
cannam@147
|
574 }
|
cannam@147
|
575
|
cannam@147
|
576 public:
|
cannam@147
|
577 #define _kJ_HANDLE_TYPE(T) \
|
cannam@147
|
578 inline constexpr operator signed T() const { return MinValue_::minSigned < signed T>(); } \
|
cannam@147
|
579 inline constexpr operator unsigned T() const { return MinValue_::minUnsigned<unsigned T>(); }
|
cannam@147
|
580 _kJ_HANDLE_TYPE(char)
|
cannam@147
|
581 _kJ_HANDLE_TYPE(short)
|
cannam@147
|
582 _kJ_HANDLE_TYPE(int)
|
cannam@147
|
583 _kJ_HANDLE_TYPE(long)
|
cannam@147
|
584 _kJ_HANDLE_TYPE(long long)
|
cannam@147
|
585 #undef _kJ_HANDLE_TYPE
|
cannam@147
|
586
|
cannam@147
|
587 inline constexpr operator char() const {
|
cannam@147
|
588 // `char` is different from both `signed char` and `unsigned char`, and may be signed or
|
cannam@147
|
589 // unsigned on different platforms. Ugh.
|
cannam@147
|
590 return char(-1) < 0 ? MinValue_::minSigned<char>()
|
cannam@147
|
591 : MinValue_::minUnsigned<char>();
|
cannam@147
|
592 }
|
cannam@147
|
593 };
|
cannam@147
|
594
|
cannam@147
|
595 static KJ_CONSTEXPR(const) MaxValue_ maxValue = MaxValue_();
|
cannam@147
|
596 // A special constant which, when cast to an integer type, takes on the maximum possible value of
|
cannam@147
|
597 // that type. This is useful to use as e.g. a parameter to a function because it will be robust
|
cannam@147
|
598 // in the face of changes to the parameter's type.
|
cannam@147
|
599 //
|
cannam@147
|
600 // `char` is not supported, but `signed char` and `unsigned char` are.
|
cannam@147
|
601
|
cannam@147
|
602 static KJ_CONSTEXPR(const) MinValue_ minValue = MinValue_();
|
cannam@147
|
603 // A special constant which, when cast to an integer type, takes on the minimum possible value
|
cannam@147
|
604 // of that type. This is useful to use as e.g. a parameter to a function because it will be robust
|
cannam@147
|
605 // in the face of changes to the parameter's type.
|
cannam@147
|
606 //
|
cannam@147
|
607 // `char` is not supported, but `signed char` and `unsigned char` are.
|
cannam@147
|
608
|
cannam@147
|
609 template <typename T>
|
cannam@147
|
610 inline bool operator==(T t, MaxValue_) { return t == Decay<T>(maxValue); }
|
cannam@147
|
611 template <typename T>
|
cannam@147
|
612 inline bool operator==(T t, MinValue_) { return t == Decay<T>(minValue); }
|
cannam@147
|
613
|
cannam@147
|
614 template <uint bits>
|
cannam@147
|
615 inline constexpr unsigned long long maxValueForBits() {
|
cannam@147
|
616 // Get the maximum integer representable in the given number of bits.
|
cannam@147
|
617
|
cannam@147
|
618 // 1ull << 64 is unfortunately undefined.
|
cannam@147
|
619 return (bits == 64 ? 0 : (1ull << bits)) - 1;
|
cannam@147
|
620 }
|
cannam@147
|
621
|
cannam@147
|
622 struct ThrowOverflow {
|
cannam@147
|
623 // Functor which throws an exception complaining about integer overflow. Usually this is used
|
cannam@147
|
624 // with the interfaces in units.h, but is defined here because Cap'n Proto wants to avoid
|
cannam@147
|
625 // including units.h when not using CAPNP_DEBUG_TYPES.
|
cannam@147
|
626 void operator()() const;
|
cannam@147
|
627 };
|
cannam@147
|
628
|
cannam@147
|
629 #if __GNUC__
|
cannam@147
|
630 inline constexpr float inf() { return __builtin_huge_valf(); }
|
cannam@147
|
631 inline constexpr float nan() { return __builtin_nanf(""); }
|
cannam@147
|
632
|
cannam@147
|
633 #elif _MSC_VER
|
cannam@147
|
634
|
cannam@147
|
635 // Do what MSVC math.h does
|
cannam@147
|
636 #pragma warning(push)
|
cannam@147
|
637 #pragma warning(disable: 4756) // "overflow in constant arithmetic"
|
cannam@147
|
638 inline constexpr float inf() { return (float)(1e300 * 1e300); }
|
cannam@147
|
639 #pragma warning(pop)
|
cannam@147
|
640
|
cannam@147
|
641 float nan();
|
cannam@147
|
642 // Unfortunatley, inf() * 0.0f produces a NaN with the sign bit set, whereas our preferred
|
cannam@147
|
643 // canonical NaN should not have the sign bit set. std::numeric_limits<float>::quiet_NaN()
|
cannam@147
|
644 // returns the correct NaN, but we don't want to #include that here. So, we give up and make
|
cannam@147
|
645 // this out-of-line on MSVC.
|
cannam@147
|
646 //
|
cannam@147
|
647 // TODO(msvc): Can we do better?
|
cannam@147
|
648
|
cannam@147
|
649 #else
|
cannam@147
|
650 #error "Not sure how to support your compiler."
|
cannam@147
|
651 #endif
|
cannam@147
|
652
|
cannam@147
|
653 inline constexpr bool isNaN(float f) { return f != f; }
|
cannam@147
|
654 inline constexpr bool isNaN(double f) { return f != f; }
|
cannam@147
|
655
|
cannam@147
|
656 inline int popCount(unsigned int x) {
|
cannam@147
|
657 #if defined(_MSC_VER)
|
cannam@147
|
658 return __popcnt(x);
|
cannam@147
|
659 // Note: __popcnt returns unsigned int, but the value is clearly guaranteed to fit into an int
|
cannam@147
|
660 #else
|
cannam@147
|
661 return __builtin_popcount(x);
|
cannam@147
|
662 #endif
|
cannam@147
|
663 }
|
cannam@147
|
664
|
cannam@147
|
665 // =======================================================================================
|
cannam@147
|
666 // Useful fake containers
|
cannam@147
|
667
|
cannam@147
|
668 template <typename T>
|
cannam@147
|
669 class Range {
|
cannam@147
|
670 public:
|
cannam@147
|
671 inline constexpr Range(const T& begin, const T& end): begin_(begin), end_(end) {}
|
cannam@147
|
672 inline explicit constexpr Range(const T& end): begin_(0), end_(end) {}
|
cannam@147
|
673
|
cannam@147
|
674 class Iterator {
|
cannam@147
|
675 public:
|
cannam@147
|
676 Iterator() = default;
|
cannam@147
|
677 inline Iterator(const T& value): value(value) {}
|
cannam@147
|
678
|
cannam@147
|
679 inline const T& operator* () const { return value; }
|
cannam@147
|
680 inline const T& operator[](size_t index) const { return value + index; }
|
cannam@147
|
681 inline Iterator& operator++() { ++value; return *this; }
|
cannam@147
|
682 inline Iterator operator++(int) { return Iterator(value++); }
|
cannam@147
|
683 inline Iterator& operator--() { --value; return *this; }
|
cannam@147
|
684 inline Iterator operator--(int) { return Iterator(value--); }
|
cannam@147
|
685 inline Iterator& operator+=(ptrdiff_t amount) { value += amount; return *this; }
|
cannam@147
|
686 inline Iterator& operator-=(ptrdiff_t amount) { value -= amount; return *this; }
|
cannam@147
|
687 inline Iterator operator+ (ptrdiff_t amount) const { return Iterator(value + amount); }
|
cannam@147
|
688 inline Iterator operator- (ptrdiff_t amount) const { return Iterator(value - amount); }
|
cannam@147
|
689 inline ptrdiff_t operator- (const Iterator& other) const { return value - other.value; }
|
cannam@147
|
690
|
cannam@147
|
691 inline bool operator==(const Iterator& other) const { return value == other.value; }
|
cannam@147
|
692 inline bool operator!=(const Iterator& other) const { return value != other.value; }
|
cannam@147
|
693 inline bool operator<=(const Iterator& other) const { return value <= other.value; }
|
cannam@147
|
694 inline bool operator>=(const Iterator& other) const { return value >= other.value; }
|
cannam@147
|
695 inline bool operator< (const Iterator& other) const { return value < other.value; }
|
cannam@147
|
696 inline bool operator> (const Iterator& other) const { return value > other.value; }
|
cannam@147
|
697
|
cannam@147
|
698 private:
|
cannam@147
|
699 T value;
|
cannam@147
|
700 };
|
cannam@147
|
701
|
cannam@147
|
702 inline Iterator begin() const { return Iterator(begin_); }
|
cannam@147
|
703 inline Iterator end() const { return Iterator(end_); }
|
cannam@147
|
704
|
cannam@147
|
705 inline auto size() const -> decltype(instance<T>() - instance<T>()) { return end_ - begin_; }
|
cannam@147
|
706
|
cannam@147
|
707 private:
|
cannam@147
|
708 T begin_;
|
cannam@147
|
709 T end_;
|
cannam@147
|
710 };
|
cannam@147
|
711
|
cannam@147
|
712 template <typename T, typename U>
|
cannam@147
|
713 inline constexpr Range<WiderType<Decay<T>, Decay<U>>> range(T begin, U end) {
|
cannam@147
|
714 return Range<WiderType<Decay<T>, Decay<U>>>(begin, end);
|
cannam@147
|
715 }
|
cannam@147
|
716
|
cannam@147
|
717 template <typename T>
|
cannam@147
|
718 inline constexpr Range<Decay<T>> range(T begin, T end) { return Range<Decay<T>>(begin, end); }
|
cannam@147
|
719 // Returns a fake iterable container containing all values of T from `begin` (inclusive) to `end`
|
cannam@147
|
720 // (exclusive). Example:
|
cannam@147
|
721 //
|
cannam@147
|
722 // // Prints 1, 2, 3, 4, 5, 6, 7, 8, 9.
|
cannam@147
|
723 // for (int i: kj::range(1, 10)) { print(i); }
|
cannam@147
|
724
|
cannam@147
|
725 template <typename T>
|
cannam@147
|
726 inline constexpr Range<Decay<T>> zeroTo(T end) { return Range<Decay<T>>(end); }
|
cannam@147
|
727 // Returns a fake iterable container containing all values of T from zero (inclusive) to `end`
|
cannam@147
|
728 // (exclusive). Example:
|
cannam@147
|
729 //
|
cannam@147
|
730 // // Prints 0, 1, 2, 3, 4, 5, 6, 7, 8, 9.
|
cannam@147
|
731 // for (int i: kj::zeroTo(10)) { print(i); }
|
cannam@147
|
732
|
cannam@147
|
733 template <typename T>
|
cannam@147
|
734 inline constexpr Range<size_t> indices(T&& container) {
|
cannam@147
|
735 // Shortcut for iterating over the indices of a container:
|
cannam@147
|
736 //
|
cannam@147
|
737 // for (size_t i: kj::indices(myArray)) { handle(myArray[i]); }
|
cannam@147
|
738
|
cannam@147
|
739 return range<size_t>(0, kj::size(container));
|
cannam@147
|
740 }
|
cannam@147
|
741
|
cannam@147
|
742 template <typename T>
|
cannam@147
|
743 class Repeat {
|
cannam@147
|
744 public:
|
cannam@147
|
745 inline constexpr Repeat(const T& value, size_t count): value(value), count(count) {}
|
cannam@147
|
746
|
cannam@147
|
747 class Iterator {
|
cannam@147
|
748 public:
|
cannam@147
|
749 Iterator() = default;
|
cannam@147
|
750 inline Iterator(const T& value, size_t index): value(value), index(index) {}
|
cannam@147
|
751
|
cannam@147
|
752 inline const T& operator* () const { return value; }
|
cannam@147
|
753 inline const T& operator[](ptrdiff_t index) const { return value; }
|
cannam@147
|
754 inline Iterator& operator++() { ++index; return *this; }
|
cannam@147
|
755 inline Iterator operator++(int) { return Iterator(value, index++); }
|
cannam@147
|
756 inline Iterator& operator--() { --index; return *this; }
|
cannam@147
|
757 inline Iterator operator--(int) { return Iterator(value, index--); }
|
cannam@147
|
758 inline Iterator& operator+=(ptrdiff_t amount) { index += amount; return *this; }
|
cannam@147
|
759 inline Iterator& operator-=(ptrdiff_t amount) { index -= amount; return *this; }
|
cannam@147
|
760 inline Iterator operator+ (ptrdiff_t amount) const { return Iterator(value, index + amount); }
|
cannam@147
|
761 inline Iterator operator- (ptrdiff_t amount) const { return Iterator(value, index - amount); }
|
cannam@147
|
762 inline ptrdiff_t operator- (const Iterator& other) const { return index - other.index; }
|
cannam@147
|
763
|
cannam@147
|
764 inline bool operator==(const Iterator& other) const { return index == other.index; }
|
cannam@147
|
765 inline bool operator!=(const Iterator& other) const { return index != other.index; }
|
cannam@147
|
766 inline bool operator<=(const Iterator& other) const { return index <= other.index; }
|
cannam@147
|
767 inline bool operator>=(const Iterator& other) const { return index >= other.index; }
|
cannam@147
|
768 inline bool operator< (const Iterator& other) const { return index < other.index; }
|
cannam@147
|
769 inline bool operator> (const Iterator& other) const { return index > other.index; }
|
cannam@147
|
770
|
cannam@147
|
771 private:
|
cannam@147
|
772 T value;
|
cannam@147
|
773 size_t index;
|
cannam@147
|
774 };
|
cannam@147
|
775
|
cannam@147
|
776 inline Iterator begin() const { return Iterator(value, 0); }
|
cannam@147
|
777 inline Iterator end() const { return Iterator(value, count); }
|
cannam@147
|
778
|
cannam@147
|
779 inline size_t size() const { return count; }
|
cannam@147
|
780 inline const T& operator[](ptrdiff_t) const { return value; }
|
cannam@147
|
781
|
cannam@147
|
782 private:
|
cannam@147
|
783 T value;
|
cannam@147
|
784 size_t count;
|
cannam@147
|
785 };
|
cannam@147
|
786
|
cannam@147
|
787 template <typename T>
|
cannam@147
|
788 inline constexpr Repeat<Decay<T>> repeat(T&& value, size_t count) {
|
cannam@147
|
789 // Returns a fake iterable which contains `count` repeats of `value`. Useful for e.g. creating
|
cannam@147
|
790 // a bunch of spaces: `kj::repeat(' ', indent * 2)`
|
cannam@147
|
791
|
cannam@147
|
792 return Repeat<Decay<T>>(value, count);
|
cannam@147
|
793 }
|
cannam@147
|
794
|
cannam@147
|
795 // =======================================================================================
|
cannam@147
|
796 // Manually invoking constructors and destructors
|
cannam@147
|
797 //
|
cannam@147
|
798 // ctor(x, ...) and dtor(x) invoke x's constructor or destructor, respectively.
|
cannam@147
|
799
|
cannam@147
|
800 // We want placement new, but we don't want to #include <new>. operator new cannot be defined in
|
cannam@147
|
801 // a namespace, and defining it globally conflicts with the definition in <new>. So we have to
|
cannam@147
|
802 // define a dummy type and an operator new that uses it.
|
cannam@147
|
803
|
cannam@147
|
804 namespace _ { // private
|
cannam@147
|
805 struct PlacementNew {};
|
cannam@147
|
806 } // namespace _ (private)
|
cannam@147
|
807 } // namespace kj
|
cannam@147
|
808
|
cannam@147
|
809 inline void* operator new(size_t, kj::_::PlacementNew, void* __p) noexcept {
|
cannam@147
|
810 return __p;
|
cannam@147
|
811 }
|
cannam@147
|
812
|
cannam@147
|
813 inline void operator delete(void*, kj::_::PlacementNew, void* __p) noexcept {}
|
cannam@147
|
814
|
cannam@147
|
815 namespace kj {
|
cannam@147
|
816
|
cannam@147
|
817 template <typename T, typename... Params>
|
cannam@147
|
818 inline void ctor(T& location, Params&&... params) {
|
cannam@147
|
819 new (_::PlacementNew(), &location) T(kj::fwd<Params>(params)...);
|
cannam@147
|
820 }
|
cannam@147
|
821
|
cannam@147
|
822 template <typename T>
|
cannam@147
|
823 inline void dtor(T& location) {
|
cannam@147
|
824 location.~T();
|
cannam@147
|
825 }
|
cannam@147
|
826
|
cannam@147
|
827 // =======================================================================================
|
cannam@147
|
828 // Maybe
|
cannam@147
|
829 //
|
cannam@147
|
830 // Use in cases where you want to indicate that a value may be null. Using Maybe<T&> instead of T*
|
cannam@147
|
831 // forces the caller to handle the null case in order to satisfy the compiler, thus reliably
|
cannam@147
|
832 // preventing null pointer dereferences at runtime.
|
cannam@147
|
833 //
|
cannam@147
|
834 // Maybe<T> can be implicitly constructed from T and from nullptr. Additionally, it can be
|
cannam@147
|
835 // implicitly constructed from T*, in which case the pointer is checked for nullness at runtime.
|
cannam@147
|
836 // To read the value of a Maybe<T>, do:
|
cannam@147
|
837 //
|
cannam@147
|
838 // KJ_IF_MAYBE(value, someFuncReturningMaybe()) {
|
cannam@147
|
839 // doSomething(*value);
|
cannam@147
|
840 // } else {
|
cannam@147
|
841 // maybeWasNull();
|
cannam@147
|
842 // }
|
cannam@147
|
843 //
|
cannam@147
|
844 // KJ_IF_MAYBE's first parameter is a variable name which will be defined within the following
|
cannam@147
|
845 // block. The variable will behave like a (guaranteed non-null) pointer to the Maybe's value,
|
cannam@147
|
846 // though it may or may not actually be a pointer.
|
cannam@147
|
847 //
|
cannam@147
|
848 // Note that Maybe<T&> actually just wraps a pointer, whereas Maybe<T> wraps a T and a boolean
|
cannam@147
|
849 // indicating nullness.
|
cannam@147
|
850
|
cannam@147
|
851 template <typename T>
|
cannam@147
|
852 class Maybe;
|
cannam@147
|
853
|
cannam@147
|
854 namespace _ { // private
|
cannam@147
|
855
|
cannam@147
|
856 template <typename T>
|
cannam@147
|
857 class NullableValue {
|
cannam@147
|
858 // Class whose interface behaves much like T*, but actually contains an instance of T and a
|
cannam@147
|
859 // boolean flag indicating nullness.
|
cannam@147
|
860
|
cannam@147
|
861 public:
|
cannam@147
|
862 inline NullableValue(NullableValue&& other) noexcept(noexcept(T(instance<T&&>())))
|
cannam@147
|
863 : isSet(other.isSet) {
|
cannam@147
|
864 if (isSet) {
|
cannam@147
|
865 ctor(value, kj::mv(other.value));
|
cannam@147
|
866 }
|
cannam@147
|
867 }
|
cannam@147
|
868 inline NullableValue(const NullableValue& other)
|
cannam@147
|
869 : isSet(other.isSet) {
|
cannam@147
|
870 if (isSet) {
|
cannam@147
|
871 ctor(value, other.value);
|
cannam@147
|
872 }
|
cannam@147
|
873 }
|
cannam@147
|
874 inline NullableValue(NullableValue& other)
|
cannam@147
|
875 : isSet(other.isSet) {
|
cannam@147
|
876 if (isSet) {
|
cannam@147
|
877 ctor(value, other.value);
|
cannam@147
|
878 }
|
cannam@147
|
879 }
|
cannam@147
|
880 inline ~NullableValue()
|
cannam@147
|
881 #if _MSC_VER
|
cannam@147
|
882 // TODO(msvc): MSVC has a hard time with noexcept specifier expressions that are more complex
|
cannam@147
|
883 // than `true` or `false`. We had a workaround for VS2015, but VS2017 regressed.
|
cannam@147
|
884 noexcept(false)
|
cannam@147
|
885 #else
|
cannam@147
|
886 noexcept(noexcept(instance<T&>().~T()))
|
cannam@147
|
887 #endif
|
cannam@147
|
888 {
|
cannam@147
|
889 if (isSet) {
|
cannam@147
|
890 dtor(value);
|
cannam@147
|
891 }
|
cannam@147
|
892 }
|
cannam@147
|
893
|
cannam@147
|
894 inline T& operator*() & { return value; }
|
cannam@147
|
895 inline const T& operator*() const & { return value; }
|
cannam@147
|
896 inline T&& operator*() && { return kj::mv(value); }
|
cannam@147
|
897 inline const T&& operator*() const && { return kj::mv(value); }
|
cannam@147
|
898 inline T* operator->() { return &value; }
|
cannam@147
|
899 inline const T* operator->() const { return &value; }
|
cannam@147
|
900 inline operator T*() { return isSet ? &value : nullptr; }
|
cannam@147
|
901 inline operator const T*() const { return isSet ? &value : nullptr; }
|
cannam@147
|
902
|
cannam@147
|
903 template <typename... Params>
|
cannam@147
|
904 inline T& emplace(Params&&... params) {
|
cannam@147
|
905 if (isSet) {
|
cannam@147
|
906 isSet = false;
|
cannam@147
|
907 dtor(value);
|
cannam@147
|
908 }
|
cannam@147
|
909 ctor(value, kj::fwd<Params>(params)...);
|
cannam@147
|
910 isSet = true;
|
cannam@147
|
911 return value;
|
cannam@147
|
912 }
|
cannam@147
|
913
|
cannam@147
|
914 private: // internal interface used by friends only
|
cannam@147
|
915 inline NullableValue() noexcept: isSet(false) {}
|
cannam@147
|
916 inline NullableValue(T&& t) noexcept(noexcept(T(instance<T&&>())))
|
cannam@147
|
917 : isSet(true) {
|
cannam@147
|
918 ctor(value, kj::mv(t));
|
cannam@147
|
919 }
|
cannam@147
|
920 inline NullableValue(T& t)
|
cannam@147
|
921 : isSet(true) {
|
cannam@147
|
922 ctor(value, t);
|
cannam@147
|
923 }
|
cannam@147
|
924 inline NullableValue(const T& t)
|
cannam@147
|
925 : isSet(true) {
|
cannam@147
|
926 ctor(value, t);
|
cannam@147
|
927 }
|
cannam@147
|
928 inline NullableValue(const T* t)
|
cannam@147
|
929 : isSet(t != nullptr) {
|
cannam@147
|
930 if (isSet) ctor(value, *t);
|
cannam@147
|
931 }
|
cannam@147
|
932 template <typename U>
|
cannam@147
|
933 inline NullableValue(NullableValue<U>&& other) noexcept(noexcept(T(instance<U&&>())))
|
cannam@147
|
934 : isSet(other.isSet) {
|
cannam@147
|
935 if (isSet) {
|
cannam@147
|
936 ctor(value, kj::mv(other.value));
|
cannam@147
|
937 }
|
cannam@147
|
938 }
|
cannam@147
|
939 template <typename U>
|
cannam@147
|
940 inline NullableValue(const NullableValue<U>& other)
|
cannam@147
|
941 : isSet(other.isSet) {
|
cannam@147
|
942 if (isSet) {
|
cannam@147
|
943 ctor(value, other.value);
|
cannam@147
|
944 }
|
cannam@147
|
945 }
|
cannam@147
|
946 template <typename U>
|
cannam@147
|
947 inline NullableValue(const NullableValue<U&>& other)
|
cannam@147
|
948 : isSet(other.isSet) {
|
cannam@147
|
949 if (isSet) {
|
cannam@147
|
950 ctor(value, *other.ptr);
|
cannam@147
|
951 }
|
cannam@147
|
952 }
|
cannam@147
|
953 inline NullableValue(decltype(nullptr)): isSet(false) {}
|
cannam@147
|
954
|
cannam@147
|
955 inline NullableValue& operator=(NullableValue&& other) {
|
cannam@147
|
956 if (&other != this) {
|
cannam@147
|
957 // Careful about throwing destructors/constructors here.
|
cannam@147
|
958 if (isSet) {
|
cannam@147
|
959 isSet = false;
|
cannam@147
|
960 dtor(value);
|
cannam@147
|
961 }
|
cannam@147
|
962 if (other.isSet) {
|
cannam@147
|
963 ctor(value, kj::mv(other.value));
|
cannam@147
|
964 isSet = true;
|
cannam@147
|
965 }
|
cannam@147
|
966 }
|
cannam@147
|
967 return *this;
|
cannam@147
|
968 }
|
cannam@147
|
969
|
cannam@147
|
970 inline NullableValue& operator=(NullableValue& other) {
|
cannam@147
|
971 if (&other != this) {
|
cannam@147
|
972 // Careful about throwing destructors/constructors here.
|
cannam@147
|
973 if (isSet) {
|
cannam@147
|
974 isSet = false;
|
cannam@147
|
975 dtor(value);
|
cannam@147
|
976 }
|
cannam@147
|
977 if (other.isSet) {
|
cannam@147
|
978 ctor(value, other.value);
|
cannam@147
|
979 isSet = true;
|
cannam@147
|
980 }
|
cannam@147
|
981 }
|
cannam@147
|
982 return *this;
|
cannam@147
|
983 }
|
cannam@147
|
984
|
cannam@147
|
985 inline NullableValue& operator=(const NullableValue& other) {
|
cannam@147
|
986 if (&other != this) {
|
cannam@147
|
987 // Careful about throwing destructors/constructors here.
|
cannam@147
|
988 if (isSet) {
|
cannam@147
|
989 isSet = false;
|
cannam@147
|
990 dtor(value);
|
cannam@147
|
991 }
|
cannam@147
|
992 if (other.isSet) {
|
cannam@147
|
993 ctor(value, other.value);
|
cannam@147
|
994 isSet = true;
|
cannam@147
|
995 }
|
cannam@147
|
996 }
|
cannam@147
|
997 return *this;
|
cannam@147
|
998 }
|
cannam@147
|
999
|
cannam@147
|
1000 inline bool operator==(decltype(nullptr)) const { return !isSet; }
|
cannam@147
|
1001 inline bool operator!=(decltype(nullptr)) const { return isSet; }
|
cannam@147
|
1002
|
cannam@147
|
1003 private:
|
cannam@147
|
1004 bool isSet;
|
cannam@147
|
1005
|
cannam@147
|
1006 #if _MSC_VER
|
cannam@147
|
1007 #pragma warning(push)
|
cannam@147
|
1008 #pragma warning(disable: 4624)
|
cannam@147
|
1009 // Warns that the anonymous union has a deleted destructor when T is non-trivial. This warning
|
cannam@147
|
1010 // seems broken.
|
cannam@147
|
1011 #endif
|
cannam@147
|
1012
|
cannam@147
|
1013 union {
|
cannam@147
|
1014 T value;
|
cannam@147
|
1015 };
|
cannam@147
|
1016
|
cannam@147
|
1017 #if _MSC_VER
|
cannam@147
|
1018 #pragma warning(pop)
|
cannam@147
|
1019 #endif
|
cannam@147
|
1020
|
cannam@147
|
1021 friend class kj::Maybe<T>;
|
cannam@147
|
1022 template <typename U>
|
cannam@147
|
1023 friend NullableValue<U>&& readMaybe(Maybe<U>&& maybe);
|
cannam@147
|
1024 };
|
cannam@147
|
1025
|
cannam@147
|
1026 template <typename T>
|
cannam@147
|
1027 inline NullableValue<T>&& readMaybe(Maybe<T>&& maybe) { return kj::mv(maybe.ptr); }
|
cannam@147
|
1028 template <typename T>
|
cannam@147
|
1029 inline T* readMaybe(Maybe<T>& maybe) { return maybe.ptr; }
|
cannam@147
|
1030 template <typename T>
|
cannam@147
|
1031 inline const T* readMaybe(const Maybe<T>& maybe) { return maybe.ptr; }
|
cannam@147
|
1032 template <typename T>
|
cannam@147
|
1033 inline T* readMaybe(Maybe<T&>&& maybe) { return maybe.ptr; }
|
cannam@147
|
1034 template <typename T>
|
cannam@147
|
1035 inline T* readMaybe(const Maybe<T&>& maybe) { return maybe.ptr; }
|
cannam@147
|
1036
|
cannam@147
|
1037 template <typename T>
|
cannam@147
|
1038 inline T* readMaybe(T* ptr) { return ptr; }
|
cannam@147
|
1039 // Allow KJ_IF_MAYBE to work on regular pointers.
|
cannam@147
|
1040
|
cannam@147
|
1041 } // namespace _ (private)
|
cannam@147
|
1042
|
cannam@147
|
1043 #define KJ_IF_MAYBE(name, exp) if (auto name = ::kj::_::readMaybe(exp))
|
cannam@147
|
1044
|
cannam@147
|
1045 template <typename T>
|
cannam@147
|
1046 class Maybe {
|
cannam@147
|
1047 // A T, or nullptr.
|
cannam@147
|
1048
|
cannam@147
|
1049 // IF YOU CHANGE THIS CLASS: Note that there is a specialization of it in memory.h.
|
cannam@147
|
1050
|
cannam@147
|
1051 public:
|
cannam@147
|
1052 Maybe(): ptr(nullptr) {}
|
cannam@147
|
1053 Maybe(T&& t) noexcept(noexcept(T(instance<T&&>()))): ptr(kj::mv(t)) {}
|
cannam@147
|
1054 Maybe(T& t): ptr(t) {}
|
cannam@147
|
1055 Maybe(const T& t): ptr(t) {}
|
cannam@147
|
1056 Maybe(const T* t) noexcept: ptr(t) {}
|
cannam@147
|
1057 Maybe(Maybe&& other) noexcept(noexcept(T(instance<T&&>()))): ptr(kj::mv(other.ptr)) {}
|
cannam@147
|
1058 Maybe(const Maybe& other): ptr(other.ptr) {}
|
cannam@147
|
1059 Maybe(Maybe& other): ptr(other.ptr) {}
|
cannam@147
|
1060
|
cannam@147
|
1061 template <typename U>
|
cannam@147
|
1062 Maybe(Maybe<U>&& other) noexcept(noexcept(T(instance<U&&>()))) {
|
cannam@147
|
1063 KJ_IF_MAYBE(val, kj::mv(other)) {
|
cannam@147
|
1064 ptr.emplace(kj::mv(*val));
|
cannam@147
|
1065 }
|
cannam@147
|
1066 }
|
cannam@147
|
1067 template <typename U>
|
cannam@147
|
1068 Maybe(const Maybe<U>& other) {
|
cannam@147
|
1069 KJ_IF_MAYBE(val, other) {
|
cannam@147
|
1070 ptr.emplace(*val);
|
cannam@147
|
1071 }
|
cannam@147
|
1072 }
|
cannam@147
|
1073
|
cannam@147
|
1074 Maybe(decltype(nullptr)) noexcept: ptr(nullptr) {}
|
cannam@147
|
1075
|
cannam@147
|
1076 template <typename... Params>
|
cannam@147
|
1077 inline T& emplace(Params&&... params) {
|
cannam@147
|
1078 // Replace this Maybe's content with a new value constructed by passing the given parametrs to
|
cannam@147
|
1079 // T's constructor. This can be used to initialize a Maybe without copying or even moving a T.
|
cannam@147
|
1080 // Returns a reference to the newly-constructed value.
|
cannam@147
|
1081
|
cannam@147
|
1082 return ptr.emplace(kj::fwd<Params>(params)...);
|
cannam@147
|
1083 }
|
cannam@147
|
1084
|
cannam@147
|
1085 inline Maybe& operator=(Maybe&& other) { ptr = kj::mv(other.ptr); return *this; }
|
cannam@147
|
1086 inline Maybe& operator=(Maybe& other) { ptr = other.ptr; return *this; }
|
cannam@147
|
1087 inline Maybe& operator=(const Maybe& other) { ptr = other.ptr; return *this; }
|
cannam@147
|
1088
|
cannam@147
|
1089 inline bool operator==(decltype(nullptr)) const { return ptr == nullptr; }
|
cannam@147
|
1090 inline bool operator!=(decltype(nullptr)) const { return ptr != nullptr; }
|
cannam@147
|
1091
|
cannam@147
|
1092 T& orDefault(T& defaultValue) {
|
cannam@147
|
1093 if (ptr == nullptr) {
|
cannam@147
|
1094 return defaultValue;
|
cannam@147
|
1095 } else {
|
cannam@147
|
1096 return *ptr;
|
cannam@147
|
1097 }
|
cannam@147
|
1098 }
|
cannam@147
|
1099 const T& orDefault(const T& defaultValue) const {
|
cannam@147
|
1100 if (ptr == nullptr) {
|
cannam@147
|
1101 return defaultValue;
|
cannam@147
|
1102 } else {
|
cannam@147
|
1103 return *ptr;
|
cannam@147
|
1104 }
|
cannam@147
|
1105 }
|
cannam@147
|
1106
|
cannam@147
|
1107 template <typename Func>
|
cannam@147
|
1108 auto map(Func&& f) & -> Maybe<decltype(f(instance<T&>()))> {
|
cannam@147
|
1109 if (ptr == nullptr) {
|
cannam@147
|
1110 return nullptr;
|
cannam@147
|
1111 } else {
|
cannam@147
|
1112 return f(*ptr);
|
cannam@147
|
1113 }
|
cannam@147
|
1114 }
|
cannam@147
|
1115
|
cannam@147
|
1116 template <typename Func>
|
cannam@147
|
1117 auto map(Func&& f) const & -> Maybe<decltype(f(instance<const T&>()))> {
|
cannam@147
|
1118 if (ptr == nullptr) {
|
cannam@147
|
1119 return nullptr;
|
cannam@147
|
1120 } else {
|
cannam@147
|
1121 return f(*ptr);
|
cannam@147
|
1122 }
|
cannam@147
|
1123 }
|
cannam@147
|
1124
|
cannam@147
|
1125 template <typename Func>
|
cannam@147
|
1126 auto map(Func&& f) && -> Maybe<decltype(f(instance<T&&>()))> {
|
cannam@147
|
1127 if (ptr == nullptr) {
|
cannam@147
|
1128 return nullptr;
|
cannam@147
|
1129 } else {
|
cannam@147
|
1130 return f(kj::mv(*ptr));
|
cannam@147
|
1131 }
|
cannam@147
|
1132 }
|
cannam@147
|
1133
|
cannam@147
|
1134 template <typename Func>
|
cannam@147
|
1135 auto map(Func&& f) const && -> Maybe<decltype(f(instance<const T&&>()))> {
|
cannam@147
|
1136 if (ptr == nullptr) {
|
cannam@147
|
1137 return nullptr;
|
cannam@147
|
1138 } else {
|
cannam@147
|
1139 return f(kj::mv(*ptr));
|
cannam@147
|
1140 }
|
cannam@147
|
1141 }
|
cannam@147
|
1142
|
cannam@147
|
1143 private:
|
cannam@147
|
1144 _::NullableValue<T> ptr;
|
cannam@147
|
1145
|
cannam@147
|
1146 template <typename U>
|
cannam@147
|
1147 friend class Maybe;
|
cannam@147
|
1148 template <typename U>
|
cannam@147
|
1149 friend _::NullableValue<U>&& _::readMaybe(Maybe<U>&& maybe);
|
cannam@147
|
1150 template <typename U>
|
cannam@147
|
1151 friend U* _::readMaybe(Maybe<U>& maybe);
|
cannam@147
|
1152 template <typename U>
|
cannam@147
|
1153 friend const U* _::readMaybe(const Maybe<U>& maybe);
|
cannam@147
|
1154 };
|
cannam@147
|
1155
|
cannam@147
|
1156 template <typename T>
|
cannam@147
|
1157 class Maybe<T&>: public DisallowConstCopyIfNotConst<T> {
|
cannam@147
|
1158 public:
|
cannam@147
|
1159 Maybe() noexcept: ptr(nullptr) {}
|
cannam@147
|
1160 Maybe(T& t) noexcept: ptr(&t) {}
|
cannam@147
|
1161 Maybe(T* t) noexcept: ptr(t) {}
|
cannam@147
|
1162
|
cannam@147
|
1163 template <typename U>
|
cannam@147
|
1164 inline Maybe(Maybe<U&>& other) noexcept: ptr(other.ptr) {}
|
cannam@147
|
1165 template <typename U>
|
cannam@147
|
1166 inline Maybe(const Maybe<const U&>& other) noexcept: ptr(other.ptr) {}
|
cannam@147
|
1167 inline Maybe(decltype(nullptr)) noexcept: ptr(nullptr) {}
|
cannam@147
|
1168
|
cannam@147
|
1169 inline Maybe& operator=(T& other) noexcept { ptr = &other; return *this; }
|
cannam@147
|
1170 inline Maybe& operator=(T* other) noexcept { ptr = other; return *this; }
|
cannam@147
|
1171 template <typename U>
|
cannam@147
|
1172 inline Maybe& operator=(Maybe<U&>& other) noexcept { ptr = other.ptr; return *this; }
|
cannam@147
|
1173 template <typename U>
|
cannam@147
|
1174 inline Maybe& operator=(const Maybe<const U&>& other) noexcept { ptr = other.ptr; return *this; }
|
cannam@147
|
1175
|
cannam@147
|
1176 inline bool operator==(decltype(nullptr)) const { return ptr == nullptr; }
|
cannam@147
|
1177 inline bool operator!=(decltype(nullptr)) const { return ptr != nullptr; }
|
cannam@147
|
1178
|
cannam@147
|
1179 T& orDefault(T& defaultValue) {
|
cannam@147
|
1180 if (ptr == nullptr) {
|
cannam@147
|
1181 return defaultValue;
|
cannam@147
|
1182 } else {
|
cannam@147
|
1183 return *ptr;
|
cannam@147
|
1184 }
|
cannam@147
|
1185 }
|
cannam@147
|
1186 const T& orDefault(const T& defaultValue) const {
|
cannam@147
|
1187 if (ptr == nullptr) {
|
cannam@147
|
1188 return defaultValue;
|
cannam@147
|
1189 } else {
|
cannam@147
|
1190 return *ptr;
|
cannam@147
|
1191 }
|
cannam@147
|
1192 }
|
cannam@147
|
1193
|
cannam@147
|
1194 template <typename Func>
|
cannam@147
|
1195 auto map(Func&& f) -> Maybe<decltype(f(instance<T&>()))> {
|
cannam@147
|
1196 if (ptr == nullptr) {
|
cannam@147
|
1197 return nullptr;
|
cannam@147
|
1198 } else {
|
cannam@147
|
1199 return f(*ptr);
|
cannam@147
|
1200 }
|
cannam@147
|
1201 }
|
cannam@147
|
1202
|
cannam@147
|
1203 private:
|
cannam@147
|
1204 T* ptr;
|
cannam@147
|
1205
|
cannam@147
|
1206 template <typename U>
|
cannam@147
|
1207 friend class Maybe;
|
cannam@147
|
1208 template <typename U>
|
cannam@147
|
1209 friend U* _::readMaybe(Maybe<U&>&& maybe);
|
cannam@147
|
1210 template <typename U>
|
cannam@147
|
1211 friend U* _::readMaybe(const Maybe<U&>& maybe);
|
cannam@147
|
1212 };
|
cannam@147
|
1213
|
cannam@147
|
1214 // =======================================================================================
|
cannam@147
|
1215 // ArrayPtr
|
cannam@147
|
1216 //
|
cannam@147
|
1217 // So common that we put it in common.h rather than array.h.
|
cannam@147
|
1218
|
cannam@147
|
1219 template <typename T>
|
cannam@147
|
1220 class ArrayPtr: public DisallowConstCopyIfNotConst<T> {
|
cannam@147
|
1221 // A pointer to an array. Includes a size. Like any pointer, it doesn't own the target data,
|
cannam@147
|
1222 // and passing by value only copies the pointer, not the target.
|
cannam@147
|
1223
|
cannam@147
|
1224 public:
|
cannam@147
|
1225 inline constexpr ArrayPtr(): ptr(nullptr), size_(0) {}
|
cannam@147
|
1226 inline constexpr ArrayPtr(decltype(nullptr)): ptr(nullptr), size_(0) {}
|
cannam@147
|
1227 inline constexpr ArrayPtr(T* ptr, size_t size): ptr(ptr), size_(size) {}
|
cannam@147
|
1228 inline constexpr ArrayPtr(T* begin, T* end): ptr(begin), size_(end - begin) {}
|
cannam@147
|
1229 inline KJ_CONSTEXPR() ArrayPtr(::std::initializer_list<RemoveConstOrDisable<T>> init)
|
cannam@147
|
1230 : ptr(init.begin()), size_(init.size()) {}
|
cannam@147
|
1231
|
cannam@147
|
1232 template <size_t size>
|
cannam@147
|
1233 inline constexpr ArrayPtr(T (&native)[size]): ptr(native), size_(size) {}
|
cannam@147
|
1234 // Construct an ArrayPtr from a native C-style array.
|
cannam@147
|
1235
|
cannam@147
|
1236 inline operator ArrayPtr<const T>() const {
|
cannam@147
|
1237 return ArrayPtr<const T>(ptr, size_);
|
cannam@147
|
1238 }
|
cannam@147
|
1239 inline ArrayPtr<const T> asConst() const {
|
cannam@147
|
1240 return ArrayPtr<const T>(ptr, size_);
|
cannam@147
|
1241 }
|
cannam@147
|
1242
|
cannam@147
|
1243 inline size_t size() const { return size_; }
|
cannam@147
|
1244 inline const T& operator[](size_t index) const {
|
cannam@147
|
1245 KJ_IREQUIRE(index < size_, "Out-of-bounds ArrayPtr access.");
|
cannam@147
|
1246 return ptr[index];
|
cannam@147
|
1247 }
|
cannam@147
|
1248 inline T& operator[](size_t index) {
|
cannam@147
|
1249 KJ_IREQUIRE(index < size_, "Out-of-bounds ArrayPtr access.");
|
cannam@147
|
1250 return ptr[index];
|
cannam@147
|
1251 }
|
cannam@147
|
1252
|
cannam@147
|
1253 inline T* begin() { return ptr; }
|
cannam@147
|
1254 inline T* end() { return ptr + size_; }
|
cannam@147
|
1255 inline T& front() { return *ptr; }
|
cannam@147
|
1256 inline T& back() { return *(ptr + size_ - 1); }
|
cannam@147
|
1257 inline const T* begin() const { return ptr; }
|
cannam@147
|
1258 inline const T* end() const { return ptr + size_; }
|
cannam@147
|
1259 inline const T& front() const { return *ptr; }
|
cannam@147
|
1260 inline const T& back() const { return *(ptr + size_ - 1); }
|
cannam@147
|
1261
|
cannam@147
|
1262 inline ArrayPtr<const T> slice(size_t start, size_t end) const {
|
cannam@147
|
1263 KJ_IREQUIRE(start <= end && end <= size_, "Out-of-bounds ArrayPtr::slice().");
|
cannam@147
|
1264 return ArrayPtr<const T>(ptr + start, end - start);
|
cannam@147
|
1265 }
|
cannam@147
|
1266 inline ArrayPtr slice(size_t start, size_t end) {
|
cannam@147
|
1267 KJ_IREQUIRE(start <= end && end <= size_, "Out-of-bounds ArrayPtr::slice().");
|
cannam@147
|
1268 return ArrayPtr(ptr + start, end - start);
|
cannam@147
|
1269 }
|
cannam@147
|
1270
|
cannam@147
|
1271 inline ArrayPtr<PropagateConst<T, byte>> asBytes() const {
|
cannam@147
|
1272 // Reinterpret the array as a byte array. This is explicitly legal under C++ aliasing
|
cannam@147
|
1273 // rules.
|
cannam@147
|
1274 return { reinterpret_cast<PropagateConst<T, byte>*>(ptr), size_ * sizeof(T) };
|
cannam@147
|
1275 }
|
cannam@147
|
1276 inline ArrayPtr<PropagateConst<T, char>> asChars() const {
|
cannam@147
|
1277 // Reinterpret the array as a char array. This is explicitly legal under C++ aliasing
|
cannam@147
|
1278 // rules.
|
cannam@147
|
1279 return { reinterpret_cast<PropagateConst<T, char>*>(ptr), size_ * sizeof(T) };
|
cannam@147
|
1280 }
|
cannam@147
|
1281
|
cannam@147
|
1282 inline bool operator==(decltype(nullptr)) const { return size_ == 0; }
|
cannam@147
|
1283 inline bool operator!=(decltype(nullptr)) const { return size_ != 0; }
|
cannam@147
|
1284
|
cannam@147
|
1285 inline bool operator==(const ArrayPtr& other) const {
|
cannam@147
|
1286 if (size_ != other.size_) return false;
|
cannam@147
|
1287 for (size_t i = 0; i < size_; i++) {
|
cannam@147
|
1288 if (ptr[i] != other[i]) return false;
|
cannam@147
|
1289 }
|
cannam@147
|
1290 return true;
|
cannam@147
|
1291 }
|
cannam@147
|
1292 inline bool operator!=(const ArrayPtr& other) const { return !(*this == other); }
|
cannam@147
|
1293
|
cannam@147
|
1294 private:
|
cannam@147
|
1295 T* ptr;
|
cannam@147
|
1296 size_t size_;
|
cannam@147
|
1297 };
|
cannam@147
|
1298
|
cannam@147
|
1299 template <typename T>
|
cannam@147
|
1300 inline constexpr ArrayPtr<T> arrayPtr(T* ptr, size_t size) {
|
cannam@147
|
1301 // Use this function to construct ArrayPtrs without writing out the type name.
|
cannam@147
|
1302 return ArrayPtr<T>(ptr, size);
|
cannam@147
|
1303 }
|
cannam@147
|
1304
|
cannam@147
|
1305 template <typename T>
|
cannam@147
|
1306 inline constexpr ArrayPtr<T> arrayPtr(T* begin, T* end) {
|
cannam@147
|
1307 // Use this function to construct ArrayPtrs without writing out the type name.
|
cannam@147
|
1308 return ArrayPtr<T>(begin, end);
|
cannam@147
|
1309 }
|
cannam@147
|
1310
|
cannam@147
|
1311 // =======================================================================================
|
cannam@147
|
1312 // Casts
|
cannam@147
|
1313
|
cannam@147
|
1314 template <typename To, typename From>
|
cannam@147
|
1315 To implicitCast(From&& from) {
|
cannam@147
|
1316 // `implicitCast<T>(value)` casts `value` to type `T` only if the conversion is implicit. Useful
|
cannam@147
|
1317 // for e.g. resolving ambiguous overloads without sacrificing type-safety.
|
cannam@147
|
1318 return kj::fwd<From>(from);
|
cannam@147
|
1319 }
|
cannam@147
|
1320
|
cannam@147
|
1321 template <typename To, typename From>
|
cannam@147
|
1322 Maybe<To&> dynamicDowncastIfAvailable(From& from) {
|
cannam@147
|
1323 // If RTTI is disabled, always returns nullptr. Otherwise, works like dynamic_cast. Useful
|
cannam@147
|
1324 // in situations where dynamic_cast could allow an optimization, but isn't strictly necessary
|
cannam@147
|
1325 // for correctness. It is highly recommended that you try to arrange all your dynamic_casts
|
cannam@147
|
1326 // this way, as a dynamic_cast that is necessary for correctness implies a flaw in the interface
|
cannam@147
|
1327 // design.
|
cannam@147
|
1328
|
cannam@147
|
1329 // Force a compile error if To is not a subtype of From. Cross-casting is rare; if it is needed
|
cannam@147
|
1330 // we should have a separate cast function like dynamicCrosscastIfAvailable().
|
cannam@147
|
1331 if (false) {
|
cannam@147
|
1332 kj::implicitCast<From*>(kj::implicitCast<To*>(nullptr));
|
cannam@147
|
1333 }
|
cannam@147
|
1334
|
cannam@147
|
1335 #if KJ_NO_RTTI
|
cannam@147
|
1336 return nullptr;
|
cannam@147
|
1337 #else
|
cannam@147
|
1338 return dynamic_cast<To*>(&from);
|
cannam@147
|
1339 #endif
|
cannam@147
|
1340 }
|
cannam@147
|
1341
|
cannam@147
|
1342 template <typename To, typename From>
|
cannam@147
|
1343 To& downcast(From& from) {
|
cannam@147
|
1344 // Down-cast a value to a sub-type, asserting that the cast is valid. In opt mode this is a
|
cannam@147
|
1345 // static_cast, but in debug mode (when RTTI is enabled) a dynamic_cast will be used to verify
|
cannam@147
|
1346 // that the value really has the requested type.
|
cannam@147
|
1347
|
cannam@147
|
1348 // Force a compile error if To is not a subtype of From.
|
cannam@147
|
1349 if (false) {
|
cannam@147
|
1350 kj::implicitCast<From*>(kj::implicitCast<To*>(nullptr));
|
cannam@147
|
1351 }
|
cannam@147
|
1352
|
cannam@147
|
1353 #if !KJ_NO_RTTI
|
cannam@147
|
1354 KJ_IREQUIRE(dynamic_cast<To*>(&from) != nullptr, "Value cannot be downcast() to requested type.");
|
cannam@147
|
1355 #endif
|
cannam@147
|
1356
|
cannam@147
|
1357 return static_cast<To&>(from);
|
cannam@147
|
1358 }
|
cannam@147
|
1359
|
cannam@147
|
1360 // =======================================================================================
|
cannam@147
|
1361 // Defer
|
cannam@147
|
1362
|
cannam@147
|
1363 namespace _ { // private
|
cannam@147
|
1364
|
cannam@147
|
1365 template <typename Func>
|
cannam@147
|
1366 class Deferred {
|
cannam@147
|
1367 public:
|
cannam@147
|
1368 inline Deferred(Func&& func): func(kj::fwd<Func>(func)), canceled(false) {}
|
cannam@147
|
1369 inline ~Deferred() noexcept(false) { if (!canceled) func(); }
|
cannam@147
|
1370 KJ_DISALLOW_COPY(Deferred);
|
cannam@147
|
1371
|
cannam@147
|
1372 // This move constructor is usually optimized away by the compiler.
|
cannam@147
|
1373 inline Deferred(Deferred&& other): func(kj::mv(other.func)), canceled(false) {
|
cannam@147
|
1374 other.canceled = true;
|
cannam@147
|
1375 }
|
cannam@147
|
1376 private:
|
cannam@147
|
1377 Func func;
|
cannam@147
|
1378 bool canceled;
|
cannam@147
|
1379 };
|
cannam@147
|
1380
|
cannam@147
|
1381 } // namespace _ (private)
|
cannam@147
|
1382
|
cannam@147
|
1383 template <typename Func>
|
cannam@147
|
1384 _::Deferred<Func> defer(Func&& func) {
|
cannam@147
|
1385 // Returns an object which will invoke the given functor in its destructor. The object is not
|
cannam@147
|
1386 // copyable but is movable with the semantics you'd expect. Since the return type is private,
|
cannam@147
|
1387 // you need to assign to an `auto` variable.
|
cannam@147
|
1388 //
|
cannam@147
|
1389 // The KJ_DEFER macro provides slightly more convenient syntax for the common case where you
|
cannam@147
|
1390 // want some code to run at current scope exit.
|
cannam@147
|
1391
|
cannam@147
|
1392 return _::Deferred<Func>(kj::fwd<Func>(func));
|
cannam@147
|
1393 }
|
cannam@147
|
1394
|
cannam@147
|
1395 #define KJ_DEFER(code) auto KJ_UNIQUE_NAME(_kjDefer) = ::kj::defer([&](){code;})
|
cannam@147
|
1396 // Run the given code when the function exits, whether by return or exception.
|
cannam@147
|
1397
|
cannam@147
|
1398 } // namespace kj
|
cannam@147
|
1399
|
cannam@147
|
1400 #endif // KJ_COMMON_H_
|