annotate win32-mingw/include/kj/common.h @ 51:bbebe9a28170

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