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