annotate win32-mingw/include/kj/common.h @ 70:9e21af8f0420

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