annotate win64-msvc/include/kj/common.h @ 169:223a55898ab9 tip default

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