common.h (70465B)
1 // Copyright (c) 2013-2014 Sandstorm Development Group, Inc. and contributors 2 // Licensed under the MIT License: 3 // 4 // Permission is hereby granted, free of charge, to any person obtaining a copy 5 // of this software and associated documentation files (the "Software"), to deal 6 // in the Software without restriction, including without limitation the rights 7 // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 // copies of the Software, and to permit persons to whom the Software is 9 // furnished to do so, subject to the following conditions: 10 // 11 // The above copyright notice and this permission notice shall be included in 12 // all copies or substantial portions of the Software. 13 // 14 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 20 // THE SOFTWARE. 21 22 // Header that should be #included by everyone. 23 // 24 // This defines very simple utilities that are widely applicable. 25 26 #pragma once 27 28 #if defined(__GNUC__) || defined(__clang__) 29 #define KJ_BEGIN_SYSTEM_HEADER _Pragma("GCC system_header") 30 #elif defined(_MSC_VER) 31 #define KJ_BEGIN_SYSTEM_HEADER __pragma(warning(push, 0)) 32 #define KJ_END_SYSTEM_HEADER __pragma(warning(pop)) 33 #endif 34 35 #ifndef KJ_BEGIN_SYSTEM_HEADER 36 #define KJ_BEGIN_SYSTEM_HEADER 37 #endif 38 39 #ifndef KJ_END_SYSTEM_HEADER 40 #define KJ_END_SYSTEM_HEADER 41 #endif 42 43 #if !defined(KJ_HEADER_WARNINGS) || !KJ_HEADER_WARNINGS 44 #define KJ_BEGIN_HEADER KJ_BEGIN_SYSTEM_HEADER 45 #define KJ_END_HEADER KJ_END_SYSTEM_HEADER 46 #else 47 #define KJ_BEGIN_HEADER 48 #define KJ_END_HEADER 49 #endif 50 51 #ifdef __has_cpp_attribute 52 #define KJ_HAS_CPP_ATTRIBUTE(x) __has_cpp_attribute(x) 53 #else 54 #define KJ_HAS_CPP_ATTRIBUTE(x) 0 55 #endif 56 57 #ifdef __has_feature 58 #define KJ_HAS_COMPILER_FEATURE(x) __has_feature(x) 59 #else 60 #define KJ_HAS_COMPILER_FEATURE(x) 0 61 #endif 62 63 KJ_BEGIN_HEADER 64 65 #ifndef KJ_NO_COMPILER_CHECK 66 // Technically, __cplusplus should be 201402L for C++14, but GCC 4.9 -- which is supported -- still 67 // had it defined to 201300L even with -std=c++14. 68 #if __cplusplus < 201300L && !__CDT_PARSER__ && !_MSC_VER 69 #error "This code requires C++14. Either your compiler does not support it or it is not enabled." 70 #ifdef __GNUC__ 71 // Compiler claims compatibility with GCC, so presumably supports -std. 72 #error "Pass -std=c++14 on the compiler command line to enable C++14." 73 #endif 74 #endif 75 76 #ifdef __GNUC__ 77 #if __clang__ 78 #if __clang_major__ < 5 79 #warning "This library requires at least Clang 5.0." 80 #elif __cplusplus >= 201402L && !__has_include(<initializer_list>) 81 #warning "Your compiler supports C++14 but your C++ standard library does not. If your "\ 82 "system has libc++ installed (as should be the case on e.g. Mac OSX), try adding "\ 83 "-stdlib=libc++ to your CXXFLAGS." 84 #endif 85 #else 86 #if __GNUC__ < 5 87 #warning "This library requires at least GCC 5.0." 88 #endif 89 #endif 90 #elif defined(_MSC_VER) 91 #if _MSC_VER < 1910 && !defined(__clang__) 92 #error "You need Visual Studio 2017 or better to compile this code." 93 #endif 94 #else 95 #warning "I don't recognize your compiler. As of this writing, Clang, GCC, and Visual Studio "\ 96 "are the only known compilers with enough C++14 support for this library. "\ 97 "#define KJ_NO_COMPILER_CHECK to make this warning go away." 98 #endif 99 #endif 100 101 #include <stddef.h> 102 #include <initializer_list> 103 104 #if __linux__ && __cplusplus > 201200L 105 // Hack around stdlib bug with C++14 that exists on some Linux systems. 106 // Apparently in this mode the C library decides not to define gets() but the C++ library still 107 // tries to import it into the std namespace. This bug has been fixed at the source but is still 108 // widely present in the wild e.g. on Ubuntu 14.04. 109 #undef _GLIBCXX_HAVE_GETS 110 #endif 111 112 #if defined(_MSC_VER) 113 #ifndef NOMINMAX 114 #define NOMINMAX 1 115 #endif 116 #include <intrin.h> // __popcnt 117 #endif 118 119 // ======================================================================================= 120 121 namespace kj { 122 123 typedef unsigned int uint; 124 typedef unsigned char byte; 125 126 // ======================================================================================= 127 // Common macros, especially for common yet compiler-specific features. 128 129 // Detect whether RTTI and exceptions are enabled, assuming they are unless we have specific 130 // evidence to the contrary. Clients can always define KJ_NO_RTTI or KJ_NO_EXCEPTIONS explicitly 131 // to override these checks. 132 133 // TODO: Ideally we'd use __cpp_exceptions/__cpp_rtti not being defined as the first pass since 134 // that is the standard compliant way. However, it's unclear how to use those macros (or any 135 // others) to distinguish between the compiler supporting feature detection and the feature being 136 // disabled vs the compiler not supporting feature detection at all. 137 #if defined(__has_feature) 138 #if !defined(KJ_NO_RTTI) && !__has_feature(cxx_rtti) 139 #define KJ_NO_RTTI 1 140 #endif 141 #if !defined(KJ_NO_EXCEPTIONS) && !__has_feature(cxx_exceptions) 142 #define KJ_NO_EXCEPTIONS 1 143 #endif 144 #elif defined(__GNUC__) 145 #if !defined(KJ_NO_RTTI) && !__GXX_RTTI 146 #define KJ_NO_RTTI 1 147 #endif 148 #if !defined(KJ_NO_EXCEPTIONS) && !__EXCEPTIONS 149 #define KJ_NO_EXCEPTIONS 1 150 #endif 151 #elif defined(_MSC_VER) 152 #if !defined(KJ_NO_RTTI) && !defined(_CPPRTTI) 153 #define KJ_NO_RTTI 1 154 #endif 155 #if !defined(KJ_NO_EXCEPTIONS) && !defined(_CPPUNWIND) 156 #define KJ_NO_EXCEPTIONS 1 157 #endif 158 #endif 159 160 #if !defined(KJ_DEBUG) && !defined(KJ_NDEBUG) 161 // Heuristically decide whether to enable debug mode. If DEBUG or NDEBUG is defined, use that. 162 // Otherwise, fall back to checking whether optimization is enabled. 163 #if defined(DEBUG) || defined(_DEBUG) 164 #define KJ_DEBUG 165 #elif defined(NDEBUG) 166 #define KJ_NDEBUG 167 #elif __OPTIMIZE__ 168 #define KJ_NDEBUG 169 #else 170 #define KJ_DEBUG 171 #endif 172 #endif 173 174 #define KJ_DISALLOW_COPY(classname) \ 175 classname(const classname&) = delete; \ 176 classname& operator=(const classname&) = delete 177 // Deletes the implicit copy constructor and assignment operator. 178 179 #ifdef __GNUC__ 180 #define KJ_LIKELY(condition) __builtin_expect(condition, true) 181 #define KJ_UNLIKELY(condition) __builtin_expect(condition, false) 182 // Branch prediction macros. Evaluates to the condition given, but also tells the compiler that we 183 // expect the condition to be true/false enough of the time that it's worth hard-coding branch 184 // prediction. 185 #else 186 #define KJ_LIKELY(condition) (condition) 187 #define KJ_UNLIKELY(condition) (condition) 188 #endif 189 190 #if defined(KJ_DEBUG) || __NO_INLINE__ 191 #define KJ_ALWAYS_INLINE(...) inline __VA_ARGS__ 192 // Don't force inline in debug mode. 193 #else 194 #if defined(_MSC_VER) && !defined(__clang__) 195 #define KJ_ALWAYS_INLINE(...) __forceinline __VA_ARGS__ 196 #else 197 #define KJ_ALWAYS_INLINE(...) inline __VA_ARGS__ __attribute__((always_inline)) 198 #endif 199 // Force a function to always be inlined. Apply only to the prototype, not to the definition. 200 #endif 201 202 #if defined(_MSC_VER) && !defined(__clang__) 203 #define KJ_NOINLINE __declspec(noinline) 204 #else 205 #define KJ_NOINLINE __attribute__((noinline)) 206 #endif 207 208 #if defined(_MSC_VER) && !__clang__ 209 #define KJ_NORETURN(prototype) __declspec(noreturn) prototype 210 #define KJ_UNUSED 211 #define KJ_WARN_UNUSED_RESULT 212 // TODO(msvc): KJ_WARN_UNUSED_RESULT can use _Check_return_ on MSVC, but it's a prefix, so 213 // wrapping the whole prototype is needed. http://msdn.microsoft.com/en-us/library/jj159529.aspx 214 // Similarly, KJ_UNUSED could use __pragma(warning(suppress:...)), but again that's a prefix. 215 #else 216 #define KJ_NORETURN(prototype) prototype __attribute__((noreturn)) 217 #define KJ_UNUSED __attribute__((unused)) 218 #define KJ_WARN_UNUSED_RESULT __attribute__((warn_unused_result)) 219 #endif 220 221 #if KJ_HAS_CPP_ATTRIBUTE(clang::lifetimebound) 222 // If this is generating too many false-positives, the user is responsible for disabling the 223 // problematic warning at the compiler switch level or by suppressing the place where the 224 // false-positive is reported through compiler-specific pragmas if available. 225 #define KJ_LIFETIMEBOUND [[clang::lifetimebound]] 226 #else 227 #define KJ_LIFETIMEBOUND 228 #endif 229 // Annotation that indicates the returned value is referencing a resource owned by this type (e.g. 230 // cStr() on a std::string). Unfortunately this lifetime can only be superficial currently & cannot 231 // track further. For example, there's no way to get `array.asPtr().slice(5, 6))` to warn if the 232 // last slice exceeds the lifetime of `array`. That's because in the general case `ArrayPtr::slice` 233 // can't have the lifetime bound annotation since it's not wrong to do something like: 234 // ArrayPtr<char> doSomething(ArrayPtr<char> foo) { 235 // ... 236 // return foo.slice(5, 6); 237 // } 238 // If `ArrayPtr::slice` had a lifetime bound then the compiler would warn about this perfectly 239 // legitimate method. Really there needs to be 2 more annotations. One to inherit the lifetime bound 240 // and another to inherit the lifetime bound from a parameter (which really could be the same thing 241 // by allowing a syntax like `[[clang::lifetimebound(*this)]]`. 242 // https://clang.llvm.org/docs/AttributeReference.html#lifetimebound 243 244 #if __clang__ 245 #define KJ_UNUSED_MEMBER __attribute__((unused)) 246 // Inhibits "unused" warning for member variables. Only Clang produces such a warning, while GCC 247 // complains if the attribute is set on members. 248 #else 249 #define KJ_UNUSED_MEMBER 250 #endif 251 252 #if __cplusplus > 201703L || (__clang__ && __clang_major__ >= 9 && __cplusplus >= 201103L) 253 // Technically this was only added to C++20 but Clang allows it for >= C++11 and spelunking the 254 // attributes manual indicates it first came in with Clang 9. 255 #define KJ_NO_UNIQUE_ADDRESS [[no_unique_address]] 256 #else 257 #define KJ_NO_UNIQUE_ADDRESS 258 #endif 259 260 #if KJ_HAS_COMPILER_FEATURE(thread_sanitizer) || defined(__SANITIZE_THREAD__) 261 #define KJ_DISABLE_TSAN __attribute__((no_sanitize("thread"), noinline)) 262 #else 263 #define KJ_DISABLE_TSAN 264 #endif 265 266 #if __clang__ 267 #define KJ_DEPRECATED(reason) \ 268 __attribute__((deprecated(reason))) 269 #define KJ_UNAVAILABLE(reason) \ 270 __attribute__((unavailable(reason))) 271 #elif __GNUC__ 272 #define KJ_DEPRECATED(reason) \ 273 __attribute__((deprecated)) 274 #define KJ_UNAVAILABLE(reason) 275 #else 276 #define KJ_DEPRECATED(reason) 277 #define KJ_UNAVAILABLE(reason) 278 // TODO(msvc): Again, here, MSVC prefers a prefix, __declspec(deprecated). 279 #endif 280 281 #if KJ_TESTING_KJ // defined in KJ's own unit tests; others should not define this 282 #undef KJ_DEPRECATED 283 #define KJ_DEPRECATED(reason) 284 #endif 285 286 namespace _ { // private 287 288 KJ_NORETURN(void inlineRequireFailure( 289 const char* file, int line, const char* expectation, const char* macroArgs, 290 const char* message = nullptr)); 291 292 KJ_NORETURN(void unreachable()); 293 294 } // namespace _ (private) 295 296 #ifdef KJ_DEBUG 297 #if _MSC_VER && !defined(__clang__) && (!defined(_MSVC_TRADITIONAL) || _MSVC_TRADITIONAL) 298 #define KJ_MSVC_TRADITIONAL_CPP 1 299 #endif 300 #if KJ_MSVC_TRADITIONAL_CPP 301 #define KJ_IREQUIRE(condition, ...) \ 302 if (KJ_LIKELY(condition)); else ::kj::_::inlineRequireFailure( \ 303 __FILE__, __LINE__, #condition, "" #__VA_ARGS__, __VA_ARGS__) 304 // Version of KJ_DREQUIRE() which is safe to use in headers that are #included by users. Used to 305 // check preconditions inside inline methods. KJ_IREQUIRE is particularly useful in that 306 // it will be enabled depending on whether the application is compiled in debug mode rather than 307 // whether libkj is. 308 #else 309 #define KJ_IREQUIRE(condition, ...) \ 310 if (KJ_LIKELY(condition)); else ::kj::_::inlineRequireFailure( \ 311 __FILE__, __LINE__, #condition, #__VA_ARGS__, ##__VA_ARGS__) 312 // Version of KJ_DREQUIRE() which is safe to use in headers that are #included by users. Used to 313 // check preconditions inside inline methods. KJ_IREQUIRE is particularly useful in that 314 // it will be enabled depending on whether the application is compiled in debug mode rather than 315 // whether libkj is. 316 #endif 317 #else 318 #define KJ_IREQUIRE(condition, ...) 319 #endif 320 321 #define KJ_IASSERT KJ_IREQUIRE 322 323 #define KJ_UNREACHABLE ::kj::_::unreachable(); 324 // Put this on code paths that cannot be reached to suppress compiler warnings about missing 325 // returns. 326 327 #if __clang__ 328 #define KJ_CLANG_KNOWS_THIS_IS_UNREACHABLE_BUT_GCC_DOESNT 329 #else 330 #define KJ_CLANG_KNOWS_THIS_IS_UNREACHABLE_BUT_GCC_DOESNT KJ_UNREACHABLE 331 #endif 332 333 #if __clang__ 334 #define KJ_KNOWN_UNREACHABLE(code) \ 335 do { \ 336 _Pragma("clang diagnostic push") \ 337 _Pragma("clang diagnostic ignored \"-Wunreachable-code\"") \ 338 code; \ 339 _Pragma("clang diagnostic pop") \ 340 } while (false) 341 // Suppress "unreachable code" warnings on intentionally unreachable code. 342 #else 343 // TODO(someday): Add support for non-clang compilers. 344 #define KJ_KNOWN_UNREACHABLE(code) do {code;} while(false) 345 #endif 346 347 #if KJ_HAS_CPP_ATTRIBUTE(fallthrough) 348 #define KJ_FALLTHROUGH [[fallthrough]] 349 #else 350 #define KJ_FALLTHROUGH 351 #endif 352 353 // #define KJ_STACK_ARRAY(type, name, size, minStack, maxStack) 354 // 355 // Allocate an array, preferably on the stack, unless it is too big. On GCC this will use 356 // variable-sized arrays. For other compilers we could just use a fixed-size array. `minStack` 357 // is the stack array size to use if variable-width arrays are not supported. `maxStack` is the 358 // maximum stack array size if variable-width arrays *are* supported. 359 #if __GNUC__ && !__clang__ 360 #define KJ_STACK_ARRAY(type, name, size, minStack, maxStack) \ 361 size_t name##_size = (size); \ 362 bool name##_isOnStack = name##_size <= (maxStack); \ 363 type name##_stack[kj::max(1, name##_isOnStack ? name##_size : 0)]; \ 364 ::kj::Array<type> name##_heap = name##_isOnStack ? \ 365 nullptr : kj::heapArray<type>(name##_size); \ 366 ::kj::ArrayPtr<type> name = name##_isOnStack ? \ 367 kj::arrayPtr(name##_stack, name##_size) : name##_heap 368 #else 369 #define KJ_STACK_ARRAY(type, name, size, minStack, maxStack) \ 370 size_t name##_size = (size); \ 371 bool name##_isOnStack = name##_size <= (minStack); \ 372 type name##_stack[minStack]; \ 373 ::kj::Array<type> name##_heap = name##_isOnStack ? \ 374 nullptr : kj::heapArray<type>(name##_size); \ 375 ::kj::ArrayPtr<type> name = name##_isOnStack ? \ 376 kj::arrayPtr(name##_stack, name##_size) : name##_heap 377 #endif 378 379 #define KJ_CONCAT_(x, y) x##y 380 #define KJ_CONCAT(x, y) KJ_CONCAT_(x, y) 381 #define KJ_UNIQUE_NAME(prefix) KJ_CONCAT(prefix, __LINE__) 382 // Create a unique identifier name. We use concatenate __LINE__ rather than __COUNTER__ so that 383 // the name can be used multiple times in the same macro. 384 385 #if _MSC_VER && !defined(__clang__) 386 387 #define KJ_CONSTEXPR(...) __VA_ARGS__ 388 // Use in cases where MSVC barfs on constexpr. A replacement keyword (e.g. "const") can be 389 // provided, or just leave blank to remove the keyword entirely. 390 // 391 // TODO(msvc): Remove this hack once MSVC fully supports constexpr. 392 393 #ifndef __restrict__ 394 #define __restrict__ __restrict 395 // TODO(msvc): Would it be better to define a KJ_RESTRICT macro? 396 #endif 397 398 #pragma warning(disable: 4521 4522) 399 // This warning complains when there are two copy constructors, one for a const reference and 400 // one for a non-const reference. It is often quite necessary to do this in wrapper templates, 401 // therefore this warning is dumb and we disable it. 402 403 #pragma warning(disable: 4458) 404 // Warns when a parameter name shadows a class member. Unfortunately my code does this a lot, 405 // since I don't use a special name format for members. 406 407 #else // _MSC_VER 408 #define KJ_CONSTEXPR(...) constexpr 409 #endif 410 411 // ======================================================================================= 412 // Template metaprogramming helpers. 413 414 template <typename T> struct NoInfer_ { typedef T Type; }; 415 template <typename T> using NoInfer = typename NoInfer_<T>::Type; 416 // Use NoInfer<T>::Type in place of T for a template function parameter to prevent inference of 417 // the type based on the parameter value. 418 419 template <typename T> struct RemoveConst_ { typedef T Type; }; 420 template <typename T> struct RemoveConst_<const T> { typedef T Type; }; 421 template <typename T> using RemoveConst = typename RemoveConst_<T>::Type; 422 423 template <typename> struct IsLvalueReference_ { static constexpr bool value = false; }; 424 template <typename T> struct IsLvalueReference_<T&> { static constexpr bool value = true; }; 425 template <typename T> 426 inline constexpr bool isLvalueReference() { return IsLvalueReference_<T>::value; } 427 428 template <typename T> struct Decay_ { typedef T Type; }; 429 template <typename T> struct Decay_<T&> { typedef typename Decay_<T>::Type Type; }; 430 template <typename T> struct Decay_<T&&> { typedef typename Decay_<T>::Type Type; }; 431 template <typename T> struct Decay_<T[]> { typedef typename Decay_<T*>::Type Type; }; 432 template <typename T> struct Decay_<const T[]> { typedef typename Decay_<const T*>::Type Type; }; 433 template <typename T, size_t s> struct Decay_<T[s]> { typedef typename Decay_<T*>::Type Type; }; 434 template <typename T, size_t s> struct Decay_<const T[s]> { typedef typename Decay_<const T*>::Type Type; }; 435 template <typename T> struct Decay_<const T> { typedef typename Decay_<T>::Type Type; }; 436 template <typename T> struct Decay_<volatile T> { typedef typename Decay_<T>::Type Type; }; 437 template <typename T> using Decay = typename Decay_<T>::Type; 438 439 template <bool b> struct EnableIf_; 440 template <> struct EnableIf_<true> { typedef void Type; }; 441 template <bool b> using EnableIf = typename EnableIf_<b>::Type; 442 // Use like: 443 // 444 // template <typename T, typename = EnableIf<isValid<T>()>> 445 // void func(T&& t); 446 447 template <typename...> struct VoidSfinae_ { using Type = void; }; 448 template <typename... Ts> using VoidSfinae = typename VoidSfinae_<Ts...>::Type; 449 // Note: VoidSfinae is std::void_t from C++17. 450 451 template <typename T> 452 T instance() noexcept; 453 // Like std::declval, but doesn't transform T into an rvalue reference. If you want that, specify 454 // instance<T&&>(). 455 456 struct DisallowConstCopy { 457 // Inherit from this, or declare a member variable of this type, to prevent the class from being 458 // copyable from a const reference -- instead, it will only be copyable from non-const references. 459 // This is useful for enforcing transitive constness of contained pointers. 460 // 461 // For example, say you have a type T which contains a pointer. T has non-const methods which 462 // modify the value at that pointer, but T's const methods are designed to allow reading only. 463 // Unfortunately, if T has a regular copy constructor, someone can simply make a copy of T and 464 // then use it to modify the pointed-to value. However, if T inherits DisallowConstCopy, then 465 // callers will only be able to copy non-const instances of T. Ideally, there is some 466 // parallel type ImmutableT which is like a version of T that only has const methods, and can 467 // be copied from a const T. 468 // 469 // Note that due to C++ rules about implicit copy constructors and assignment operators, any 470 // type that contains or inherits from a type that disallows const copies will also automatically 471 // disallow const copies. Hey, cool, that's exactly what we want. 472 473 #if CAPNP_DEBUG_TYPES 474 // Alas! Declaring a defaulted non-const copy constructor tickles a bug which causes GCC and 475 // Clang to disagree on ABI, using different calling conventions to pass this type, leading to 476 // immediate segfaults. See: 477 // https://bugs.llvm.org/show_bug.cgi?id=23764 478 // https://gcc.gnu.org/bugzilla/show_bug.cgi?id=58074 479 // 480 // Because of this, we can't use this technique. We guard it by CAPNP_DEBUG_TYPES so that it 481 // still applies to the Cap'n Proto developers during internal testing. 482 483 DisallowConstCopy() = default; 484 DisallowConstCopy(DisallowConstCopy&) = default; 485 DisallowConstCopy(DisallowConstCopy&&) = default; 486 DisallowConstCopy& operator=(DisallowConstCopy&) = default; 487 DisallowConstCopy& operator=(DisallowConstCopy&&) = default; 488 #endif 489 }; 490 491 #if _MSC_VER && !defined(__clang__) 492 493 #define KJ_CPCAP(obj) obj=::kj::cp(obj) 494 // TODO(msvc): MSVC refuses to invoke non-const versions of copy constructors in by-value lambda 495 // captures. Wrap your captured object in this macro to force the compiler to perform a copy. 496 // Example: 497 // 498 // struct Foo: DisallowConstCopy {}; 499 // Foo foo; 500 // auto lambda = [KJ_CPCAP(foo)] {}; 501 502 #else 503 504 #define KJ_CPCAP(obj) obj 505 // Clang and gcc both already perform copy capturing correctly with non-const copy constructors. 506 507 #endif 508 509 template <typename T> 510 struct DisallowConstCopyIfNotConst: public DisallowConstCopy { 511 // Inherit from this when implementing a template that contains a pointer to T and which should 512 // enforce transitive constness. If T is a const type, this has no effect. Otherwise, it is 513 // an alias for DisallowConstCopy. 514 }; 515 516 template <typename T> 517 struct DisallowConstCopyIfNotConst<const T> {}; 518 519 template <typename T> struct IsConst_ { static constexpr bool value = false; }; 520 template <typename T> struct IsConst_<const T> { static constexpr bool value = true; }; 521 template <typename T> constexpr bool isConst() { return IsConst_<T>::value; } 522 523 template <typename T> struct EnableIfNotConst_ { typedef T Type; }; 524 template <typename T> struct EnableIfNotConst_<const T>; 525 template <typename T> using EnableIfNotConst = typename EnableIfNotConst_<T>::Type; 526 527 template <typename T> struct EnableIfConst_; 528 template <typename T> struct EnableIfConst_<const T> { typedef T Type; }; 529 template <typename T> using EnableIfConst = typename EnableIfConst_<T>::Type; 530 531 template <typename T> struct RemoveConstOrDisable_ { struct Type; }; 532 template <typename T> struct RemoveConstOrDisable_<const T> { typedef T Type; }; 533 template <typename T> using RemoveConstOrDisable = typename RemoveConstOrDisable_<T>::Type; 534 535 template <typename T> struct IsReference_ { static constexpr bool value = false; }; 536 template <typename T> struct IsReference_<T&> { static constexpr bool value = true; }; 537 template <typename T> constexpr bool isReference() { return IsReference_<T>::value; } 538 539 template <typename From, typename To> 540 struct PropagateConst_ { typedef To Type; }; 541 template <typename From, typename To> 542 struct PropagateConst_<const From, To> { typedef const To Type; }; 543 template <typename From, typename To> 544 using PropagateConst = typename PropagateConst_<From, To>::Type; 545 546 namespace _ { // private 547 548 template <typename T> 549 T refIfLvalue(T&&); 550 551 } // namespace _ (private) 552 553 #define KJ_DECLTYPE_REF(exp) decltype(::kj::_::refIfLvalue(exp)) 554 // Like decltype(exp), but if exp is an lvalue, produces a reference type. 555 // 556 // int i; 557 // decltype(i) i1(i); // i1 has type int. 558 // KJ_DECLTYPE_REF(i + 1) i2(i + 1); // i2 has type int. 559 // KJ_DECLTYPE_REF(i) i3(i); // i3 has type int&. 560 // KJ_DECLTYPE_REF(kj::mv(i)) i4(kj::mv(i)); // i4 has type int. 561 562 template <typename T, typename U> struct IsSameType_ { static constexpr bool value = false; }; 563 template <typename T> struct IsSameType_<T, T> { static constexpr bool value = true; }; 564 template <typename T, typename U> constexpr bool isSameType() { return IsSameType_<T, U>::value; } 565 566 template <typename T> 567 struct CanConvert_ { 568 static int sfinae(T); 569 static bool sfinae(...); 570 }; 571 572 template <typename T, typename U> 573 constexpr bool canConvert() { 574 return sizeof(CanConvert_<U>::sfinae(instance<T>())) == sizeof(int); 575 } 576 577 #if __GNUC__ && !__clang__ && __GNUC__ < 5 578 template <typename T> 579 constexpr bool canMemcpy() { 580 // Returns true if T can be copied using memcpy instead of using the copy constructor or 581 // assignment operator. 582 583 // GCC 4 does not have __is_trivially_constructible and friends, and there doesn't seem to be 584 // any reliable alternative. __has_trivial_copy() and __has_trivial_assign() return the right 585 // thing at one point but later on they changed such that a deleted copy constructor was 586 // considered "trivial" (apparently technically correct, though useless). So, on GCC 4 we give up 587 // and assume we can't memcpy() at all, and must explicitly copy-construct everything. 588 return false; 589 } 590 #define KJ_ASSERT_CAN_MEMCPY(T) 591 #else 592 template <typename T> 593 constexpr bool canMemcpy() { 594 // Returns true if T can be copied using memcpy instead of using the copy constructor or 595 // assignment operator. 596 597 return __is_trivially_constructible(T, const T&) && __is_trivially_assignable(T, const T&); 598 } 599 #define KJ_ASSERT_CAN_MEMCPY(T) \ 600 static_assert(kj::canMemcpy<T>(), "this code expects this type to be memcpy()-able"); 601 #endif 602 603 template <typename T> 604 class Badge { 605 // A pattern for marking individual methods such that they can only be called from a specific 606 // caller class: Make the method public but give it a parameter of type `Badge<Caller>`. Only 607 // `Caller` can construct one, so only `Caller` can call the method. 608 // 609 // // We only allow calls from the class `Bar`. 610 // void foo(Badge<Bar>) 611 // 612 // The call site looks like: 613 // 614 // foo({}); 615 // 616 // This pattern also works well for declaring private constructors, but still being able to use 617 // them with `kj::heap()`, etc. 618 // 619 // Idea from: https://awesomekling.github.io/Serenity-C++-patterns-The-Badge/ 620 // 621 // Note that some forms of this idea make the copy constructor private as well, in order to 622 // prohibit `Badge<NotMe>(*(Badge<NotMe>*)nullptr)`. However, that would prevent badges from 623 // being passed through forwarding functions like `kj::heap()`, which would ruin one of the main 624 // use cases for this pattern in KJ. In any case, dereferencing a null pointer is UB; there are 625 // plenty of other ways to get access to private members if you're willing to go UB. For one-off 626 // debugging purposes, you might as well use `#define private public` at the top of the file. 627 private: 628 Badge() {} 629 friend T; 630 }; 631 632 // ======================================================================================= 633 // Equivalents to std::move() and std::forward(), since these are very commonly needed and the 634 // std header <utility> pulls in lots of other stuff. 635 // 636 // We use abbreviated names mv and fwd because these helpers (especially mv) are so commonly used 637 // that the cost of typing more letters outweighs the cost of being slightly harder to understand 638 // when first encountered. 639 640 template<typename T> constexpr T&& mv(T& t) noexcept { return static_cast<T&&>(t); } 641 template<typename T> constexpr T&& fwd(NoInfer<T>& t) noexcept { return static_cast<T&&>(t); } 642 643 template<typename T> constexpr T cp(T& t) noexcept { return t; } 644 template<typename T> constexpr T cp(const T& t) noexcept { return t; } 645 // Useful to force a copy, particularly to pass into a function that expects T&&. 646 647 template <typename T, typename U, bool takeT, bool uOK = true> struct ChooseType_; 648 template <typename T, typename U> struct ChooseType_<T, U, true, true> { typedef T Type; }; 649 template <typename T, typename U> struct ChooseType_<T, U, true, false> { typedef T Type; }; 650 template <typename T, typename U> struct ChooseType_<T, U, false, true> { typedef U Type; }; 651 652 template <typename T, typename U> 653 using WiderType = typename ChooseType_<T, U, sizeof(T) >= sizeof(U)>::Type; 654 655 template <typename T, typename U> 656 inline constexpr auto min(T&& a, U&& b) -> WiderType<Decay<T>, Decay<U>> { 657 return a < b ? WiderType<Decay<T>, Decay<U>>(a) : WiderType<Decay<T>, Decay<U>>(b); 658 } 659 660 template <typename T, typename U> 661 inline constexpr auto max(T&& a, U&& b) -> WiderType<Decay<T>, Decay<U>> { 662 return a > b ? WiderType<Decay<T>, Decay<U>>(a) : WiderType<Decay<T>, Decay<U>>(b); 663 } 664 665 template <typename T, size_t s> 666 inline constexpr size_t size(T (&arr)[s]) { return s; } 667 template <typename T> 668 inline constexpr size_t size(T&& arr) { return arr.size(); } 669 // Returns the size of the parameter, whether the parameter is a regular C array or a container 670 // with a `.size()` method. 671 672 class MaxValue_ { 673 private: 674 template <typename T> 675 inline constexpr T maxSigned() const { 676 return (1ull << (sizeof(T) * 8 - 1)) - 1; 677 } 678 template <typename T> 679 inline constexpr T maxUnsigned() const { 680 return ~static_cast<T>(0u); 681 } 682 683 public: 684 #define _kJ_HANDLE_TYPE(T) \ 685 inline constexpr operator signed T() const { return MaxValue_::maxSigned < signed T>(); } \ 686 inline constexpr operator unsigned T() const { return MaxValue_::maxUnsigned<unsigned T>(); } 687 _kJ_HANDLE_TYPE(char) 688 _kJ_HANDLE_TYPE(short) 689 _kJ_HANDLE_TYPE(int) 690 _kJ_HANDLE_TYPE(long) 691 _kJ_HANDLE_TYPE(long long) 692 #undef _kJ_HANDLE_TYPE 693 694 inline constexpr operator char() const { 695 // `char` is different from both `signed char` and `unsigned char`, and may be signed or 696 // unsigned on different platforms. Ugh. 697 return char(-1) < 0 ? MaxValue_::maxSigned<char>() 698 : MaxValue_::maxUnsigned<char>(); 699 } 700 }; 701 702 class MinValue_ { 703 private: 704 template <typename T> 705 inline constexpr T minSigned() const { 706 return 1ull << (sizeof(T) * 8 - 1); 707 } 708 template <typename T> 709 inline constexpr T minUnsigned() const { 710 return 0u; 711 } 712 713 public: 714 #define _kJ_HANDLE_TYPE(T) \ 715 inline constexpr operator signed T() const { return MinValue_::minSigned < signed T>(); } \ 716 inline constexpr operator unsigned T() const { return MinValue_::minUnsigned<unsigned T>(); } 717 _kJ_HANDLE_TYPE(char) 718 _kJ_HANDLE_TYPE(short) 719 _kJ_HANDLE_TYPE(int) 720 _kJ_HANDLE_TYPE(long) 721 _kJ_HANDLE_TYPE(long long) 722 #undef _kJ_HANDLE_TYPE 723 724 inline constexpr operator char() const { 725 // `char` is different from both `signed char` and `unsigned char`, and may be signed or 726 // unsigned on different platforms. Ugh. 727 return char(-1) < 0 ? MinValue_::minSigned<char>() 728 : MinValue_::minUnsigned<char>(); 729 } 730 }; 731 732 static KJ_CONSTEXPR(const) MaxValue_ maxValue = MaxValue_(); 733 // A special constant which, when cast to an integer type, takes on the maximum possible value of 734 // that type. This is useful to use as e.g. a parameter to a function because it will be robust 735 // in the face of changes to the parameter's type. 736 // 737 // `char` is not supported, but `signed char` and `unsigned char` are. 738 739 static KJ_CONSTEXPR(const) MinValue_ minValue = MinValue_(); 740 // A special constant which, when cast to an integer type, takes on the minimum possible value 741 // of that type. This is useful to use as e.g. a parameter to a function because it will be robust 742 // in the face of changes to the parameter's type. 743 // 744 // `char` is not supported, but `signed char` and `unsigned char` are. 745 746 template <typename T> 747 inline bool operator==(T t, MaxValue_) { return t == Decay<T>(maxValue); } 748 template <typename T> 749 inline bool operator==(T t, MinValue_) { return t == Decay<T>(minValue); } 750 751 template <uint bits> 752 inline constexpr unsigned long long maxValueForBits() { 753 // Get the maximum integer representable in the given number of bits. 754 755 // 1ull << 64 is unfortunately undefined. 756 return (bits == 64 ? 0 : (1ull << bits)) - 1; 757 } 758 759 struct ThrowOverflow { 760 // Functor which throws an exception complaining about integer overflow. Usually this is used 761 // with the interfaces in units.h, but is defined here because Cap'n Proto wants to avoid 762 // including units.h when not using CAPNP_DEBUG_TYPES. 763 [[noreturn]] void operator()() const; 764 }; 765 766 #if __GNUC__ || __clang__ || _MSC_VER 767 inline constexpr float inf() { return __builtin_huge_valf(); } 768 inline constexpr float nan() { return __builtin_nanf(""); } 769 770 #else 771 #error "Not sure how to support your compiler." 772 #endif 773 774 inline constexpr bool isNaN(float f) { return f != f; } 775 inline constexpr bool isNaN(double f) { return f != f; } 776 777 inline int popCount(unsigned int x) { 778 #if defined(_MSC_VER) && !defined(__clang__) 779 return __popcnt(x); 780 // Note: __popcnt returns unsigned int, but the value is clearly guaranteed to fit into an int 781 #else 782 return __builtin_popcount(x); 783 #endif 784 } 785 786 // ======================================================================================= 787 // Useful fake containers 788 789 template <typename T> 790 class Range { 791 public: 792 inline constexpr Range(const T& begin, const T& end): begin_(begin), end_(end) {} 793 inline explicit constexpr Range(const T& end): begin_(0), end_(end) {} 794 795 class Iterator { 796 public: 797 Iterator() = default; 798 inline Iterator(const T& value): value(value) {} 799 800 inline const T& operator* () const { return value; } 801 inline const T& operator[](size_t index) const { return value + index; } 802 inline Iterator& operator++() { ++value; return *this; } 803 inline Iterator operator++(int) { return Iterator(value++); } 804 inline Iterator& operator--() { --value; return *this; } 805 inline Iterator operator--(int) { return Iterator(value--); } 806 inline Iterator& operator+=(ptrdiff_t amount) { value += amount; return *this; } 807 inline Iterator& operator-=(ptrdiff_t amount) { value -= amount; return *this; } 808 inline Iterator operator+ (ptrdiff_t amount) const { return Iterator(value + amount); } 809 inline Iterator operator- (ptrdiff_t amount) const { return Iterator(value - amount); } 810 inline ptrdiff_t operator- (const Iterator& other) const { return value - other.value; } 811 812 inline bool operator==(const Iterator& other) const { return value == other.value; } 813 inline bool operator!=(const Iterator& other) const { return value != other.value; } 814 inline bool operator<=(const Iterator& other) const { return value <= other.value; } 815 inline bool operator>=(const Iterator& other) const { return value >= other.value; } 816 inline bool operator< (const Iterator& other) const { return value < other.value; } 817 inline bool operator> (const Iterator& other) const { return value > other.value; } 818 819 private: 820 T value; 821 }; 822 823 inline Iterator begin() const { return Iterator(begin_); } 824 inline Iterator end() const { return Iterator(end_); } 825 826 inline auto size() const -> decltype(instance<T>() - instance<T>()) { return end_ - begin_; } 827 828 private: 829 T begin_; 830 T end_; 831 }; 832 833 template <typename T, typename U> 834 inline constexpr Range<WiderType<Decay<T>, Decay<U>>> range(T begin, U end) { 835 return Range<WiderType<Decay<T>, Decay<U>>>(begin, end); 836 } 837 838 template <typename T> 839 inline constexpr Range<Decay<T>> range(T begin, T end) { return Range<Decay<T>>(begin, end); } 840 // Returns a fake iterable container containing all values of T from `begin` (inclusive) to `end` 841 // (exclusive). Example: 842 // 843 // // Prints 1, 2, 3, 4, 5, 6, 7, 8, 9. 844 // for (int i: kj::range(1, 10)) { print(i); } 845 846 template <typename T> 847 inline constexpr Range<Decay<T>> zeroTo(T end) { return Range<Decay<T>>(end); } 848 // Returns a fake iterable container containing all values of T from zero (inclusive) to `end` 849 // (exclusive). Example: 850 // 851 // // Prints 0, 1, 2, 3, 4, 5, 6, 7, 8, 9. 852 // for (int i: kj::zeroTo(10)) { print(i); } 853 854 template <typename T> 855 inline constexpr Range<size_t> indices(T&& container) { 856 // Shortcut for iterating over the indices of a container: 857 // 858 // for (size_t i: kj::indices(myArray)) { handle(myArray[i]); } 859 860 return range<size_t>(0, kj::size(container)); 861 } 862 863 template <typename T> 864 class Repeat { 865 public: 866 inline constexpr Repeat(const T& value, size_t count): value(value), count(count) {} 867 868 class Iterator { 869 public: 870 Iterator() = default; 871 inline Iterator(const T& value, size_t index): value(value), index(index) {} 872 873 inline const T& operator* () const { return value; } 874 inline const T& operator[](ptrdiff_t index) const { return value; } 875 inline Iterator& operator++() { ++index; return *this; } 876 inline Iterator operator++(int) { return Iterator(value, index++); } 877 inline Iterator& operator--() { --index; return *this; } 878 inline Iterator operator--(int) { return Iterator(value, index--); } 879 inline Iterator& operator+=(ptrdiff_t amount) { index += amount; return *this; } 880 inline Iterator& operator-=(ptrdiff_t amount) { index -= amount; return *this; } 881 inline Iterator operator+ (ptrdiff_t amount) const { return Iterator(value, index + amount); } 882 inline Iterator operator- (ptrdiff_t amount) const { return Iterator(value, index - amount); } 883 inline ptrdiff_t operator- (const Iterator& other) const { return index - other.index; } 884 885 inline bool operator==(const Iterator& other) const { return index == other.index; } 886 inline bool operator!=(const Iterator& other) const { return index != other.index; } 887 inline bool operator<=(const Iterator& other) const { return index <= other.index; } 888 inline bool operator>=(const Iterator& other) const { return index >= other.index; } 889 inline bool operator< (const Iterator& other) const { return index < other.index; } 890 inline bool operator> (const Iterator& other) const { return index > other.index; } 891 892 private: 893 T value; 894 size_t index; 895 }; 896 897 inline Iterator begin() const { return Iterator(value, 0); } 898 inline Iterator end() const { return Iterator(value, count); } 899 900 inline size_t size() const { return count; } 901 inline const T& operator[](ptrdiff_t) const { return value; } 902 903 private: 904 T value; 905 size_t count; 906 }; 907 908 template <typename T> 909 inline constexpr Repeat<Decay<T>> repeat(T&& value, size_t count) { 910 // Returns a fake iterable which contains `count` repeats of `value`. Useful for e.g. creating 911 // a bunch of spaces: `kj::repeat(' ', indent * 2)` 912 913 return Repeat<Decay<T>>(value, count); 914 } 915 916 template <typename Inner, class Mapping> 917 class MappedIterator: private Mapping { 918 // An iterator that wraps some other iterator and maps the values through a mapping function. 919 // The type `Mapping` must define a method `map()` which performs this mapping. 920 921 public: 922 template <typename... Params> 923 MappedIterator(Inner inner, Params&&... params) 924 : Mapping(kj::fwd<Params>(params)...), inner(inner) {} 925 926 inline auto operator->() const { return &Mapping::map(*inner); } 927 inline decltype(auto) operator* () const { return Mapping::map(*inner); } 928 inline decltype(auto) operator[](size_t index) const { return Mapping::map(inner[index]); } 929 inline MappedIterator& operator++() { ++inner; return *this; } 930 inline MappedIterator operator++(int) { return MappedIterator(inner++, *this); } 931 inline MappedIterator& operator--() { --inner; return *this; } 932 inline MappedIterator operator--(int) { return MappedIterator(inner--, *this); } 933 inline MappedIterator& operator+=(ptrdiff_t amount) { inner += amount; return *this; } 934 inline MappedIterator& operator-=(ptrdiff_t amount) { inner -= amount; return *this; } 935 inline MappedIterator operator+ (ptrdiff_t amount) const { 936 return MappedIterator(inner + amount, *this); 937 } 938 inline MappedIterator operator- (ptrdiff_t amount) const { 939 return MappedIterator(inner - amount, *this); 940 } 941 inline ptrdiff_t operator- (const MappedIterator& other) const { return inner - other.inner; } 942 943 inline bool operator==(const MappedIterator& other) const { return inner == other.inner; } 944 inline bool operator!=(const MappedIterator& other) const { return inner != other.inner; } 945 inline bool operator<=(const MappedIterator& other) const { return inner <= other.inner; } 946 inline bool operator>=(const MappedIterator& other) const { return inner >= other.inner; } 947 inline bool operator< (const MappedIterator& other) const { return inner < other.inner; } 948 inline bool operator> (const MappedIterator& other) const { return inner > other.inner; } 949 950 private: 951 Inner inner; 952 }; 953 954 template <typename Inner, typename Mapping> 955 class MappedIterable: private Mapping { 956 // An iterable that wraps some other iterable and maps the values through a mapping function. 957 // The type `Mapping` must define a method `map()` which performs this mapping. 958 959 public: 960 template <typename... Params> 961 MappedIterable(Inner inner, Params&&... params) 962 : Mapping(kj::fwd<Params>(params)...), inner(inner) {} 963 964 typedef Decay<decltype(instance<Inner>().begin())> InnerIterator; 965 typedef MappedIterator<InnerIterator, Mapping> Iterator; 966 typedef Decay<decltype(instance<const Inner>().begin())> InnerConstIterator; 967 typedef MappedIterator<InnerConstIterator, Mapping> ConstIterator; 968 969 inline Iterator begin() { return { inner.begin(), (Mapping&)*this }; } 970 inline Iterator end() { return { inner.end(), (Mapping&)*this }; } 971 inline ConstIterator begin() const { return { inner.begin(), (const Mapping&)*this }; } 972 inline ConstIterator end() const { return { inner.end(), (const Mapping&)*this }; } 973 974 private: 975 Inner inner; 976 }; 977 978 // ======================================================================================= 979 // Manually invoking constructors and destructors 980 // 981 // ctor(x, ...) and dtor(x) invoke x's constructor or destructor, respectively. 982 983 // We want placement new, but we don't want to #include <new>. operator new cannot be defined in 984 // a namespace, and defining it globally conflicts with the definition in <new>. So we have to 985 // define a dummy type and an operator new that uses it. 986 987 namespace _ { // private 988 struct PlacementNew {}; 989 } // namespace _ (private) 990 } // namespace kj 991 992 inline void* operator new(size_t, kj::_::PlacementNew, void* __p) noexcept { 993 return __p; 994 } 995 996 inline void operator delete(void*, kj::_::PlacementNew, void* __p) noexcept {} 997 998 namespace kj { 999 1000 template <typename T, typename... Params> 1001 inline void ctor(T& location, Params&&... params) { 1002 new (_::PlacementNew(), &location) T(kj::fwd<Params>(params)...); 1003 } 1004 1005 template <typename T> 1006 inline void dtor(T& location) { 1007 location.~T(); 1008 } 1009 1010 // ======================================================================================= 1011 // Maybe 1012 // 1013 // Use in cases where you want to indicate that a value may be null. Using Maybe<T&> instead of T* 1014 // forces the caller to handle the null case in order to satisfy the compiler, thus reliably 1015 // preventing null pointer dereferences at runtime. 1016 // 1017 // Maybe<T> can be implicitly constructed from T and from nullptr. Additionally, it can be 1018 // implicitly constructed from T*, in which case the pointer is checked for nullness at runtime. 1019 // To read the value of a Maybe<T>, do: 1020 // 1021 // KJ_IF_MAYBE(value, someFuncReturningMaybe()) { 1022 // doSomething(*value); 1023 // } else { 1024 // maybeWasNull(); 1025 // } 1026 // 1027 // KJ_IF_MAYBE's first parameter is a variable name which will be defined within the following 1028 // block. The variable will behave like a (guaranteed non-null) pointer to the Maybe's value, 1029 // though it may or may not actually be a pointer. 1030 // 1031 // Note that Maybe<T&> actually just wraps a pointer, whereas Maybe<T> wraps a T and a boolean 1032 // indicating nullness. 1033 1034 template <typename T> 1035 class Maybe; 1036 1037 namespace _ { // private 1038 1039 template <typename T> 1040 class NullableValue { 1041 // Class whose interface behaves much like T*, but actually contains an instance of T and a 1042 // boolean flag indicating nullness. 1043 1044 public: 1045 inline NullableValue(NullableValue&& other) 1046 : isSet(other.isSet) { 1047 if (isSet) { 1048 ctor(value, kj::mv(other.value)); 1049 } 1050 } 1051 inline NullableValue(const NullableValue& other) 1052 : isSet(other.isSet) { 1053 if (isSet) { 1054 ctor(value, other.value); 1055 } 1056 } 1057 inline NullableValue(NullableValue& other) 1058 : isSet(other.isSet) { 1059 if (isSet) { 1060 ctor(value, other.value); 1061 } 1062 } 1063 inline ~NullableValue() 1064 #if _MSC_VER && !defined(__clang__) 1065 // TODO(msvc): MSVC has a hard time with noexcept specifier expressions that are more complex 1066 // than `true` or `false`. We had a workaround for VS2015, but VS2017 regressed. 1067 noexcept(false) 1068 #else 1069 noexcept(noexcept(instance<T&>().~T())) 1070 #endif 1071 { 1072 if (isSet) { 1073 dtor(value); 1074 } 1075 } 1076 1077 inline T& operator*() & { return value; } 1078 inline const T& operator*() const & { return value; } 1079 inline T&& operator*() && { return kj::mv(value); } 1080 inline const T&& operator*() const && { return kj::mv(value); } 1081 inline T* operator->() { return &value; } 1082 inline const T* operator->() const { return &value; } 1083 inline operator T*() { return isSet ? &value : nullptr; } 1084 inline operator const T*() const { return isSet ? &value : nullptr; } 1085 1086 template <typename... Params> 1087 inline T& emplace(Params&&... params) { 1088 if (isSet) { 1089 isSet = false; 1090 dtor(value); 1091 } 1092 ctor(value, kj::fwd<Params>(params)...); 1093 isSet = true; 1094 return value; 1095 } 1096 1097 inline NullableValue(): isSet(false) {} 1098 inline NullableValue(T&& t) 1099 : isSet(true) { 1100 ctor(value, kj::mv(t)); 1101 } 1102 inline NullableValue(T& t) 1103 : isSet(true) { 1104 ctor(value, t); 1105 } 1106 inline NullableValue(const T& t) 1107 : isSet(true) { 1108 ctor(value, t); 1109 } 1110 template <typename U> 1111 inline NullableValue(NullableValue<U>&& other) 1112 : isSet(other.isSet) { 1113 if (isSet) { 1114 ctor(value, kj::mv(other.value)); 1115 } 1116 } 1117 template <typename U> 1118 inline NullableValue(const NullableValue<U>& other) 1119 : isSet(other.isSet) { 1120 if (isSet) { 1121 ctor(value, other.value); 1122 } 1123 } 1124 template <typename U> 1125 inline NullableValue(const NullableValue<U&>& other) 1126 : isSet(other.isSet) { 1127 if (isSet) { 1128 ctor(value, *other.ptr); 1129 } 1130 } 1131 inline NullableValue(decltype(nullptr)): isSet(false) {} 1132 1133 inline NullableValue& operator=(NullableValue&& other) { 1134 if (&other != this) { 1135 // Careful about throwing destructors/constructors here. 1136 if (isSet) { 1137 isSet = false; 1138 dtor(value); 1139 } 1140 if (other.isSet) { 1141 ctor(value, kj::mv(other.value)); 1142 isSet = true; 1143 } 1144 } 1145 return *this; 1146 } 1147 1148 inline NullableValue& operator=(NullableValue& other) { 1149 if (&other != this) { 1150 // Careful about throwing destructors/constructors here. 1151 if (isSet) { 1152 isSet = false; 1153 dtor(value); 1154 } 1155 if (other.isSet) { 1156 ctor(value, other.value); 1157 isSet = true; 1158 } 1159 } 1160 return *this; 1161 } 1162 1163 inline NullableValue& operator=(const NullableValue& other) { 1164 if (&other != this) { 1165 // Careful about throwing destructors/constructors here. 1166 if (isSet) { 1167 isSet = false; 1168 dtor(value); 1169 } 1170 if (other.isSet) { 1171 ctor(value, other.value); 1172 isSet = true; 1173 } 1174 } 1175 return *this; 1176 } 1177 1178 inline NullableValue& operator=(T&& other) { emplace(kj::mv(other)); return *this; } 1179 inline NullableValue& operator=(T& other) { emplace(other); return *this; } 1180 inline NullableValue& operator=(const T& other) { emplace(other); return *this; } 1181 template <typename U> 1182 inline NullableValue& operator=(NullableValue<U>&& other) { 1183 if (other.isSet) { 1184 emplace(kj::mv(other.value)); 1185 } else { 1186 *this = nullptr; 1187 } 1188 return *this; 1189 } 1190 template <typename U> 1191 inline NullableValue& operator=(const NullableValue<U>& other) { 1192 if (other.isSet) { 1193 emplace(other.value); 1194 } else { 1195 *this = nullptr; 1196 } 1197 return *this; 1198 } 1199 template <typename U> 1200 inline NullableValue& operator=(const NullableValue<U&>& other) { 1201 if (other.isSet) { 1202 emplace(other.value); 1203 } else { 1204 *this = nullptr; 1205 } 1206 return *this; 1207 } 1208 inline NullableValue& operator=(decltype(nullptr)) { 1209 if (isSet) { 1210 isSet = false; 1211 dtor(value); 1212 } 1213 return *this; 1214 } 1215 1216 inline bool operator==(decltype(nullptr)) const { return !isSet; } 1217 inline bool operator!=(decltype(nullptr)) const { return isSet; } 1218 1219 NullableValue(const T* t) = delete; 1220 NullableValue& operator=(const T* other) = delete; 1221 // We used to permit assigning a Maybe<T> directly from a T*, and the assignment would check for 1222 // nullness. This turned out never to be useful, and sometimes to be dangerous. 1223 1224 private: 1225 bool isSet; 1226 1227 #if _MSC_VER && !defined(__clang__) 1228 #pragma warning(push) 1229 #pragma warning(disable: 4624) 1230 // Warns that the anonymous union has a deleted destructor when T is non-trivial. This warning 1231 // seems broken. 1232 #endif 1233 1234 union { 1235 T value; 1236 }; 1237 1238 #if _MSC_VER && !defined(__clang__) 1239 #pragma warning(pop) 1240 #endif 1241 1242 friend class kj::Maybe<T>; 1243 template <typename U> 1244 friend NullableValue<U>&& readMaybe(Maybe<U>&& maybe); 1245 }; 1246 1247 template <typename T> 1248 inline NullableValue<T>&& readMaybe(Maybe<T>&& maybe) { return kj::mv(maybe.ptr); } 1249 template <typename T> 1250 inline T* readMaybe(Maybe<T>& maybe) { return maybe.ptr; } 1251 template <typename T> 1252 inline const T* readMaybe(const Maybe<T>& maybe) { return maybe.ptr; } 1253 template <typename T> 1254 inline T* readMaybe(Maybe<T&>&& maybe) { return maybe.ptr; } 1255 template <typename T> 1256 inline T* readMaybe(const Maybe<T&>& maybe) { return maybe.ptr; } 1257 1258 template <typename T> 1259 inline T* readMaybe(T* ptr) { return ptr; } 1260 // Allow KJ_IF_MAYBE to work on regular pointers. 1261 1262 } // namespace _ (private) 1263 1264 #define KJ_IF_MAYBE(name, exp) if (auto name = ::kj::_::readMaybe(exp)) 1265 1266 #if __GNUC__ 1267 // These two macros provide a friendly syntax to extract the value of a Maybe or return early. 1268 // 1269 // Use KJ_UNWRAP_OR_RETURN if you just want to return a simple value when the Maybe is null: 1270 // 1271 // int foo(Maybe<int> maybe) { 1272 // int value = KJ_UNWRAP_OR_RETURN(maybe, -1); 1273 // // ... use value ... 1274 // } 1275 // 1276 // For functions returning void, omit the second parameter to KJ_UNWRAP_OR_RETURN: 1277 // 1278 // void foo(Maybe<int> maybe) { 1279 // int value = KJ_UNWRAP_OR_RETURN(maybe); 1280 // // ... use value ... 1281 // } 1282 // 1283 // Use KJ_UNWRAP_OR if you want to execute a block with multiple statements. 1284 // 1285 // int foo(Maybe<int> maybe) { 1286 // int value = KJ_UNWRAP_OR(maybe, { 1287 // KJ_LOG(ERROR, "problem!!!"); 1288 // return -1; 1289 // }); 1290 // // ... use value ... 1291 // } 1292 // 1293 // The block MUST return at the end or you will get a compiler error 1294 // 1295 // Unfortunately, these macros seem impossible to express without using GCC's non-standard 1296 // "statement expressions" extension. IIFEs don't do the trick here because a lambda cannot 1297 // return out of the parent scope. These macros should therefore only be used in projects that 1298 // target GCC or GCC-compatible compilers. 1299 1300 #define KJ_UNWRAP_OR_RETURN(value, ...) \ 1301 (*({ \ 1302 auto _kj_result = ::kj::_::readMaybe(value); \ 1303 if (!_kj_result) { \ 1304 return __VA_ARGS__; \ 1305 } \ 1306 kj::mv(_kj_result); \ 1307 })) 1308 1309 #define KJ_UNWRAP_OR(value, block) \ 1310 (*({ \ 1311 auto _kj_result = ::kj::_::readMaybe(value); \ 1312 if (!_kj_result) { \ 1313 block; \ 1314 asm("KJ_UNWRAP_OR_block_is_missing_return_statement\n"); \ 1315 } \ 1316 kj::mv(_kj_result); \ 1317 })) 1318 #endif 1319 1320 template <typename T> 1321 class Maybe { 1322 // A T, or nullptr. 1323 1324 // IF YOU CHANGE THIS CLASS: Note that there is a specialization of it in memory.h. 1325 1326 public: 1327 Maybe(): ptr(nullptr) {} 1328 Maybe(T&& t): ptr(kj::mv(t)) {} 1329 Maybe(T& t): ptr(t) {} 1330 Maybe(const T& t): ptr(t) {} 1331 Maybe(Maybe&& other): ptr(kj::mv(other.ptr)) { other = nullptr; } 1332 Maybe(const Maybe& other): ptr(other.ptr) {} 1333 Maybe(Maybe& other): ptr(other.ptr) {} 1334 1335 template <typename U> 1336 Maybe(Maybe<U>&& other) { 1337 KJ_IF_MAYBE(val, kj::mv(other)) { 1338 ptr.emplace(kj::mv(*val)); 1339 other = nullptr; 1340 } 1341 } 1342 template <typename U> 1343 Maybe(Maybe<U&>&& other) { 1344 KJ_IF_MAYBE(val, other) { 1345 ptr.emplace(*val); 1346 other = nullptr; 1347 } 1348 } 1349 template <typename U> 1350 Maybe(const Maybe<U>& other) { 1351 KJ_IF_MAYBE(val, other) { 1352 ptr.emplace(*val); 1353 } 1354 } 1355 1356 Maybe(decltype(nullptr)): ptr(nullptr) {} 1357 1358 template <typename... Params> 1359 inline T& emplace(Params&&... params) { 1360 // Replace this Maybe's content with a new value constructed by passing the given parameters to 1361 // T's constructor. This can be used to initialize a Maybe without copying or even moving a T. 1362 // Returns a reference to the newly-constructed value. 1363 1364 return ptr.emplace(kj::fwd<Params>(params)...); 1365 } 1366 1367 inline Maybe& operator=(T&& other) { ptr = kj::mv(other); return *this; } 1368 inline Maybe& operator=(T& other) { ptr = other; return *this; } 1369 inline Maybe& operator=(const T& other) { ptr = other; return *this; } 1370 1371 inline Maybe& operator=(Maybe&& other) { ptr = kj::mv(other.ptr); other = nullptr; return *this; } 1372 inline Maybe& operator=(Maybe& other) { ptr = other.ptr; return *this; } 1373 inline Maybe& operator=(const Maybe& other) { ptr = other.ptr; return *this; } 1374 1375 template <typename U> 1376 Maybe& operator=(Maybe<U>&& other) { 1377 KJ_IF_MAYBE(val, kj::mv(other)) { 1378 ptr.emplace(kj::mv(*val)); 1379 other = nullptr; 1380 } else { 1381 ptr = nullptr; 1382 } 1383 return *this; 1384 } 1385 template <typename U> 1386 Maybe& operator=(const Maybe<U>& other) { 1387 KJ_IF_MAYBE(val, other) { 1388 ptr.emplace(*val); 1389 } else { 1390 ptr = nullptr; 1391 } 1392 return *this; 1393 } 1394 1395 inline Maybe& operator=(decltype(nullptr)) { ptr = nullptr; return *this; } 1396 1397 inline bool operator==(decltype(nullptr)) const { return ptr == nullptr; } 1398 inline bool operator!=(decltype(nullptr)) const { return ptr != nullptr; } 1399 1400 inline bool operator==(const Maybe<T>& other) const { 1401 if (ptr == nullptr) { 1402 return other == nullptr; 1403 } else { 1404 return other.ptr != nullptr && *ptr == *other.ptr; 1405 } 1406 } 1407 inline bool operator!=(const Maybe<T>& other) const { return !(*this == other); } 1408 1409 Maybe(const T* t) = delete; 1410 Maybe& operator=(const T* other) = delete; 1411 // We used to permit assigning a Maybe<T> directly from a T*, and the assignment would check for 1412 // nullness. This turned out never to be useful, and sometimes to be dangerous. 1413 1414 T& orDefault(T& defaultValue) & { 1415 if (ptr == nullptr) { 1416 return defaultValue; 1417 } else { 1418 return *ptr; 1419 } 1420 } 1421 const T& orDefault(const T& defaultValue) const & { 1422 if (ptr == nullptr) { 1423 return defaultValue; 1424 } else { 1425 return *ptr; 1426 } 1427 } 1428 T&& orDefault(T&& defaultValue) && { 1429 if (ptr == nullptr) { 1430 return kj::mv(defaultValue); 1431 } else { 1432 return kj::mv(*ptr); 1433 } 1434 } 1435 const T&& orDefault(const T&& defaultValue) const && { 1436 if (ptr == nullptr) { 1437 return kj::mv(defaultValue); 1438 } else { 1439 return kj::mv(*ptr); 1440 } 1441 } 1442 1443 template <typename F, 1444 typename Result = decltype(instance<bool>() ? instance<T&>() : instance<F>()())> 1445 Result orDefault(F&& lazyDefaultValue) & { 1446 if (ptr == nullptr) { 1447 return lazyDefaultValue(); 1448 } else { 1449 return *ptr; 1450 } 1451 } 1452 1453 template <typename F, 1454 typename Result = decltype(instance<bool>() ? instance<const T&>() : instance<F>()())> 1455 Result orDefault(F&& lazyDefaultValue) const & { 1456 if (ptr == nullptr) { 1457 return lazyDefaultValue(); 1458 } else { 1459 return *ptr; 1460 } 1461 } 1462 1463 template <typename F, 1464 typename Result = decltype(instance<bool>() ? instance<T&&>() : instance<F>()())> 1465 Result orDefault(F&& lazyDefaultValue) && { 1466 if (ptr == nullptr) { 1467 return lazyDefaultValue(); 1468 } else { 1469 return kj::mv(*ptr); 1470 } 1471 } 1472 1473 template <typename F, 1474 typename Result = decltype(instance<bool>() ? instance<const T&&>() : instance<F>()())> 1475 Result orDefault(F&& lazyDefaultValue) const && { 1476 if (ptr == nullptr) { 1477 return lazyDefaultValue(); 1478 } else { 1479 return kj::mv(*ptr); 1480 } 1481 } 1482 1483 template <typename Func> 1484 auto map(Func&& f) & -> Maybe<decltype(f(instance<T&>()))> { 1485 if (ptr == nullptr) { 1486 return nullptr; 1487 } else { 1488 return f(*ptr); 1489 } 1490 } 1491 1492 template <typename Func> 1493 auto map(Func&& f) const & -> Maybe<decltype(f(instance<const T&>()))> { 1494 if (ptr == nullptr) { 1495 return nullptr; 1496 } else { 1497 return f(*ptr); 1498 } 1499 } 1500 1501 template <typename Func> 1502 auto map(Func&& f) && -> Maybe<decltype(f(instance<T&&>()))> { 1503 if (ptr == nullptr) { 1504 return nullptr; 1505 } else { 1506 return f(kj::mv(*ptr)); 1507 } 1508 } 1509 1510 template <typename Func> 1511 auto map(Func&& f) const && -> Maybe<decltype(f(instance<const T&&>()))> { 1512 if (ptr == nullptr) { 1513 return nullptr; 1514 } else { 1515 return f(kj::mv(*ptr)); 1516 } 1517 } 1518 1519 private: 1520 _::NullableValue<T> ptr; 1521 1522 template <typename U> 1523 friend class Maybe; 1524 template <typename U> 1525 friend _::NullableValue<U>&& _::readMaybe(Maybe<U>&& maybe); 1526 template <typename U> 1527 friend U* _::readMaybe(Maybe<U>& maybe); 1528 template <typename U> 1529 friend const U* _::readMaybe(const Maybe<U>& maybe); 1530 }; 1531 1532 template <typename T> 1533 class Maybe<T&> { 1534 public: 1535 constexpr Maybe(): ptr(nullptr) {} 1536 constexpr Maybe(T& t): ptr(&t) {} 1537 constexpr Maybe(T* t): ptr(t) {} 1538 1539 inline constexpr Maybe(PropagateConst<T, Maybe>& other): ptr(other.ptr) {} 1540 // Allow const copy only if `T` itself is const. Otherwise allow only non-const copy, to 1541 // protect transitive constness. Clang is happy for this constructor to be declared `= default` 1542 // since, after evaluation of `PropagateConst`, it does end up being a default-able constructor. 1543 // But, GCC and MSVC both complain about that, claiming this constructor cannot be declared 1544 // default. I don't know who is correct, but whatever, we'll write out an implementation, fine. 1545 // 1546 // Note that we can't solve this by inheriting DisallowConstCopyIfNotConst<T> because we want 1547 // to override the move constructor, and if we override the move constructor then we must define 1548 // the copy constructor here. 1549 1550 inline constexpr Maybe(Maybe&& other): ptr(other.ptr) { other.ptr = nullptr; } 1551 1552 template <typename U> 1553 inline constexpr Maybe(Maybe<U&>& other): ptr(other.ptr) {} 1554 template <typename U> 1555 inline constexpr Maybe(const Maybe<U&>& other): ptr(const_cast<const U*>(other.ptr)) {} 1556 template <typename U> 1557 inline constexpr Maybe(Maybe<U&>&& other): ptr(other.ptr) { other.ptr = nullptr; } 1558 template <typename U> 1559 inline constexpr Maybe(const Maybe<U&>&& other) = delete; 1560 template <typename U, typename = EnableIf<canConvert<U*, T*>()>> 1561 constexpr Maybe(Maybe<U>& other): ptr(other.ptr.operator U*()) {} 1562 template <typename U, typename = EnableIf<canConvert<const U*, T*>()>> 1563 constexpr Maybe(const Maybe<U>& other): ptr(other.ptr.operator const U*()) {} 1564 inline constexpr Maybe(decltype(nullptr)): ptr(nullptr) {} 1565 1566 inline Maybe& operator=(T& other) { ptr = &other; return *this; } 1567 inline Maybe& operator=(T* other) { ptr = other; return *this; } 1568 inline Maybe& operator=(PropagateConst<T, Maybe>& other) { ptr = other.ptr; return *this; } 1569 inline Maybe& operator=(Maybe&& other) { ptr = other.ptr; other.ptr = nullptr; return *this; } 1570 template <typename U> 1571 inline Maybe& operator=(Maybe<U&>& other) { ptr = other.ptr; return *this; } 1572 template <typename U> 1573 inline Maybe& operator=(const Maybe<const U&>& other) { ptr = other.ptr; return *this; } 1574 template <typename U> 1575 inline Maybe& operator=(Maybe<U&>&& other) { ptr = other.ptr; other.ptr = nullptr; return *this; } 1576 template <typename U> 1577 inline Maybe& operator=(const Maybe<U&>&& other) = delete; 1578 1579 inline bool operator==(decltype(nullptr)) const { return ptr == nullptr; } 1580 inline bool operator!=(decltype(nullptr)) const { return ptr != nullptr; } 1581 1582 T& orDefault(T& defaultValue) { 1583 if (ptr == nullptr) { 1584 return defaultValue; 1585 } else { 1586 return *ptr; 1587 } 1588 } 1589 const T& orDefault(const T& defaultValue) const { 1590 if (ptr == nullptr) { 1591 return defaultValue; 1592 } else { 1593 return *ptr; 1594 } 1595 } 1596 1597 template <typename Func> 1598 auto map(Func&& f) -> Maybe<decltype(f(instance<T&>()))> { 1599 if (ptr == nullptr) { 1600 return nullptr; 1601 } else { 1602 return f(*ptr); 1603 } 1604 } 1605 1606 template <typename Func> 1607 auto map(Func&& f) const -> Maybe<decltype(f(instance<const T&>()))> { 1608 if (ptr == nullptr) { 1609 return nullptr; 1610 } else { 1611 const T& ref = *ptr; 1612 return f(ref); 1613 } 1614 } 1615 1616 private: 1617 T* ptr; 1618 1619 template <typename U> 1620 friend class Maybe; 1621 template <typename U> 1622 friend U* _::readMaybe(Maybe<U&>&& maybe); 1623 template <typename U> 1624 friend U* _::readMaybe(const Maybe<U&>& maybe); 1625 }; 1626 1627 // ======================================================================================= 1628 // ArrayPtr 1629 // 1630 // So common that we put it in common.h rather than array.h. 1631 1632 template <typename T> 1633 class Array; 1634 1635 template <typename T> 1636 class ArrayPtr: public DisallowConstCopyIfNotConst<T> { 1637 // A pointer to an array. Includes a size. Like any pointer, it doesn't own the target data, 1638 // and passing by value only copies the pointer, not the target. 1639 1640 public: 1641 inline constexpr ArrayPtr(): ptr(nullptr), size_(0) {} 1642 inline constexpr ArrayPtr(decltype(nullptr)): ptr(nullptr), size_(0) {} 1643 inline constexpr ArrayPtr(T* ptr KJ_LIFETIMEBOUND, size_t size): ptr(ptr), size_(size) {} 1644 inline constexpr ArrayPtr(T* begin KJ_LIFETIMEBOUND, T* end KJ_LIFETIMEBOUND) 1645 : ptr(begin), size_(end - begin) {} 1646 ArrayPtr<T>& operator=(Array<T>&&) = delete; 1647 ArrayPtr<T>& operator=(decltype(nullptr)) { 1648 ptr = nullptr; 1649 size_ = 0; 1650 return *this; 1651 } 1652 1653 #if __GNUC__ && !__clang__ && __GNUC__ >= 9 1654 // GCC 9 added a warning when we take an initializer_list as a constructor parameter and save a 1655 // pointer to its content in a class member. GCC apparently imagines we're going to do something 1656 // dumb like this: 1657 // ArrayPtr<const int> ptr = { 1, 2, 3 }; 1658 // foo(ptr[1]); // undefined behavior! 1659 // Any KJ programmer should be able to recognize that this is UB, because an ArrayPtr does not own 1660 // its content. That's not what this constructor is for, tohugh. This constructor is meant to allow 1661 // code like this: 1662 // int foo(ArrayPtr<const int> p); 1663 // // ... later ... 1664 // foo({1, 2, 3}); 1665 // In this case, the initializer_list's backing array, like any temporary, lives until the end of 1666 // the statement `foo({1, 2, 3});`. Therefore, it lives at least until the call to foo() has 1667 // returned, which is exactly what we care about. This usage is fine! GCC is wrong to warn. 1668 // 1669 // Amusingly, Clang's implementation has a similar type that they call ArrayRef which apparently 1670 // triggers this same GCC warning. My guess is that Clang will not introduce a similar warning 1671 // given that it triggers on their own, legitimate code. 1672 #pragma GCC diagnostic push 1673 #pragma GCC diagnostic ignored "-Winit-list-lifetime" 1674 #endif 1675 inline KJ_CONSTEXPR() ArrayPtr( 1676 ::std::initializer_list<RemoveConstOrDisable<T>> init KJ_LIFETIMEBOUND) 1677 : ptr(init.begin()), size_(init.size()) {} 1678 #if __GNUC__ && !__clang__ && __GNUC__ >= 9 1679 #pragma GCC diagnostic pop 1680 #endif 1681 1682 template <size_t size> 1683 inline constexpr ArrayPtr(KJ_LIFETIMEBOUND T (&native)[size]): ptr(native), size_(size) { 1684 // Construct an ArrayPtr from a native C-style array. 1685 // 1686 // We disable this constructor for const char arrays because otherwise you would be able to 1687 // implicitly convert a character literal to ArrayPtr<const char>, which sounds really great, 1688 // except that the NUL terminator would be included, which probably isn't what you intended. 1689 // 1690 // TODO(someday): Maybe we should support character literals but explicitly chop off the NUL 1691 // terminator. This could do the wrong thing if someone tries to construct an 1692 // ArrayPtr<const char> from a non-NUL-terminated char array, but evidence suggests that all 1693 // real use cases are in fact intending to remove the NUL terminator. It's convenient to be 1694 // able to specify ArrayPtr<const char> as a parameter type and be able to accept strings 1695 // as input in addition to arrays. Currently, you'll need overloading to support string 1696 // literals in this case, but if you overload StringPtr, then you'll find that several 1697 // conversions (e.g. from String and from a literal char array) become ambiguous! You end up 1698 // having to overload for literal char arrays specifically which is cumbersome. 1699 1700 static_assert(!isSameType<T, const char>(), 1701 "Can't implicitly convert literal char array to ArrayPtr because we don't know if " 1702 "you meant to include the NUL terminator. We may change this in the future to " 1703 "automatically drop the NUL terminator. For now, try explicitly converting to StringPtr, " 1704 "which can in turn implicitly convert to ArrayPtr<const char>."); 1705 static_assert(!isSameType<T, const char16_t>(), "see above"); 1706 static_assert(!isSameType<T, const char32_t>(), "see above"); 1707 } 1708 1709 inline operator ArrayPtr<const T>() const { 1710 return ArrayPtr<const T>(ptr, size_); 1711 } 1712 inline ArrayPtr<const T> asConst() const { 1713 return ArrayPtr<const T>(ptr, size_); 1714 } 1715 1716 inline constexpr size_t size() const { return size_; } 1717 inline const T& operator[](size_t index) const { 1718 KJ_IREQUIRE(index < size_, "Out-of-bounds ArrayPtr access."); 1719 return ptr[index]; 1720 } 1721 inline T& operator[](size_t index) { 1722 KJ_IREQUIRE(index < size_, "Out-of-bounds ArrayPtr access."); 1723 return ptr[index]; 1724 } 1725 1726 inline T* begin() { return ptr; } 1727 inline T* end() { return ptr + size_; } 1728 inline T& front() { return *ptr; } 1729 inline T& back() { return *(ptr + size_ - 1); } 1730 inline constexpr const T* begin() const { return ptr; } 1731 inline constexpr const T* end() const { return ptr + size_; } 1732 inline const T& front() const { return *ptr; } 1733 inline const T& back() const { return *(ptr + size_ - 1); } 1734 1735 inline ArrayPtr<const T> slice(size_t start, size_t end) const { 1736 KJ_IREQUIRE(start <= end && end <= size_, "Out-of-bounds ArrayPtr::slice()."); 1737 return ArrayPtr<const T>(ptr + start, end - start); 1738 } 1739 inline ArrayPtr slice(size_t start, size_t end) { 1740 KJ_IREQUIRE(start <= end && end <= size_, "Out-of-bounds ArrayPtr::slice()."); 1741 return ArrayPtr(ptr + start, end - start); 1742 } 1743 1744 inline ArrayPtr<PropagateConst<T, byte>> asBytes() const { 1745 // Reinterpret the array as a byte array. This is explicitly legal under C++ aliasing 1746 // rules. 1747 return { reinterpret_cast<PropagateConst<T, byte>*>(ptr), size_ * sizeof(T) }; 1748 } 1749 inline ArrayPtr<PropagateConst<T, char>> asChars() const { 1750 // Reinterpret the array as a char array. This is explicitly legal under C++ aliasing 1751 // rules. 1752 return { reinterpret_cast<PropagateConst<T, char>*>(ptr), size_ * sizeof(T) }; 1753 } 1754 1755 inline bool operator==(decltype(nullptr)) const { return size_ == 0; } 1756 inline bool operator!=(decltype(nullptr)) const { return size_ != 0; } 1757 1758 inline bool operator==(const ArrayPtr& other) const { 1759 if (size_ != other.size_) return false; 1760 for (size_t i = 0; i < size_; i++) { 1761 if (ptr[i] != other[i]) return false; 1762 } 1763 return true; 1764 } 1765 inline bool operator!=(const ArrayPtr& other) const { return !(*this == other); } 1766 1767 template <typename U> 1768 inline bool operator==(const ArrayPtr<U>& other) const { 1769 if (size_ != other.size()) return false; 1770 for (size_t i = 0; i < size_; i++) { 1771 if (ptr[i] != other[i]) return false; 1772 } 1773 return true; 1774 } 1775 template <typename U> 1776 inline bool operator!=(const ArrayPtr<U>& other) const { return !(*this == other); } 1777 1778 template <typename... Attachments> 1779 Array<T> attach(Attachments&&... attachments) const KJ_WARN_UNUSED_RESULT; 1780 // Like Array<T>::attach(), but also promotes an ArrayPtr to an Array. Generally the attachment 1781 // should be an object that actually owns the array that the ArrayPtr is pointing at. 1782 // 1783 // You must include kj/array.h to call this. 1784 1785 private: 1786 T* ptr; 1787 size_t size_; 1788 }; 1789 1790 template <typename T> 1791 inline constexpr ArrayPtr<T> arrayPtr(T* ptr KJ_LIFETIMEBOUND, size_t size) { 1792 // Use this function to construct ArrayPtrs without writing out the type name. 1793 return ArrayPtr<T>(ptr, size); 1794 } 1795 1796 template <typename T> 1797 inline constexpr ArrayPtr<T> arrayPtr(T* begin KJ_LIFETIMEBOUND, T* end KJ_LIFETIMEBOUND) { 1798 // Use this function to construct ArrayPtrs without writing out the type name. 1799 return ArrayPtr<T>(begin, end); 1800 } 1801 1802 // ======================================================================================= 1803 // Casts 1804 1805 template <typename To, typename From> 1806 To implicitCast(From&& from) { 1807 // `implicitCast<T>(value)` casts `value` to type `T` only if the conversion is implicit. Useful 1808 // for e.g. resolving ambiguous overloads without sacrificing type-safety. 1809 return kj::fwd<From>(from); 1810 } 1811 1812 template <typename To, typename From> 1813 Maybe<To&> dynamicDowncastIfAvailable(From& from) { 1814 // If RTTI is disabled, always returns nullptr. Otherwise, works like dynamic_cast. Useful 1815 // in situations where dynamic_cast could allow an optimization, but isn't strictly necessary 1816 // for correctness. It is highly recommended that you try to arrange all your dynamic_casts 1817 // this way, as a dynamic_cast that is necessary for correctness implies a flaw in the interface 1818 // design. 1819 1820 // Force a compile error if To is not a subtype of From. Cross-casting is rare; if it is needed 1821 // we should have a separate cast function like dynamicCrosscastIfAvailable(). 1822 if (false) { 1823 kj::implicitCast<From*>(kj::implicitCast<To*>(nullptr)); 1824 } 1825 1826 #if KJ_NO_RTTI 1827 return nullptr; 1828 #else 1829 return dynamic_cast<To*>(&from); 1830 #endif 1831 } 1832 1833 template <typename To, typename From> 1834 To& downcast(From& from) { 1835 // Down-cast a value to a sub-type, asserting that the cast is valid. In opt mode this is a 1836 // static_cast, but in debug mode (when RTTI is enabled) a dynamic_cast will be used to verify 1837 // that the value really has the requested type. 1838 1839 // Force a compile error if To is not a subtype of From. 1840 if (false) { 1841 kj::implicitCast<From*>(kj::implicitCast<To*>(nullptr)); 1842 } 1843 1844 #if !KJ_NO_RTTI 1845 KJ_IREQUIRE(dynamic_cast<To*>(&from) != nullptr, "Value cannot be downcast() to requested type."); 1846 #endif 1847 1848 return static_cast<To&>(from); 1849 } 1850 1851 // ======================================================================================= 1852 // Defer 1853 1854 namespace _ { // private 1855 1856 template <typename Func> 1857 class Deferred { 1858 public: 1859 inline Deferred(Func&& func): func(kj::fwd<Func>(func)), canceled(false) {} 1860 inline ~Deferred() noexcept(false) { if (!canceled) func(); } 1861 KJ_DISALLOW_COPY(Deferred); 1862 1863 // This move constructor is usually optimized away by the compiler. 1864 inline Deferred(Deferred&& other): func(kj::fwd<Func>(other.func)), canceled(false) { 1865 other.canceled = true; 1866 } 1867 private: 1868 Func func; 1869 bool canceled; 1870 }; 1871 1872 } // namespace _ (private) 1873 1874 template <typename Func> 1875 _::Deferred<Func> defer(Func&& func) { 1876 // Returns an object which will invoke the given functor in its destructor. The object is not 1877 // copyable but is movable with the semantics you'd expect. Since the return type is private, 1878 // you need to assign to an `auto` variable. 1879 // 1880 // The KJ_DEFER macro provides slightly more convenient syntax for the common case where you 1881 // want some code to run at current scope exit. 1882 1883 return _::Deferred<Func>(kj::fwd<Func>(func)); 1884 } 1885 1886 #define KJ_DEFER(code) auto KJ_UNIQUE_NAME(_kjDefer) = ::kj::defer([&](){code;}) 1887 // Run the given code when the function exits, whether by return or exception. 1888 1889 } // namespace kj 1890 1891 KJ_END_HEADER