annotate win64-msvc/include/kj/common.h @ 57:e56993504470

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