annotate win64-msvc/include/kj/common.h @ 143:e95e00bdc3eb

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