Chris@63: // Copyright (c) 2013-2014 Sandstorm Development Group, Inc. and contributors Chris@63: // Licensed under the MIT License: Chris@63: // Chris@63: // Permission is hereby granted, free of charge, to any person obtaining a copy Chris@63: // of this software and associated documentation files (the "Software"), to deal Chris@63: // in the Software without restriction, including without limitation the rights Chris@63: // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell Chris@63: // copies of the Software, and to permit persons to whom the Software is Chris@63: // furnished to do so, subject to the following conditions: Chris@63: // Chris@63: // The above copyright notice and this permission notice shall be included in Chris@63: // all copies or substantial portions of the Software. Chris@63: // Chris@63: // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR Chris@63: // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, Chris@63: // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE Chris@63: // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER Chris@63: // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, Chris@63: // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN Chris@63: // THE SOFTWARE. Chris@63: Chris@63: // Header that should be #included by everyone. Chris@63: // Chris@63: // This defines very simple utilities that are widely applicable. Chris@63: Chris@63: #ifndef KJ_COMMON_H_ Chris@63: #define KJ_COMMON_H_ Chris@63: Chris@63: #if defined(__GNUC__) && !KJ_HEADER_WARNINGS Chris@63: #pragma GCC system_header Chris@63: #endif Chris@63: Chris@63: #ifndef KJ_NO_COMPILER_CHECK Chris@63: #if __cplusplus < 201103L && !__CDT_PARSER__ && !_MSC_VER Chris@63: #error "This code requires C++11. Either your compiler does not support it or it is not enabled." Chris@63: #ifdef __GNUC__ Chris@63: // Compiler claims compatibility with GCC, so presumably supports -std. Chris@63: #error "Pass -std=c++11 on the compiler command line to enable C++11." Chris@63: #endif Chris@63: #endif Chris@63: Chris@63: #ifdef __GNUC__ Chris@63: #if __clang__ Chris@63: #if __clang_major__ < 3 || (__clang_major__ == 3 && __clang_minor__ < 2) Chris@63: #warning "This library requires at least Clang 3.2." Chris@63: #elif defined(__apple_build_version__) && __apple_build_version__ <= 4250028 Chris@63: #warning "This library requires at least Clang 3.2. XCode 4.6's Clang, which claims to be "\ Chris@63: "version 4.2 (wat?), is actually built from some random SVN revision between 3.1 "\ Chris@63: "and 3.2. Unfortunately, it is insufficient for compiling this library. You can "\ Chris@63: "download the real Clang 3.2 (or newer) from the Clang web site. Step-by-step "\ Chris@63: "instructions can be found in Cap'n Proto's documentation: "\ Chris@63: "http://kentonv.github.io/capnproto/install.html#clang_32_on_mac_osx" Chris@63: #elif __cplusplus >= 201103L && !__has_include() Chris@63: #warning "Your compiler supports C++11 but your C++ standard library does not. If your "\ Chris@63: "system has libc++ installed (as should be the case on e.g. Mac OSX), try adding "\ Chris@63: "-stdlib=libc++ to your CXXFLAGS." Chris@63: #endif Chris@63: #else Chris@63: #if __GNUC__ < 4 || (__GNUC__ == 4 && __GNUC_MINOR__ < 7) Chris@63: #warning "This library requires at least GCC 4.7." Chris@63: #endif Chris@63: #endif Chris@63: #elif defined(_MSC_VER) Chris@63: #if _MSC_VER < 1900 Chris@63: #error "You need Visual Studio 2015 or better to compile this code." Chris@63: #endif Chris@63: #else Chris@63: #warning "I don't recognize your compiler. As of this writing, Clang and GCC are the only "\ Chris@63: "known compilers with enough C++11 support for this library. "\ Chris@63: "#define KJ_NO_COMPILER_CHECK to make this warning go away." Chris@63: #endif Chris@63: #endif Chris@63: Chris@63: #include Chris@63: #include Chris@63: Chris@63: #if __linux__ && __cplusplus > 201200L Chris@63: // Hack around stdlib bug with C++14 that exists on some Linux systems. Chris@63: // Apparently in this mode the C library decides not to define gets() but the C++ library still Chris@63: // tries to import it into the std namespace. This bug has been fixed at the source but is still Chris@63: // widely present in the wild e.g. on Ubuntu 14.04. Chris@63: #undef _GLIBCXX_HAVE_GETS Chris@63: #endif Chris@63: Chris@63: #if defined(_MSC_VER) Chris@63: #ifndef NOMINMAX Chris@63: #define NOMINMAX 1 Chris@63: #endif Chris@63: #include // __popcnt Chris@63: #endif Chris@63: Chris@63: // ======================================================================================= Chris@63: Chris@63: namespace kj { Chris@63: Chris@63: typedef unsigned int uint; Chris@63: typedef unsigned char byte; Chris@63: Chris@63: // ======================================================================================= Chris@63: // Common macros, especially for common yet compiler-specific features. Chris@63: Chris@63: // Detect whether RTTI and exceptions are enabled, assuming they are unless we have specific Chris@63: // evidence to the contrary. Clients can always define KJ_NO_RTTI or KJ_NO_EXCEPTIONS explicitly Chris@63: // to override these checks. Chris@63: #ifdef __GNUC__ Chris@63: #if !defined(KJ_NO_RTTI) && !__GXX_RTTI Chris@63: #define KJ_NO_RTTI 1 Chris@63: #endif Chris@63: #if !defined(KJ_NO_EXCEPTIONS) && !__EXCEPTIONS Chris@63: #define KJ_NO_EXCEPTIONS 1 Chris@63: #endif Chris@63: #elif defined(_MSC_VER) Chris@63: #if !defined(KJ_NO_RTTI) && !defined(_CPPRTTI) Chris@63: #define KJ_NO_RTTI 1 Chris@63: #endif Chris@63: #if !defined(KJ_NO_EXCEPTIONS) && !defined(_CPPUNWIND) Chris@63: #define KJ_NO_EXCEPTIONS 1 Chris@63: #endif Chris@63: #endif Chris@63: Chris@63: #if !defined(KJ_DEBUG) && !defined(KJ_NDEBUG) Chris@63: // Heuristically decide whether to enable debug mode. If DEBUG or NDEBUG is defined, use that. Chris@63: // Otherwise, fall back to checking whether optimization is enabled. Chris@63: #if defined(DEBUG) || defined(_DEBUG) Chris@63: #define KJ_DEBUG Chris@63: #elif defined(NDEBUG) Chris@63: #define KJ_NDEBUG Chris@63: #elif __OPTIMIZE__ Chris@63: #define KJ_NDEBUG Chris@63: #else Chris@63: #define KJ_DEBUG Chris@63: #endif Chris@63: #endif Chris@63: Chris@63: #define KJ_DISALLOW_COPY(classname) \ Chris@63: classname(const classname&) = delete; \ Chris@63: classname& operator=(const classname&) = delete Chris@63: // Deletes the implicit copy constructor and assignment operator. Chris@63: Chris@63: #ifdef __GNUC__ Chris@63: #define KJ_LIKELY(condition) __builtin_expect(condition, true) Chris@63: #define KJ_UNLIKELY(condition) __builtin_expect(condition, false) Chris@63: // Branch prediction macros. Evaluates to the condition given, but also tells the compiler that we Chris@63: // expect the condition to be true/false enough of the time that it's worth hard-coding branch Chris@63: // prediction. Chris@63: #else Chris@63: #define KJ_LIKELY(condition) (condition) Chris@63: #define KJ_UNLIKELY(condition) (condition) Chris@63: #endif Chris@63: Chris@63: #if defined(KJ_DEBUG) || __NO_INLINE__ Chris@63: #define KJ_ALWAYS_INLINE(...) inline __VA_ARGS__ Chris@63: // Don't force inline in debug mode. Chris@63: #else Chris@63: #if defined(_MSC_VER) Chris@63: #define KJ_ALWAYS_INLINE(...) __forceinline __VA_ARGS__ Chris@63: #else Chris@63: #define KJ_ALWAYS_INLINE(...) inline __VA_ARGS__ __attribute__((always_inline)) Chris@63: #endif Chris@63: // Force a function to always be inlined. Apply only to the prototype, not to the definition. Chris@63: #endif Chris@63: Chris@63: #if defined(_MSC_VER) Chris@63: #define KJ_NOINLINE __declspec(noinline) Chris@63: #else Chris@63: #define KJ_NOINLINE __attribute__((noinline)) Chris@63: #endif Chris@63: Chris@63: #if defined(_MSC_VER) Chris@63: #define KJ_NORETURN(prototype) __declspec(noreturn) prototype Chris@63: #define KJ_UNUSED Chris@63: #define KJ_WARN_UNUSED_RESULT Chris@63: // TODO(msvc): KJ_WARN_UNUSED_RESULT can use _Check_return_ on MSVC, but it's a prefix, so Chris@63: // wrapping the whole prototype is needed. http://msdn.microsoft.com/en-us/library/jj159529.aspx Chris@63: // Similarly, KJ_UNUSED could use __pragma(warning(suppress:...)), but again that's a prefix. Chris@63: #else Chris@63: #define KJ_NORETURN(prototype) prototype __attribute__((noreturn)) Chris@63: #define KJ_UNUSED __attribute__((unused)) Chris@63: #define KJ_WARN_UNUSED_RESULT __attribute__((warn_unused_result)) Chris@63: #endif Chris@63: Chris@63: #if __clang__ Chris@63: #define KJ_UNUSED_MEMBER __attribute__((unused)) Chris@63: // Inhibits "unused" warning for member variables. Only Clang produces such a warning, while GCC Chris@63: // complains if the attribute is set on members. Chris@63: #else Chris@63: #define KJ_UNUSED_MEMBER Chris@63: #endif Chris@63: Chris@63: #if __clang__ Chris@63: #define KJ_DEPRECATED(reason) \ Chris@63: __attribute__((deprecated(reason))) Chris@63: #define KJ_UNAVAILABLE(reason) \ Chris@63: __attribute__((unavailable(reason))) Chris@63: #elif __GNUC__ Chris@63: #define KJ_DEPRECATED(reason) \ Chris@63: __attribute__((deprecated)) Chris@63: #define KJ_UNAVAILABLE(reason) Chris@63: #else Chris@63: #define KJ_DEPRECATED(reason) Chris@63: #define KJ_UNAVAILABLE(reason) Chris@63: // TODO(msvc): Again, here, MSVC prefers a prefix, __declspec(deprecated). Chris@63: #endif Chris@63: Chris@63: namespace _ { // private Chris@63: Chris@63: KJ_NORETURN(void inlineRequireFailure( Chris@63: const char* file, int line, const char* expectation, const char* macroArgs, Chris@63: const char* message = nullptr)); Chris@63: Chris@63: KJ_NORETURN(void unreachable()); Chris@63: Chris@63: } // namespace _ (private) Chris@63: Chris@63: #ifdef KJ_DEBUG Chris@63: #if _MSC_VER Chris@63: #define KJ_IREQUIRE(condition, ...) \ Chris@63: if (KJ_LIKELY(condition)); else ::kj::_::inlineRequireFailure( \ Chris@63: __FILE__, __LINE__, #condition, "" #__VA_ARGS__, __VA_ARGS__) Chris@63: // Version of KJ_DREQUIRE() which is safe to use in headers that are #included by users. Used to Chris@63: // check preconditions inside inline methods. KJ_IREQUIRE is particularly useful in that Chris@63: // it will be enabled depending on whether the application is compiled in debug mode rather than Chris@63: // whether libkj is. Chris@63: #else Chris@63: #define KJ_IREQUIRE(condition, ...) \ Chris@63: if (KJ_LIKELY(condition)); else ::kj::_::inlineRequireFailure( \ Chris@63: __FILE__, __LINE__, #condition, #__VA_ARGS__, ##__VA_ARGS__) Chris@63: // Version of KJ_DREQUIRE() which is safe to use in headers that are #included by users. Used to Chris@63: // check preconditions inside inline methods. KJ_IREQUIRE is particularly useful in that Chris@63: // it will be enabled depending on whether the application is compiled in debug mode rather than Chris@63: // whether libkj is. Chris@63: #endif Chris@63: #else Chris@63: #define KJ_IREQUIRE(condition, ...) Chris@63: #endif Chris@63: Chris@63: #define KJ_IASSERT KJ_IREQUIRE Chris@63: Chris@63: #define KJ_UNREACHABLE ::kj::_::unreachable(); Chris@63: // Put this on code paths that cannot be reached to suppress compiler warnings about missing Chris@63: // returns. Chris@63: Chris@63: #if __clang__ Chris@63: #define KJ_CLANG_KNOWS_THIS_IS_UNREACHABLE_BUT_GCC_DOESNT Chris@63: #else Chris@63: #define KJ_CLANG_KNOWS_THIS_IS_UNREACHABLE_BUT_GCC_DOESNT KJ_UNREACHABLE Chris@63: #endif Chris@63: Chris@63: // #define KJ_STACK_ARRAY(type, name, size, minStack, maxStack) Chris@63: // Chris@63: // Allocate an array, preferably on the stack, unless it is too big. On GCC this will use Chris@63: // variable-sized arrays. For other compilers we could just use a fixed-size array. `minStack` Chris@63: // is the stack array size to use if variable-width arrays are not supported. `maxStack` is the Chris@63: // maximum stack array size if variable-width arrays *are* supported. Chris@63: #if __GNUC__ && !__clang__ Chris@63: #define KJ_STACK_ARRAY(type, name, size, minStack, maxStack) \ Chris@63: size_t name##_size = (size); \ Chris@63: bool name##_isOnStack = name##_size <= (maxStack); \ Chris@63: type name##_stack[name##_isOnStack ? size : 0]; \ Chris@63: ::kj::Array name##_heap = name##_isOnStack ? \ Chris@63: nullptr : kj::heapArray(name##_size); \ Chris@63: ::kj::ArrayPtr name = name##_isOnStack ? \ Chris@63: kj::arrayPtr(name##_stack, name##_size) : name##_heap Chris@63: #else Chris@63: #define KJ_STACK_ARRAY(type, name, size, minStack, maxStack) \ Chris@63: size_t name##_size = (size); \ Chris@63: bool name##_isOnStack = name##_size <= (minStack); \ Chris@63: type name##_stack[minStack]; \ Chris@63: ::kj::Array name##_heap = name##_isOnStack ? \ Chris@63: nullptr : kj::heapArray(name##_size); \ Chris@63: ::kj::ArrayPtr name = name##_isOnStack ? \ Chris@63: kj::arrayPtr(name##_stack, name##_size) : name##_heap Chris@63: #endif Chris@63: Chris@63: #define KJ_CONCAT_(x, y) x##y Chris@63: #define KJ_CONCAT(x, y) KJ_CONCAT_(x, y) Chris@63: #define KJ_UNIQUE_NAME(prefix) KJ_CONCAT(prefix, __LINE__) Chris@63: // Create a unique identifier name. We use concatenate __LINE__ rather than __COUNTER__ so that Chris@63: // the name can be used multiple times in the same macro. Chris@63: Chris@63: #if _MSC_VER Chris@63: Chris@63: #define KJ_CONSTEXPR(...) __VA_ARGS__ Chris@63: // Use in cases where MSVC barfs on constexpr. A replacement keyword (e.g. "const") can be Chris@63: // provided, or just leave blank to remove the keyword entirely. Chris@63: // Chris@63: // TODO(msvc): Remove this hack once MSVC fully supports constexpr. Chris@63: Chris@63: #ifndef __restrict__ Chris@63: #define __restrict__ __restrict Chris@63: // TODO(msvc): Would it be better to define a KJ_RESTRICT macro? Chris@63: #endif Chris@63: Chris@63: #pragma warning(disable: 4521 4522) Chris@63: // This warning complains when there are two copy constructors, one for a const reference and Chris@63: // one for a non-const reference. It is often quite necessary to do this in wrapper templates, Chris@63: // therefore this warning is dumb and we disable it. Chris@63: Chris@63: #pragma warning(disable: 4458) Chris@63: // Warns when a parameter name shadows a class member. Unfortunately my code does this a lot, Chris@63: // since I don't use a special name format for members. Chris@63: Chris@63: #else // _MSC_VER Chris@63: #define KJ_CONSTEXPR(...) constexpr Chris@63: #endif Chris@63: Chris@63: // ======================================================================================= Chris@63: // Template metaprogramming helpers. Chris@63: Chris@63: template struct NoInfer_ { typedef T Type; }; Chris@63: template using NoInfer = typename NoInfer_::Type; Chris@63: // Use NoInfer::Type in place of T for a template function parameter to prevent inference of Chris@63: // the type based on the parameter value. Chris@63: Chris@63: template struct RemoveConst_ { typedef T Type; }; Chris@63: template struct RemoveConst_ { typedef T Type; }; Chris@63: template using RemoveConst = typename RemoveConst_::Type; Chris@63: Chris@63: template struct IsLvalueReference_ { static constexpr bool value = false; }; Chris@63: template struct IsLvalueReference_ { static constexpr bool value = true; }; Chris@63: template Chris@63: inline constexpr bool isLvalueReference() { return IsLvalueReference_::value; } Chris@63: Chris@63: template struct Decay_ { typedef T Type; }; Chris@63: template struct Decay_ { typedef typename Decay_::Type Type; }; Chris@63: template struct Decay_ { typedef typename Decay_::Type Type; }; Chris@63: template struct Decay_ { typedef typename Decay_::Type Type; }; Chris@63: template struct Decay_ { typedef typename Decay_::Type Type; }; Chris@63: template struct Decay_ { typedef typename Decay_::Type Type; }; Chris@63: template struct Decay_ { typedef typename Decay_::Type Type; }; Chris@63: template struct Decay_ { typedef typename Decay_::Type Type; }; Chris@63: template struct Decay_ { typedef typename Decay_::Type Type; }; Chris@63: template using Decay = typename Decay_::Type; Chris@63: Chris@63: template struct EnableIf_; Chris@63: template <> struct EnableIf_ { typedef void Type; }; Chris@63: template using EnableIf = typename EnableIf_::Type; Chris@63: // Use like: Chris@63: // Chris@63: // template ()> Chris@63: // void func(T&& t); Chris@63: Chris@63: template struct VoidSfinae_ { using Type = void; }; Chris@63: template using VoidSfinae = typename VoidSfinae_::Type; Chris@63: // Note: VoidSfinae is std::void_t from C++17. Chris@63: Chris@63: template Chris@63: T instance() noexcept; Chris@63: // Like std::declval, but doesn't transform T into an rvalue reference. If you want that, specify Chris@63: // instance(). Chris@63: Chris@63: struct DisallowConstCopy { Chris@63: // Inherit from this, or declare a member variable of this type, to prevent the class from being Chris@63: // copyable from a const reference -- instead, it will only be copyable from non-const references. Chris@63: // This is useful for enforcing transitive constness of contained pointers. Chris@63: // Chris@63: // For example, say you have a type T which contains a pointer. T has non-const methods which Chris@63: // modify the value at that pointer, but T's const methods are designed to allow reading only. Chris@63: // Unfortunately, if T has a regular copy constructor, someone can simply make a copy of T and Chris@63: // then use it to modify the pointed-to value. However, if T inherits DisallowConstCopy, then Chris@63: // callers will only be able to copy non-const instances of T. Ideally, there is some Chris@63: // parallel type ImmutableT which is like a version of T that only has const methods, and can Chris@63: // be copied from a const T. Chris@63: // Chris@63: // Note that due to C++ rules about implicit copy constructors and assignment operators, any Chris@63: // type that contains or inherits from a type that disallows const copies will also automatically Chris@63: // disallow const copies. Hey, cool, that's exactly what we want. Chris@63: Chris@63: #if CAPNP_DEBUG_TYPES Chris@63: // Alas! Declaring a defaulted non-const copy constructor tickles a bug which causes GCC and Chris@63: // Clang to disagree on ABI, using different calling conventions to pass this type, leading to Chris@63: // immediate segfaults. See: Chris@63: // https://bugs.llvm.org/show_bug.cgi?id=23764 Chris@63: // https://gcc.gnu.org/bugzilla/show_bug.cgi?id=58074 Chris@63: // Chris@63: // Because of this, we can't use this technique. We guard it by CAPNP_DEBUG_TYPES so that it Chris@63: // still applies to the Cap'n Proto developers during internal testing. Chris@63: Chris@63: DisallowConstCopy() = default; Chris@63: DisallowConstCopy(DisallowConstCopy&) = default; Chris@63: DisallowConstCopy(DisallowConstCopy&&) = default; Chris@63: DisallowConstCopy& operator=(DisallowConstCopy&) = default; Chris@63: DisallowConstCopy& operator=(DisallowConstCopy&&) = default; Chris@63: #endif Chris@63: }; Chris@63: Chris@63: #if _MSC_VER Chris@63: Chris@63: #define KJ_CPCAP(obj) obj=::kj::cp(obj) Chris@63: // TODO(msvc): MSVC refuses to invoke non-const versions of copy constructors in by-value lambda Chris@63: // captures. Wrap your captured object in this macro to force the compiler to perform a copy. Chris@63: // Example: Chris@63: // Chris@63: // struct Foo: DisallowConstCopy {}; Chris@63: // Foo foo; Chris@63: // auto lambda = [KJ_CPCAP(foo)] {}; Chris@63: Chris@63: #else Chris@63: Chris@63: #define KJ_CPCAP(obj) obj Chris@63: // Clang and gcc both already perform copy capturing correctly with non-const copy constructors. Chris@63: Chris@63: #endif Chris@63: Chris@63: template Chris@63: struct DisallowConstCopyIfNotConst: public DisallowConstCopy { Chris@63: // Inherit from this when implementing a template that contains a pointer to T and which should Chris@63: // enforce transitive constness. If T is a const type, this has no effect. Otherwise, it is Chris@63: // an alias for DisallowConstCopy. Chris@63: }; Chris@63: Chris@63: template Chris@63: struct DisallowConstCopyIfNotConst {}; Chris@63: Chris@63: template struct IsConst_ { static constexpr bool value = false; }; Chris@63: template struct IsConst_ { static constexpr bool value = true; }; Chris@63: template constexpr bool isConst() { return IsConst_::value; } Chris@63: Chris@63: template struct EnableIfNotConst_ { typedef T Type; }; Chris@63: template struct EnableIfNotConst_; Chris@63: template using EnableIfNotConst = typename EnableIfNotConst_::Type; Chris@63: Chris@63: template struct EnableIfConst_; Chris@63: template struct EnableIfConst_ { typedef T Type; }; Chris@63: template using EnableIfConst = typename EnableIfConst_::Type; Chris@63: Chris@63: template struct RemoveConstOrDisable_ { struct Type; }; Chris@63: template struct RemoveConstOrDisable_ { typedef T Type; }; Chris@63: template using RemoveConstOrDisable = typename RemoveConstOrDisable_::Type; Chris@63: Chris@63: template struct IsReference_ { static constexpr bool value = false; }; Chris@63: template struct IsReference_ { static constexpr bool value = true; }; Chris@63: template constexpr bool isReference() { return IsReference_::value; } Chris@63: Chris@63: template Chris@63: struct PropagateConst_ { typedef To Type; }; Chris@63: template Chris@63: struct PropagateConst_ { typedef const To Type; }; Chris@63: template Chris@63: using PropagateConst = typename PropagateConst_::Type; Chris@63: Chris@63: namespace _ { // private Chris@63: Chris@63: template Chris@63: T refIfLvalue(T&&); Chris@63: Chris@63: } // namespace _ (private) Chris@63: Chris@63: #define KJ_DECLTYPE_REF(exp) decltype(::kj::_::refIfLvalue(exp)) Chris@63: // Like decltype(exp), but if exp is an lvalue, produces a reference type. Chris@63: // Chris@63: // int i; Chris@63: // decltype(i) i1(i); // i1 has type int. Chris@63: // KJ_DECLTYPE_REF(i + 1) i2(i + 1); // i2 has type int. Chris@63: // KJ_DECLTYPE_REF(i) i3(i); // i3 has type int&. Chris@63: // KJ_DECLTYPE_REF(kj::mv(i)) i4(kj::mv(i)); // i4 has type int. Chris@63: Chris@63: template Chris@63: struct CanConvert_ { Chris@63: static int sfinae(T); Chris@63: static bool sfinae(...); Chris@63: }; Chris@63: Chris@63: template Chris@63: constexpr bool canConvert() { Chris@63: return sizeof(CanConvert_::sfinae(instance())) == sizeof(int); Chris@63: } Chris@63: Chris@63: #if __GNUC__ && !__clang__ && __GNUC__ < 5 Chris@63: template Chris@63: constexpr bool canMemcpy() { Chris@63: // Returns true if T can be copied using memcpy instead of using the copy constructor or Chris@63: // assignment operator. Chris@63: Chris@63: // GCC 4 does not have __is_trivially_constructible and friends, and there doesn't seem to be Chris@63: // any reliable alternative. __has_trivial_copy() and __has_trivial_assign() return the right Chris@63: // thing at one point but later on they changed such that a deleted copy constructor was Chris@63: // considered "trivial" (apparently technically correct, though useless). So, on GCC 4 we give up Chris@63: // and assume we can't memcpy() at all, and must explicitly copy-construct everything. Chris@63: return false; Chris@63: } Chris@63: #define KJ_ASSERT_CAN_MEMCPY(T) Chris@63: #else Chris@63: template Chris@63: constexpr bool canMemcpy() { Chris@63: // Returns true if T can be copied using memcpy instead of using the copy constructor or Chris@63: // assignment operator. Chris@63: Chris@63: return __is_trivially_constructible(T, const T&) && __is_trivially_assignable(T, const T&); Chris@63: } Chris@63: #define KJ_ASSERT_CAN_MEMCPY(T) \ Chris@63: static_assert(kj::canMemcpy(), "this code expects this type to be memcpy()-able"); Chris@63: #endif Chris@63: Chris@63: // ======================================================================================= Chris@63: // Equivalents to std::move() and std::forward(), since these are very commonly needed and the Chris@63: // std header pulls in lots of other stuff. Chris@63: // Chris@63: // We use abbreviated names mv and fwd because these helpers (especially mv) are so commonly used Chris@63: // that the cost of typing more letters outweighs the cost of being slightly harder to understand Chris@63: // when first encountered. Chris@63: Chris@63: template constexpr T&& mv(T& t) noexcept { return static_cast(t); } Chris@63: template constexpr T&& fwd(NoInfer& t) noexcept { return static_cast(t); } Chris@63: Chris@63: template constexpr T cp(T& t) noexcept { return t; } Chris@63: template constexpr T cp(const T& t) noexcept { return t; } Chris@63: // Useful to force a copy, particularly to pass into a function that expects T&&. Chris@63: Chris@63: template struct ChooseType_; Chris@63: template struct ChooseType_ { typedef T Type; }; Chris@63: template struct ChooseType_ { typedef T Type; }; Chris@63: template struct ChooseType_ { typedef U Type; }; Chris@63: Chris@63: template Chris@63: using WiderType = typename ChooseType_= sizeof(U)>::Type; Chris@63: Chris@63: template Chris@63: inline constexpr auto min(T&& a, U&& b) -> WiderType, Decay> { Chris@63: return a < b ? WiderType, Decay>(a) : WiderType, Decay>(b); Chris@63: } Chris@63: Chris@63: template Chris@63: inline constexpr auto max(T&& a, U&& b) -> WiderType, Decay> { Chris@63: return a > b ? WiderType, Decay>(a) : WiderType, Decay>(b); Chris@63: } Chris@63: Chris@63: template Chris@63: inline constexpr size_t size(T (&arr)[s]) { return s; } Chris@63: template Chris@63: inline constexpr size_t size(T&& arr) { return arr.size(); } Chris@63: // Returns the size of the parameter, whether the parameter is a regular C array or a container Chris@63: // with a `.size()` method. Chris@63: Chris@63: class MaxValue_ { Chris@63: private: Chris@63: template Chris@63: inline constexpr T maxSigned() const { Chris@63: return (1ull << (sizeof(T) * 8 - 1)) - 1; Chris@63: } Chris@63: template Chris@63: inline constexpr T maxUnsigned() const { Chris@63: return ~static_cast(0u); Chris@63: } Chris@63: Chris@63: public: Chris@63: #define _kJ_HANDLE_TYPE(T) \ Chris@63: inline constexpr operator signed T() const { return MaxValue_::maxSigned < signed T>(); } \ Chris@63: inline constexpr operator unsigned T() const { return MaxValue_::maxUnsigned(); } Chris@63: _kJ_HANDLE_TYPE(char) Chris@63: _kJ_HANDLE_TYPE(short) Chris@63: _kJ_HANDLE_TYPE(int) Chris@63: _kJ_HANDLE_TYPE(long) Chris@63: _kJ_HANDLE_TYPE(long long) Chris@63: #undef _kJ_HANDLE_TYPE Chris@63: Chris@63: inline constexpr operator char() const { Chris@63: // `char` is different from both `signed char` and `unsigned char`, and may be signed or Chris@63: // unsigned on different platforms. Ugh. Chris@63: return char(-1) < 0 ? MaxValue_::maxSigned() Chris@63: : MaxValue_::maxUnsigned(); Chris@63: } Chris@63: }; Chris@63: Chris@63: class MinValue_ { Chris@63: private: Chris@63: template Chris@63: inline constexpr T minSigned() const { Chris@63: return 1ull << (sizeof(T) * 8 - 1); Chris@63: } Chris@63: template Chris@63: inline constexpr T minUnsigned() const { Chris@63: return 0u; Chris@63: } Chris@63: Chris@63: public: Chris@63: #define _kJ_HANDLE_TYPE(T) \ Chris@63: inline constexpr operator signed T() const { return MinValue_::minSigned < signed T>(); } \ Chris@63: inline constexpr operator unsigned T() const { return MinValue_::minUnsigned(); } Chris@63: _kJ_HANDLE_TYPE(char) Chris@63: _kJ_HANDLE_TYPE(short) Chris@63: _kJ_HANDLE_TYPE(int) Chris@63: _kJ_HANDLE_TYPE(long) Chris@63: _kJ_HANDLE_TYPE(long long) Chris@63: #undef _kJ_HANDLE_TYPE Chris@63: Chris@63: inline constexpr operator char() const { Chris@63: // `char` is different from both `signed char` and `unsigned char`, and may be signed or Chris@63: // unsigned on different platforms. Ugh. Chris@63: return char(-1) < 0 ? MinValue_::minSigned() Chris@63: : MinValue_::minUnsigned(); Chris@63: } Chris@63: }; Chris@63: Chris@63: static KJ_CONSTEXPR(const) MaxValue_ maxValue = MaxValue_(); Chris@63: // A special constant which, when cast to an integer type, takes on the maximum possible value of Chris@63: // that type. This is useful to use as e.g. a parameter to a function because it will be robust Chris@63: // in the face of changes to the parameter's type. Chris@63: // Chris@63: // `char` is not supported, but `signed char` and `unsigned char` are. Chris@63: Chris@63: static KJ_CONSTEXPR(const) MinValue_ minValue = MinValue_(); Chris@63: // A special constant which, when cast to an integer type, takes on the minimum possible value Chris@63: // of that type. This is useful to use as e.g. a parameter to a function because it will be robust Chris@63: // in the face of changes to the parameter's type. Chris@63: // Chris@63: // `char` is not supported, but `signed char` and `unsigned char` are. Chris@63: Chris@63: template Chris@63: inline bool operator==(T t, MaxValue_) { return t == Decay(maxValue); } Chris@63: template Chris@63: inline bool operator==(T t, MinValue_) { return t == Decay(minValue); } Chris@63: Chris@63: template Chris@63: inline constexpr unsigned long long maxValueForBits() { Chris@63: // Get the maximum integer representable in the given number of bits. Chris@63: Chris@63: // 1ull << 64 is unfortunately undefined. Chris@63: return (bits == 64 ? 0 : (1ull << bits)) - 1; Chris@63: } Chris@63: Chris@63: struct ThrowOverflow { Chris@63: // Functor which throws an exception complaining about integer overflow. Usually this is used Chris@63: // with the interfaces in units.h, but is defined here because Cap'n Proto wants to avoid Chris@63: // including units.h when not using CAPNP_DEBUG_TYPES. Chris@63: void operator()() const; Chris@63: }; Chris@63: Chris@63: #if __GNUC__ Chris@63: inline constexpr float inf() { return __builtin_huge_valf(); } Chris@63: inline constexpr float nan() { return __builtin_nanf(""); } Chris@63: Chris@63: #elif _MSC_VER Chris@63: Chris@63: // Do what MSVC math.h does Chris@63: #pragma warning(push) Chris@63: #pragma warning(disable: 4756) // "overflow in constant arithmetic" Chris@63: inline constexpr float inf() { return (float)(1e300 * 1e300); } Chris@63: #pragma warning(pop) Chris@63: Chris@63: float nan(); Chris@63: // Unfortunatley, inf() * 0.0f produces a NaN with the sign bit set, whereas our preferred Chris@63: // canonical NaN should not have the sign bit set. std::numeric_limits::quiet_NaN() Chris@63: // returns the correct NaN, but we don't want to #include that here. So, we give up and make Chris@63: // this out-of-line on MSVC. Chris@63: // Chris@63: // TODO(msvc): Can we do better? Chris@63: Chris@63: #else Chris@63: #error "Not sure how to support your compiler." Chris@63: #endif Chris@63: Chris@63: inline constexpr bool isNaN(float f) { return f != f; } Chris@63: inline constexpr bool isNaN(double f) { return f != f; } Chris@63: Chris@63: inline int popCount(unsigned int x) { Chris@63: #if defined(_MSC_VER) Chris@63: return __popcnt(x); Chris@63: // Note: __popcnt returns unsigned int, but the value is clearly guaranteed to fit into an int Chris@63: #else Chris@63: return __builtin_popcount(x); Chris@63: #endif Chris@63: } Chris@63: Chris@63: // ======================================================================================= Chris@63: // Useful fake containers Chris@63: Chris@63: template Chris@63: class Range { Chris@63: public: Chris@63: inline constexpr Range(const T& begin, const T& end): begin_(begin), end_(end) {} Chris@63: inline explicit constexpr Range(const T& end): begin_(0), end_(end) {} Chris@63: Chris@63: class Iterator { Chris@63: public: Chris@63: Iterator() = default; Chris@63: inline Iterator(const T& value): value(value) {} Chris@63: Chris@63: inline const T& operator* () const { return value; } Chris@63: inline const T& operator[](size_t index) const { return value + index; } Chris@63: inline Iterator& operator++() { ++value; return *this; } Chris@63: inline Iterator operator++(int) { return Iterator(value++); } Chris@63: inline Iterator& operator--() { --value; return *this; } Chris@63: inline Iterator operator--(int) { return Iterator(value--); } Chris@63: inline Iterator& operator+=(ptrdiff_t amount) { value += amount; return *this; } Chris@63: inline Iterator& operator-=(ptrdiff_t amount) { value -= amount; return *this; } Chris@63: inline Iterator operator+ (ptrdiff_t amount) const { return Iterator(value + amount); } Chris@63: inline Iterator operator- (ptrdiff_t amount) const { return Iterator(value - amount); } Chris@63: inline ptrdiff_t operator- (const Iterator& other) const { return value - other.value; } Chris@63: Chris@63: inline bool operator==(const Iterator& other) const { return value == other.value; } Chris@63: inline bool operator!=(const Iterator& other) const { return value != other.value; } Chris@63: inline bool operator<=(const Iterator& other) const { return value <= other.value; } Chris@63: inline bool operator>=(const Iterator& other) const { return value >= other.value; } Chris@63: inline bool operator< (const Iterator& other) const { return value < other.value; } Chris@63: inline bool operator> (const Iterator& other) const { return value > other.value; } Chris@63: Chris@63: private: Chris@63: T value; Chris@63: }; Chris@63: Chris@63: inline Iterator begin() const { return Iterator(begin_); } Chris@63: inline Iterator end() const { return Iterator(end_); } Chris@63: Chris@63: inline auto size() const -> decltype(instance() - instance()) { return end_ - begin_; } Chris@63: Chris@63: private: Chris@63: T begin_; Chris@63: T end_; Chris@63: }; Chris@63: Chris@63: template Chris@63: inline constexpr Range, Decay>> range(T begin, U end) { Chris@63: return Range, Decay>>(begin, end); Chris@63: } Chris@63: Chris@63: template Chris@63: inline constexpr Range> range(T begin, T end) { return Range>(begin, end); } Chris@63: // Returns a fake iterable container containing all values of T from `begin` (inclusive) to `end` Chris@63: // (exclusive). Example: Chris@63: // Chris@63: // // Prints 1, 2, 3, 4, 5, 6, 7, 8, 9. Chris@63: // for (int i: kj::range(1, 10)) { print(i); } Chris@63: Chris@63: template Chris@63: inline constexpr Range> zeroTo(T end) { return Range>(end); } Chris@63: // Returns a fake iterable container containing all values of T from zero (inclusive) to `end` Chris@63: // (exclusive). Example: Chris@63: // Chris@63: // // Prints 0, 1, 2, 3, 4, 5, 6, 7, 8, 9. Chris@63: // for (int i: kj::zeroTo(10)) { print(i); } Chris@63: Chris@63: template Chris@63: inline constexpr Range indices(T&& container) { Chris@63: // Shortcut for iterating over the indices of a container: Chris@63: // Chris@63: // for (size_t i: kj::indices(myArray)) { handle(myArray[i]); } Chris@63: Chris@63: return range(0, kj::size(container)); Chris@63: } Chris@63: Chris@63: template Chris@63: class Repeat { Chris@63: public: Chris@63: inline constexpr Repeat(const T& value, size_t count): value(value), count(count) {} Chris@63: Chris@63: class Iterator { Chris@63: public: Chris@63: Iterator() = default; Chris@63: inline Iterator(const T& value, size_t index): value(value), index(index) {} Chris@63: Chris@63: inline const T& operator* () const { return value; } Chris@63: inline const T& operator[](ptrdiff_t index) const { return value; } Chris@63: inline Iterator& operator++() { ++index; return *this; } Chris@63: inline Iterator operator++(int) { return Iterator(value, index++); } Chris@63: inline Iterator& operator--() { --index; return *this; } Chris@63: inline Iterator operator--(int) { return Iterator(value, index--); } Chris@63: inline Iterator& operator+=(ptrdiff_t amount) { index += amount; return *this; } Chris@63: inline Iterator& operator-=(ptrdiff_t amount) { index -= amount; return *this; } Chris@63: inline Iterator operator+ (ptrdiff_t amount) const { return Iterator(value, index + amount); } Chris@63: inline Iterator operator- (ptrdiff_t amount) const { return Iterator(value, index - amount); } Chris@63: inline ptrdiff_t operator- (const Iterator& other) const { return index - other.index; } Chris@63: Chris@63: inline bool operator==(const Iterator& other) const { return index == other.index; } Chris@63: inline bool operator!=(const Iterator& other) const { return index != other.index; } Chris@63: inline bool operator<=(const Iterator& other) const { return index <= other.index; } Chris@63: inline bool operator>=(const Iterator& other) const { return index >= other.index; } Chris@63: inline bool operator< (const Iterator& other) const { return index < other.index; } Chris@63: inline bool operator> (const Iterator& other) const { return index > other.index; } Chris@63: Chris@63: private: Chris@63: T value; Chris@63: size_t index; Chris@63: }; Chris@63: Chris@63: inline Iterator begin() const { return Iterator(value, 0); } Chris@63: inline Iterator end() const { return Iterator(value, count); } Chris@63: Chris@63: inline size_t size() const { return count; } Chris@63: inline const T& operator[](ptrdiff_t) const { return value; } Chris@63: Chris@63: private: Chris@63: T value; Chris@63: size_t count; Chris@63: }; Chris@63: Chris@63: template Chris@63: inline constexpr Repeat> repeat(T&& value, size_t count) { Chris@63: // Returns a fake iterable which contains `count` repeats of `value`. Useful for e.g. creating Chris@63: // a bunch of spaces: `kj::repeat(' ', indent * 2)` Chris@63: Chris@63: return Repeat>(value, count); Chris@63: } Chris@63: Chris@63: // ======================================================================================= Chris@63: // Manually invoking constructors and destructors Chris@63: // Chris@63: // ctor(x, ...) and dtor(x) invoke x's constructor or destructor, respectively. Chris@63: Chris@63: // We want placement new, but we don't want to #include . operator new cannot be defined in Chris@63: // a namespace, and defining it globally conflicts with the definition in . So we have to Chris@63: // define a dummy type and an operator new that uses it. Chris@63: Chris@63: namespace _ { // private Chris@63: struct PlacementNew {}; Chris@63: } // namespace _ (private) Chris@63: } // namespace kj Chris@63: Chris@63: inline void* operator new(size_t, kj::_::PlacementNew, void* __p) noexcept { Chris@63: return __p; Chris@63: } Chris@63: Chris@63: inline void operator delete(void*, kj::_::PlacementNew, void* __p) noexcept {} Chris@63: Chris@63: namespace kj { Chris@63: Chris@63: template Chris@63: inline void ctor(T& location, Params&&... params) { Chris@63: new (_::PlacementNew(), &location) T(kj::fwd(params)...); Chris@63: } Chris@63: Chris@63: template Chris@63: inline void dtor(T& location) { Chris@63: location.~T(); Chris@63: } Chris@63: Chris@63: // ======================================================================================= Chris@63: // Maybe Chris@63: // Chris@63: // Use in cases where you want to indicate that a value may be null. Using Maybe instead of T* Chris@63: // forces the caller to handle the null case in order to satisfy the compiler, thus reliably Chris@63: // preventing null pointer dereferences at runtime. Chris@63: // Chris@63: // Maybe can be implicitly constructed from T and from nullptr. Additionally, it can be Chris@63: // implicitly constructed from T*, in which case the pointer is checked for nullness at runtime. Chris@63: // To read the value of a Maybe, do: Chris@63: // Chris@63: // KJ_IF_MAYBE(value, someFuncReturningMaybe()) { Chris@63: // doSomething(*value); Chris@63: // } else { Chris@63: // maybeWasNull(); Chris@63: // } Chris@63: // Chris@63: // KJ_IF_MAYBE's first parameter is a variable name which will be defined within the following Chris@63: // block. The variable will behave like a (guaranteed non-null) pointer to the Maybe's value, Chris@63: // though it may or may not actually be a pointer. Chris@63: // Chris@63: // Note that Maybe actually just wraps a pointer, whereas Maybe wraps a T and a boolean Chris@63: // indicating nullness. Chris@63: Chris@63: template Chris@63: class Maybe; Chris@63: Chris@63: namespace _ { // private Chris@63: Chris@63: template Chris@63: class NullableValue { Chris@63: // Class whose interface behaves much like T*, but actually contains an instance of T and a Chris@63: // boolean flag indicating nullness. Chris@63: Chris@63: public: Chris@63: inline NullableValue(NullableValue&& other) noexcept(noexcept(T(instance()))) Chris@63: : isSet(other.isSet) { Chris@63: if (isSet) { Chris@63: ctor(value, kj::mv(other.value)); Chris@63: } Chris@63: } Chris@63: inline NullableValue(const NullableValue& other) Chris@63: : isSet(other.isSet) { Chris@63: if (isSet) { Chris@63: ctor(value, other.value); Chris@63: } Chris@63: } Chris@63: inline NullableValue(NullableValue& other) Chris@63: : isSet(other.isSet) { Chris@63: if (isSet) { Chris@63: ctor(value, other.value); Chris@63: } Chris@63: } Chris@63: inline ~NullableValue() Chris@63: #if _MSC_VER Chris@63: // TODO(msvc): MSVC has a hard time with noexcept specifier expressions that are more complex Chris@63: // than `true` or `false`. We had a workaround for VS2015, but VS2017 regressed. Chris@63: noexcept(false) Chris@63: #else Chris@63: noexcept(noexcept(instance().~T())) Chris@63: #endif Chris@63: { Chris@63: if (isSet) { Chris@63: dtor(value); Chris@63: } Chris@63: } Chris@63: Chris@63: inline T& operator*() & { return value; } Chris@63: inline const T& operator*() const & { return value; } Chris@63: inline T&& operator*() && { return kj::mv(value); } Chris@63: inline const T&& operator*() const && { return kj::mv(value); } Chris@63: inline T* operator->() { return &value; } Chris@63: inline const T* operator->() const { return &value; } Chris@63: inline operator T*() { return isSet ? &value : nullptr; } Chris@63: inline operator const T*() const { return isSet ? &value : nullptr; } Chris@63: Chris@63: template Chris@63: inline T& emplace(Params&&... params) { Chris@63: if (isSet) { Chris@63: isSet = false; Chris@63: dtor(value); Chris@63: } Chris@63: ctor(value, kj::fwd(params)...); Chris@63: isSet = true; Chris@63: return value; Chris@63: } Chris@63: Chris@63: private: // internal interface used by friends only Chris@63: inline NullableValue() noexcept: isSet(false) {} Chris@63: inline NullableValue(T&& t) noexcept(noexcept(T(instance()))) Chris@63: : isSet(true) { Chris@63: ctor(value, kj::mv(t)); Chris@63: } Chris@63: inline NullableValue(T& t) Chris@63: : isSet(true) { Chris@63: ctor(value, t); Chris@63: } Chris@63: inline NullableValue(const T& t) Chris@63: : isSet(true) { Chris@63: ctor(value, t); Chris@63: } Chris@63: inline NullableValue(const T* t) Chris@63: : isSet(t != nullptr) { Chris@63: if (isSet) ctor(value, *t); Chris@63: } Chris@63: template Chris@63: inline NullableValue(NullableValue&& other) noexcept(noexcept(T(instance()))) Chris@63: : isSet(other.isSet) { Chris@63: if (isSet) { Chris@63: ctor(value, kj::mv(other.value)); Chris@63: } Chris@63: } Chris@63: template Chris@63: inline NullableValue(const NullableValue& other) Chris@63: : isSet(other.isSet) { Chris@63: if (isSet) { Chris@63: ctor(value, other.value); Chris@63: } Chris@63: } Chris@63: template Chris@63: inline NullableValue(const NullableValue& other) Chris@63: : isSet(other.isSet) { Chris@63: if (isSet) { Chris@63: ctor(value, *other.ptr); Chris@63: } Chris@63: } Chris@63: inline NullableValue(decltype(nullptr)): isSet(false) {} Chris@63: Chris@63: inline NullableValue& operator=(NullableValue&& other) { Chris@63: if (&other != this) { Chris@63: // Careful about throwing destructors/constructors here. Chris@63: if (isSet) { Chris@63: isSet = false; Chris@63: dtor(value); Chris@63: } Chris@63: if (other.isSet) { Chris@63: ctor(value, kj::mv(other.value)); Chris@63: isSet = true; Chris@63: } Chris@63: } Chris@63: return *this; Chris@63: } Chris@63: Chris@63: inline NullableValue& operator=(NullableValue& other) { Chris@63: if (&other != this) { Chris@63: // Careful about throwing destructors/constructors here. Chris@63: if (isSet) { Chris@63: isSet = false; Chris@63: dtor(value); Chris@63: } Chris@63: if (other.isSet) { Chris@63: ctor(value, other.value); Chris@63: isSet = true; Chris@63: } Chris@63: } Chris@63: return *this; Chris@63: } Chris@63: Chris@63: inline NullableValue& operator=(const NullableValue& other) { Chris@63: if (&other != this) { Chris@63: // Careful about throwing destructors/constructors here. Chris@63: if (isSet) { Chris@63: isSet = false; Chris@63: dtor(value); Chris@63: } Chris@63: if (other.isSet) { Chris@63: ctor(value, other.value); Chris@63: isSet = true; Chris@63: } Chris@63: } Chris@63: return *this; Chris@63: } Chris@63: Chris@63: inline bool operator==(decltype(nullptr)) const { return !isSet; } Chris@63: inline bool operator!=(decltype(nullptr)) const { return isSet; } Chris@63: Chris@63: private: Chris@63: bool isSet; Chris@63: Chris@63: #if _MSC_VER Chris@63: #pragma warning(push) Chris@63: #pragma warning(disable: 4624) Chris@63: // Warns that the anonymous union has a deleted destructor when T is non-trivial. This warning Chris@63: // seems broken. Chris@63: #endif Chris@63: Chris@63: union { Chris@63: T value; Chris@63: }; Chris@63: Chris@63: #if _MSC_VER Chris@63: #pragma warning(pop) Chris@63: #endif Chris@63: Chris@63: friend class kj::Maybe; Chris@63: template Chris@63: friend NullableValue&& readMaybe(Maybe&& maybe); Chris@63: }; Chris@63: Chris@63: template Chris@63: inline NullableValue&& readMaybe(Maybe&& maybe) { return kj::mv(maybe.ptr); } Chris@63: template Chris@63: inline T* readMaybe(Maybe& maybe) { return maybe.ptr; } Chris@63: template Chris@63: inline const T* readMaybe(const Maybe& maybe) { return maybe.ptr; } Chris@63: template Chris@63: inline T* readMaybe(Maybe&& maybe) { return maybe.ptr; } Chris@63: template Chris@63: inline T* readMaybe(const Maybe& maybe) { return maybe.ptr; } Chris@63: Chris@63: template Chris@63: inline T* readMaybe(T* ptr) { return ptr; } Chris@63: // Allow KJ_IF_MAYBE to work on regular pointers. Chris@63: Chris@63: } // namespace _ (private) Chris@63: Chris@63: #define KJ_IF_MAYBE(name, exp) if (auto name = ::kj::_::readMaybe(exp)) Chris@63: Chris@63: template Chris@63: class Maybe { Chris@63: // A T, or nullptr. Chris@63: Chris@63: // IF YOU CHANGE THIS CLASS: Note that there is a specialization of it in memory.h. Chris@63: Chris@63: public: Chris@63: Maybe(): ptr(nullptr) {} Chris@63: Maybe(T&& t) noexcept(noexcept(T(instance()))): ptr(kj::mv(t)) {} Chris@63: Maybe(T& t): ptr(t) {} Chris@63: Maybe(const T& t): ptr(t) {} Chris@63: Maybe(const T* t) noexcept: ptr(t) {} Chris@63: Maybe(Maybe&& other) noexcept(noexcept(T(instance()))): ptr(kj::mv(other.ptr)) {} Chris@63: Maybe(const Maybe& other): ptr(other.ptr) {} Chris@63: Maybe(Maybe& other): ptr(other.ptr) {} Chris@63: Chris@63: template Chris@63: Maybe(Maybe&& other) noexcept(noexcept(T(instance()))) { Chris@63: KJ_IF_MAYBE(val, kj::mv(other)) { Chris@63: ptr.emplace(kj::mv(*val)); Chris@63: } Chris@63: } Chris@63: template Chris@63: Maybe(const Maybe& other) { Chris@63: KJ_IF_MAYBE(val, other) { Chris@63: ptr.emplace(*val); Chris@63: } Chris@63: } Chris@63: Chris@63: Maybe(decltype(nullptr)) noexcept: ptr(nullptr) {} Chris@63: Chris@63: template Chris@63: inline T& emplace(Params&&... params) { Chris@63: // Replace this Maybe's content with a new value constructed by passing the given parametrs to Chris@63: // T's constructor. This can be used to initialize a Maybe without copying or even moving a T. Chris@63: // Returns a reference to the newly-constructed value. Chris@63: Chris@63: return ptr.emplace(kj::fwd(params)...); Chris@63: } Chris@63: Chris@63: inline Maybe& operator=(Maybe&& other) { ptr = kj::mv(other.ptr); return *this; } Chris@63: inline Maybe& operator=(Maybe& other) { ptr = other.ptr; return *this; } Chris@63: inline Maybe& operator=(const Maybe& other) { ptr = other.ptr; return *this; } Chris@63: Chris@63: inline bool operator==(decltype(nullptr)) const { return ptr == nullptr; } Chris@63: inline bool operator!=(decltype(nullptr)) const { return ptr != nullptr; } Chris@63: Chris@63: T& orDefault(T& defaultValue) { Chris@63: if (ptr == nullptr) { Chris@63: return defaultValue; Chris@63: } else { Chris@63: return *ptr; Chris@63: } Chris@63: } Chris@63: const T& orDefault(const T& defaultValue) const { Chris@63: if (ptr == nullptr) { Chris@63: return defaultValue; Chris@63: } else { Chris@63: return *ptr; Chris@63: } Chris@63: } Chris@63: Chris@63: template Chris@63: auto map(Func&& f) & -> Maybe()))> { Chris@63: if (ptr == nullptr) { Chris@63: return nullptr; Chris@63: } else { Chris@63: return f(*ptr); Chris@63: } Chris@63: } Chris@63: Chris@63: template Chris@63: auto map(Func&& f) const & -> Maybe()))> { Chris@63: if (ptr == nullptr) { Chris@63: return nullptr; Chris@63: } else { Chris@63: return f(*ptr); Chris@63: } Chris@63: } Chris@63: Chris@63: template Chris@63: auto map(Func&& f) && -> Maybe()))> { Chris@63: if (ptr == nullptr) { Chris@63: return nullptr; Chris@63: } else { Chris@63: return f(kj::mv(*ptr)); Chris@63: } Chris@63: } Chris@63: Chris@63: template Chris@63: auto map(Func&& f) const && -> Maybe()))> { Chris@63: if (ptr == nullptr) { Chris@63: return nullptr; Chris@63: } else { Chris@63: return f(kj::mv(*ptr)); Chris@63: } Chris@63: } Chris@63: Chris@63: private: Chris@63: _::NullableValue ptr; Chris@63: Chris@63: template Chris@63: friend class Maybe; Chris@63: template Chris@63: friend _::NullableValue&& _::readMaybe(Maybe&& maybe); Chris@63: template Chris@63: friend U* _::readMaybe(Maybe& maybe); Chris@63: template Chris@63: friend const U* _::readMaybe(const Maybe& maybe); Chris@63: }; Chris@63: Chris@63: template Chris@63: class Maybe: public DisallowConstCopyIfNotConst { Chris@63: public: Chris@63: Maybe() noexcept: ptr(nullptr) {} Chris@63: Maybe(T& t) noexcept: ptr(&t) {} Chris@63: Maybe(T* t) noexcept: ptr(t) {} Chris@63: Chris@63: template Chris@63: inline Maybe(Maybe& other) noexcept: ptr(other.ptr) {} Chris@63: template Chris@63: inline Maybe(const Maybe& other) noexcept: ptr(other.ptr) {} Chris@63: inline Maybe(decltype(nullptr)) noexcept: ptr(nullptr) {} Chris@63: Chris@63: inline Maybe& operator=(T& other) noexcept { ptr = &other; return *this; } Chris@63: inline Maybe& operator=(T* other) noexcept { ptr = other; return *this; } Chris@63: template Chris@63: inline Maybe& operator=(Maybe& other) noexcept { ptr = other.ptr; return *this; } Chris@63: template Chris@63: inline Maybe& operator=(const Maybe& other) noexcept { ptr = other.ptr; return *this; } Chris@63: Chris@63: inline bool operator==(decltype(nullptr)) const { return ptr == nullptr; } Chris@63: inline bool operator!=(decltype(nullptr)) const { return ptr != nullptr; } Chris@63: Chris@63: T& orDefault(T& defaultValue) { Chris@63: if (ptr == nullptr) { Chris@63: return defaultValue; Chris@63: } else { Chris@63: return *ptr; Chris@63: } Chris@63: } Chris@63: const T& orDefault(const T& defaultValue) const { Chris@63: if (ptr == nullptr) { Chris@63: return defaultValue; Chris@63: } else { Chris@63: return *ptr; Chris@63: } Chris@63: } Chris@63: Chris@63: template Chris@63: auto map(Func&& f) -> Maybe()))> { Chris@63: if (ptr == nullptr) { Chris@63: return nullptr; Chris@63: } else { Chris@63: return f(*ptr); Chris@63: } Chris@63: } Chris@63: Chris@63: private: Chris@63: T* ptr; Chris@63: Chris@63: template Chris@63: friend class Maybe; Chris@63: template Chris@63: friend U* _::readMaybe(Maybe&& maybe); Chris@63: template Chris@63: friend U* _::readMaybe(const Maybe& maybe); Chris@63: }; Chris@63: Chris@63: // ======================================================================================= Chris@63: // ArrayPtr Chris@63: // Chris@63: // So common that we put it in common.h rather than array.h. Chris@63: Chris@63: template Chris@63: class ArrayPtr: public DisallowConstCopyIfNotConst { Chris@63: // A pointer to an array. Includes a size. Like any pointer, it doesn't own the target data, Chris@63: // and passing by value only copies the pointer, not the target. Chris@63: Chris@63: public: Chris@63: inline constexpr ArrayPtr(): ptr(nullptr), size_(0) {} Chris@63: inline constexpr ArrayPtr(decltype(nullptr)): ptr(nullptr), size_(0) {} Chris@63: inline constexpr ArrayPtr(T* ptr, size_t size): ptr(ptr), size_(size) {} Chris@63: inline constexpr ArrayPtr(T* begin, T* end): ptr(begin), size_(end - begin) {} Chris@63: inline KJ_CONSTEXPR() ArrayPtr(::std::initializer_list> init) Chris@63: : ptr(init.begin()), size_(init.size()) {} Chris@63: Chris@63: template Chris@63: inline constexpr ArrayPtr(T (&native)[size]): ptr(native), size_(size) {} Chris@63: // Construct an ArrayPtr from a native C-style array. Chris@63: Chris@63: inline operator ArrayPtr() const { Chris@63: return ArrayPtr(ptr, size_); Chris@63: } Chris@63: inline ArrayPtr asConst() const { Chris@63: return ArrayPtr(ptr, size_); Chris@63: } Chris@63: Chris@63: inline size_t size() const { return size_; } Chris@63: inline const T& operator[](size_t index) const { Chris@63: KJ_IREQUIRE(index < size_, "Out-of-bounds ArrayPtr access."); Chris@63: return ptr[index]; Chris@63: } Chris@63: inline T& operator[](size_t index) { Chris@63: KJ_IREQUIRE(index < size_, "Out-of-bounds ArrayPtr access."); Chris@63: return ptr[index]; Chris@63: } Chris@63: Chris@63: inline T* begin() { return ptr; } Chris@63: inline T* end() { return ptr + size_; } Chris@63: inline T& front() { return *ptr; } Chris@63: inline T& back() { return *(ptr + size_ - 1); } Chris@63: inline const T* begin() const { return ptr; } Chris@63: inline const T* end() const { return ptr + size_; } Chris@63: inline const T& front() const { return *ptr; } Chris@63: inline const T& back() const { return *(ptr + size_ - 1); } Chris@63: Chris@63: inline ArrayPtr slice(size_t start, size_t end) const { Chris@63: KJ_IREQUIRE(start <= end && end <= size_, "Out-of-bounds ArrayPtr::slice()."); Chris@63: return ArrayPtr(ptr + start, end - start); Chris@63: } Chris@63: inline ArrayPtr slice(size_t start, size_t end) { Chris@63: KJ_IREQUIRE(start <= end && end <= size_, "Out-of-bounds ArrayPtr::slice()."); Chris@63: return ArrayPtr(ptr + start, end - start); Chris@63: } Chris@63: Chris@63: inline ArrayPtr> asBytes() const { Chris@63: // Reinterpret the array as a byte array. This is explicitly legal under C++ aliasing Chris@63: // rules. Chris@63: return { reinterpret_cast*>(ptr), size_ * sizeof(T) }; Chris@63: } Chris@63: inline ArrayPtr> asChars() const { Chris@63: // Reinterpret the array as a char array. This is explicitly legal under C++ aliasing Chris@63: // rules. Chris@63: return { reinterpret_cast*>(ptr), size_ * sizeof(T) }; Chris@63: } Chris@63: Chris@63: inline bool operator==(decltype(nullptr)) const { return size_ == 0; } Chris@63: inline bool operator!=(decltype(nullptr)) const { return size_ != 0; } Chris@63: Chris@63: inline bool operator==(const ArrayPtr& other) const { Chris@63: if (size_ != other.size_) return false; Chris@63: for (size_t i = 0; i < size_; i++) { Chris@63: if (ptr[i] != other[i]) return false; Chris@63: } Chris@63: return true; Chris@63: } Chris@63: inline bool operator!=(const ArrayPtr& other) const { return !(*this == other); } Chris@63: Chris@63: private: Chris@63: T* ptr; Chris@63: size_t size_; Chris@63: }; Chris@63: Chris@63: template Chris@63: inline constexpr ArrayPtr arrayPtr(T* ptr, size_t size) { Chris@63: // Use this function to construct ArrayPtrs without writing out the type name. Chris@63: return ArrayPtr(ptr, size); Chris@63: } Chris@63: Chris@63: template Chris@63: inline constexpr ArrayPtr arrayPtr(T* begin, T* end) { Chris@63: // Use this function to construct ArrayPtrs without writing out the type name. Chris@63: return ArrayPtr(begin, end); Chris@63: } Chris@63: Chris@63: // ======================================================================================= Chris@63: // Casts Chris@63: Chris@63: template Chris@63: To implicitCast(From&& from) { Chris@63: // `implicitCast(value)` casts `value` to type `T` only if the conversion is implicit. Useful Chris@63: // for e.g. resolving ambiguous overloads without sacrificing type-safety. Chris@63: return kj::fwd(from); Chris@63: } Chris@63: Chris@63: template Chris@63: Maybe dynamicDowncastIfAvailable(From& from) { Chris@63: // If RTTI is disabled, always returns nullptr. Otherwise, works like dynamic_cast. Useful Chris@63: // in situations where dynamic_cast could allow an optimization, but isn't strictly necessary Chris@63: // for correctness. It is highly recommended that you try to arrange all your dynamic_casts Chris@63: // this way, as a dynamic_cast that is necessary for correctness implies a flaw in the interface Chris@63: // design. Chris@63: Chris@63: // Force a compile error if To is not a subtype of From. Cross-casting is rare; if it is needed Chris@63: // we should have a separate cast function like dynamicCrosscastIfAvailable(). Chris@63: if (false) { Chris@63: kj::implicitCast(kj::implicitCast(nullptr)); Chris@63: } Chris@63: Chris@63: #if KJ_NO_RTTI Chris@63: return nullptr; Chris@63: #else Chris@63: return dynamic_cast(&from); Chris@63: #endif Chris@63: } Chris@63: Chris@63: template Chris@63: To& downcast(From& from) { Chris@63: // Down-cast a value to a sub-type, asserting that the cast is valid. In opt mode this is a Chris@63: // static_cast, but in debug mode (when RTTI is enabled) a dynamic_cast will be used to verify Chris@63: // that the value really has the requested type. Chris@63: Chris@63: // Force a compile error if To is not a subtype of From. Chris@63: if (false) { Chris@63: kj::implicitCast(kj::implicitCast(nullptr)); Chris@63: } Chris@63: Chris@63: #if !KJ_NO_RTTI Chris@63: KJ_IREQUIRE(dynamic_cast(&from) != nullptr, "Value cannot be downcast() to requested type."); Chris@63: #endif Chris@63: Chris@63: return static_cast(from); Chris@63: } Chris@63: Chris@63: // ======================================================================================= Chris@63: // Defer Chris@63: Chris@63: namespace _ { // private Chris@63: Chris@63: template Chris@63: class Deferred { Chris@63: public: Chris@63: inline Deferred(Func&& func): func(kj::fwd(func)), canceled(false) {} Chris@63: inline ~Deferred() noexcept(false) { if (!canceled) func(); } Chris@63: KJ_DISALLOW_COPY(Deferred); Chris@63: Chris@63: // This move constructor is usually optimized away by the compiler. Chris@63: inline Deferred(Deferred&& other): func(kj::mv(other.func)), canceled(false) { Chris@63: other.canceled = true; Chris@63: } Chris@63: private: Chris@63: Func func; Chris@63: bool canceled; Chris@63: }; Chris@63: Chris@63: } // namespace _ (private) Chris@63: Chris@63: template Chris@63: _::Deferred defer(Func&& func) { Chris@63: // Returns an object which will invoke the given functor in its destructor. The object is not Chris@63: // copyable but is movable with the semantics you'd expect. Since the return type is private, Chris@63: // you need to assign to an `auto` variable. Chris@63: // Chris@63: // The KJ_DEFER macro provides slightly more convenient syntax for the common case where you Chris@63: // want some code to run at current scope exit. Chris@63: Chris@63: return _::Deferred(kj::fwd(func)); Chris@63: } Chris@63: Chris@63: #define KJ_DEFER(code) auto KJ_UNIQUE_NAME(_kjDefer) = ::kj::defer([&](){code;}) Chris@63: // Run the given code when the function exits, whether by return or exception. Chris@63: Chris@63: } // namespace kj Chris@63: Chris@63: #endif // KJ_COMMON_H_