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