common.h 29.2 KB
Newer Older
Kenton Varda's avatar
Kenton Varda committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
// Copyright (c) 2013, Kenton Varda <temporal@gmail.com>
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this
//    list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright notice,
//    this list of conditions and the following disclaimer in the documentation
//    and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

// Header that should be #included by everyone.
//
// This defines very simple utilities that are widely applicable.

28 29
#include <stddef.h>

Kenton Varda's avatar
Kenton Varda committed
30 31 32
#ifndef KJ_COMMON_H_
#define KJ_COMMON_H_

33
#ifndef KJ_NO_COMPILER_CHECK
34
#if __cplusplus < 201103L && !__CDT_PARSER__
Kenton Varda's avatar
Kenton Varda committed
35 36 37 38 39 40 41 42 43 44 45
  #error "This code requires C++11. Either your compiler does not support it or it is not enabled."
  #ifdef __GNUC__
    // Compiler claims compatibility with GCC, so presumably supports -std.
    #error "Pass -std=c++11 on the compiler command line to enable C++11."
  #endif
#endif

#ifdef __GNUC__
  #if __clang__
    #if __clang_major__ < 3 || (__clang_major__ == 3 && __clang_minor__ < 2)
      #warning "This library requires at least Clang 3.2."
46 47 48 49
    #elif defined(__apple_build_version__) && __apple_build_version__ <= 4250028
      #warning "This library requires at least Clang 3.2.  XCode 4.6's Clang, which claims to be "\
               "version 4.2 (wat?), is actually built from some random SVN revision between 3.1 "\
               "and 3.2.  Unfortunately, it is insufficient for compiling this library.  You can "\
50 51 52
               "download the real Clang 3.2 (or newer) from the Clang web site.  Step-by-step "\
               "instructions can be found in Cap'n Proto's documentation: "\
               "http://kentonv.github.io/capnproto/install.html#clang_32_on_mac_osx"
53 54 55 56
    #elif __cplusplus >= 201103L && !__has_include(<initializer_list>)
      #warning "Your compiler supports C++11 but your C++ standard library does not.  If your "\
               "system has libc++ installed (as should be the case on e.g. Mac OSX), try adding "\
               "-stdlib=libc++ to your CXXFLAGS."
Kenton Varda's avatar
Kenton Varda committed
57 58 59 60 61 62
    #endif
  #else
    #if __GNUC__ < 4 || (__GNUC__ == 4 && __GNUC_MINOR__ < 7)
      #warning "This library requires at least GCC 4.7."
    #endif
  #endif
Kenton Varda's avatar
Kenton Varda committed
63 64
#elif defined(_MSC_VER)
  #warning "As of June 2013, Visual Studio's C++11 support was hopelessly behind what is needed to compile this code."
65 66 67 68 69
#else
  #warning "I don't recognize your compiler.  As of this writing, Clang and GCC are the only "\
           "known compilers with enough C++11 support for this library.  "\
           "#define KJ_NO_COMPILER_CHECK to make this warning go away."
#endif
Kenton Varda's avatar
Kenton Varda committed
70 71 72 73 74 75 76 77 78 79 80 81
#endif

// =======================================================================================

namespace kj {

typedef unsigned int uint;
typedef unsigned char byte;

// =======================================================================================
// Common macros, especially for common yet compiler-specific features.

Kenton Varda's avatar
Kenton Varda committed
82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97
// Detect whether RTTI and exceptions are enabled, assuming they are unless we have specific
// evidence to the contrary.  Clients can always define KJ_NO_RTTI or KJ_NO_EXCEPTIONS explicitly
// to override these checks.
#ifdef __GNUC__
  #if !defined(KJ_NO_RTTI) && !__GXX_RTTI
    #define KJ_NO_RTTI 1
  #endif
  #if !defined(KJ_NO_EXCEPTIONS) && !__EXCEPTIONS
    #define KJ_NO_EXCEPTIONS 1
  #endif
#elif defined(_MSC_VER)
  #if !defined(KJ_NO_RTTI) && !defined(_CPPRTTI)
    #define KJ_NO_RTTI 1
  #endif
  #if !defined(KJ_NO_EXCEPTIONS) && !defined(_CPPUNWIND)
    #define KJ_NO_EXCEPTIONS 1
98 99 100
  #endif
#endif

Kenton Varda's avatar
Kenton Varda committed
101 102 103
#define KJ_DISALLOW_COPY(classname) \
  classname(const classname&) = delete; \
  classname& operator=(const classname&) = delete
Kenton Varda's avatar
Kenton Varda committed
104
// Deletes the implicit copy constructor and assignment operator.
Kenton Varda's avatar
Kenton Varda committed
105

106 107
#define KJ_LIKELY(condition) __builtin_expect(condition, true)
#define KJ_UNLIKELY(condition) __builtin_expect(condition, false)
Kenton Varda's avatar
Kenton Varda committed
108 109 110 111
// Branch prediction macros.  Evaluates to the condition given, but also tells the compiler that we
// expect the condition to be true/false enough of the time that it's worth hard-coding branch
// prediction.

Kenton Varda's avatar
Kenton Varda committed
112
#if defined(NDEBUG) && !__NO_INLINE__
Kenton Varda's avatar
Kenton Varda committed
113 114 115 116 117 118 119
#define KJ_ALWAYS_INLINE(prototype) inline prototype __attribute__((always_inline))
// Force a function to always be inlined.  Apply only to the prototype, not to the definition.
#else
#define KJ_ALWAYS_INLINE(prototype) inline prototype
// Don't force inline in debug mode.
#endif

120 121
#define KJ_NORETURN __attribute__((noreturn))
#define KJ_UNUSED __attribute__((unused))
Kenton Varda's avatar
Kenton Varda committed
122 123

#if __clang__
124
#define KJ_UNUSED_MEMBER __attribute__((unused))
Kenton Varda's avatar
Kenton Varda committed
125 126
// Inhibits "unused" warning for member variables.  Only Clang produces such a warning, while GCC
// complains if the attribute is set on members.
Kenton Varda's avatar
Kenton Varda committed
127
#else
Kenton Varda's avatar
Kenton Varda committed
128
#define KJ_UNUSED_MEMBER
Kenton Varda's avatar
Kenton Varda committed
129 130
#endif

131
namespace _ {  // private
Kenton Varda's avatar
Kenton Varda committed
132

Kenton Varda's avatar
Kenton Varda committed
133
void inlineRequireFailure(
Kenton Varda's avatar
Kenton Varda committed
134 135 136
    const char* file, int line, const char* expectation, const char* macroArgs,
    const char* message = nullptr) KJ_NORETURN;

Kenton Varda's avatar
Kenton Varda committed
137 138
void unreachable() KJ_NORETURN;

139
}  // namespace _ (private)
Kenton Varda's avatar
Kenton Varda committed
140

Kenton Varda's avatar
Kenton Varda committed
141 142 143 144
#ifdef NDEBUG
#define KJ_IREQUIRE(condition, ...)
#else
#define KJ_IREQUIRE(condition, ...) \
145
    if (KJ_LIKELY(condition)); else ::kj::_::inlineRequireFailure( \
Kenton Varda's avatar
Kenton Varda committed
146
        __FILE__, __LINE__, #condition, #__VA_ARGS__, ##__VA_ARGS__)
147
// Version of KJ_REQUIRE() which is safe to use in headers that are #included by users.  Used to
Kenton Varda's avatar
Kenton Varda committed
148
// check preconditions inside inline methods.  KJ_IREQUIRE is particularly useful in that
Kenton Varda's avatar
Kenton Varda committed
149 150 151 152
// it will be enabled depending on whether the application is compiled in debug mode rather than
// whether libkj is.
#endif

Kenton Varda's avatar
Kenton Varda committed
153 154 155 156 157 158 159 160 161 162
#define KJ_UNREACHABLE ::kj::_::unreachable();
// Put this on code paths that cannot be reached to suppress compiler warnings about missing
// returns.

#if __clang__
#define KJ_CLANG_KNOWS_THIS_IS_UNREACHABLE_BUT_GCC_DOESNT
#else
#define KJ_CLANG_KNOWS_THIS_IS_UNREACHABLE_BUT_GCC_DOESNT KJ_UNREACHABLE
#endif

Kenton Varda's avatar
Kenton Varda committed
163 164 165 166 167 168 169 170 171 172 173 174
// #define KJ_STACK_ARRAY(type, name, size, minStack, maxStack)
//
// Allocate an array, preferably on the stack, unless it is too big.  On GCC this will use
// variable-sized arrays.  For other compilers we could just use a fixed-size array.  `minStack`
// is the stack array size to use if variable-width arrays are not supported.  `maxStack` is the
// maximum stack array size if variable-width arrays *are* supported.
#if __clang__
#define KJ_STACK_ARRAY(type, name, size, minStack, maxStack) \
  size_t name##_size = (size); \
  bool name##_isOnStack = name##_size <= (minStack); \
  type name##_stack[minStack]; \
  ::kj::Array<type> name##_heap = name##_isOnStack ? \
Kenton Varda's avatar
Kenton Varda committed
175
      nullptr : kj::heapArray<type>(name##_size); \
Kenton Varda's avatar
Kenton Varda committed
176 177 178 179 180 181 182 183
  ::kj::ArrayPtr<type> name = name##_isOnStack ? \
      kj::arrayPtr(name##_stack, name##_size) : name##_heap
#else
#define KJ_STACK_ARRAY(type, name, size, minStack, maxStack) \
  size_t name##_size = (size); \
  bool name##_isOnStack = name##_size <= (maxStack); \
  type name##_stack[name##_isOnStack ? size : 0]; \
  ::kj::Array<type> name##_heap = name##_isOnStack ? \
Kenton Varda's avatar
Kenton Varda committed
184
      nullptr : kj::heapArray<type>(name##_size); \
Kenton Varda's avatar
Kenton Varda committed
185 186 187 188
  ::kj::ArrayPtr<type> name = name##_isOnStack ? \
      kj::arrayPtr(name##_stack, name##_size) : name##_heap
#endif

189 190
#define KJ_ARRAY_SIZE(arr) (sizeof(arr) / sizeof(arr[0]))

191 192 193 194 195 196
#define KJ_CONCAT_(x, y) x##y
#define KJ_CONCAT(x, y) KJ_CONCAT_(x, y)
#define KJ_UNIQUE_NAME(prefix) KJ_CONCAT(prefix, __LINE__)
// Create a unique identifier name.  We use concatenate __LINE__ rather than __COUNTER__ so that
// the name can be used multiple times in the same macro.

Kenton Varda's avatar
Kenton Varda committed
197 198 199
// =======================================================================================
// Template metaprogramming helpers.

200 201 202 203
template <typename T> struct NoInfer_ { typedef T Type; };
template <typename T> using NoInfer = typename NoInfer_<T>::Type;
// Use NoInfer<T>::Type in place of T for a template function parameter to prevent inference of
// the type based on the parameter value.
Kenton Varda's avatar
Kenton Varda committed
204

205 206 207 208
template <typename T> struct RemoveConst_ { typedef T Type; };
template <typename T> struct RemoveConst_<const T> { typedef T Type; };
template <typename T> using RemoveConst = typename RemoveConst_<T>::Type;

Kenton Varda's avatar
Kenton Varda committed
209 210 211 212 213
template <typename> struct IsLvalueReference_ { static constexpr bool value = false; };
template <typename T> struct IsLvalueReference_<T&> { static constexpr bool value = true; };
template <typename T>
inline constexpr bool isLvalueReference() { return IsLvalueReference_<T>::value; }

Kenton Varda's avatar
Kenton Varda committed
214 215 216 217
template <typename T> struct Decay_ { typedef T Type; };
template <typename T> struct Decay_<T&> { typedef typename Decay_<T>::Type Type; };
template <typename T> struct Decay_<T&&> { typedef typename Decay_<T>::Type Type; };
template <typename T> struct Decay_<T[]> { typedef typename Decay_<T*>::Type Type; };
218 219 220
template <typename T> struct Decay_<const T[]> { typedef typename Decay_<const T*>::Type Type; };
template <typename T, size_t s> struct Decay_<T[s]> { typedef typename Decay_<T*>::Type Type; };
template <typename T, size_t s> struct Decay_<const T[s]> { typedef typename Decay_<const T*>::Type Type; };
Kenton Varda's avatar
Kenton Varda committed
221 222 223 224
template <typename T> struct Decay_<const T> { typedef typename Decay_<T>::Type Type; };
template <typename T> struct Decay_<volatile T> { typedef typename Decay_<T>::Type Type; };
template <typename T> using Decay = typename Decay_<T>::Type;

Kenton Varda's avatar
Kenton Varda committed
225 226 227 228 229 230 231 232
template <bool b> struct EnableIf_;
template <> struct EnableIf_<true> { typedef void Type; };
template <bool b> using EnableIf = typename EnableIf_<b>::Type;
// Use like:
//
//     template <typename T, typename = EnableIf<isValid<T>()>
//     void func(T&& t);

Kenton Varda's avatar
Kenton Varda committed
233 234 235 236 237
template <typename T>
T instance() noexcept;
// Like std::declval, but doesn't transform T into an rvalue reference.  If you want that, specify
// instance<T&&>().

238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275
struct DisallowConstCopy {
  // Inherit from this, or declare a member variable of this type, to prevent the class from being
  // copyable from a const reference -- instead, it will only be copyable from non-const references.
  // This is useful for enforcing transitive constness of contained pointers.
  //
  // For example, say you have a type T which contains a pointer.  T has non-const methods which
  // modify the value at that pointer, but T's const methods are designed to allow reading only.
  // Unfortunately, if T has a regular copy constructor, someone can simply make a copy of T and
  // then use it to modify the pointed-to value.  However, if T inherits DisallowConstCopy, then
  // callers will only be able to copy non-const instances of T.  Ideally, there is some
  // parallel type ImmutableT which is like a version of T that only has const methods, and can
  // be copied from a const T.
  //
  // Note that due to C++ rules about implicit copy constructors and assignment operators, any
  // type that contains or inherits from a type that disallows const copies will also automatically
  // disallow const copies.  Hey, cool, that's exactly what we want.

  DisallowConstCopy() = default;
  DisallowConstCopy(DisallowConstCopy&);
  DisallowConstCopy(DisallowConstCopy&&) = default;
  DisallowConstCopy& operator=(DisallowConstCopy&);
  DisallowConstCopy& operator=(DisallowConstCopy&&) = default;
};

// Apparently these cannot be defaulted inside the class due to some obscure C++ rule.
inline DisallowConstCopy::DisallowConstCopy(DisallowConstCopy&) = default;
inline DisallowConstCopy& DisallowConstCopy::operator=(DisallowConstCopy&) = default;

template <typename T>
struct DisallowConstCopyIfNotConst: public DisallowConstCopy {
  // Inherit from this when implementing a template that contains a pointer to T and which should
  // enforce transitive constness.  If T is a const type, this has no effect.  Otherwise, it is
  // an alias for DisallowConstCopy.
};

template <typename T>
struct DisallowConstCopyIfNotConst<const T> {};

276 277 278 279
template <typename T> struct IsConst_ { static constexpr bool value = false; };
template <typename T> struct IsConst_<const T> { static constexpr bool value = true; };
template <typename T> constexpr bool isConst() { return IsConst_<T>::value; }

280 281 282 283 284 285 286
template <typename T> struct EnableIfNotConst_ { typedef T Type; };
template <typename T> struct EnableIfNotConst_<const T>;
template <typename T> using EnableIfNotConst = typename EnableIfNotConst_<T>::Type;

template <typename T> struct EnableIfConst_;
template <typename T> struct EnableIfConst_<const T> { typedef T Type; };
template <typename T> using EnableIfConst = typename EnableIfConst_<T>::Type;
Kenton Varda's avatar
Kenton Varda committed
287

288 289 290
template <typename T> struct RemoveConstOrDisable_ { struct Type; };
template <typename T> struct RemoveConstOrDisable_<const T> { typedef T Type; };
template <typename T> using RemoveConstOrDisable = typename RemoveConstOrDisable_<T>::Type;
291

292 293 294 295
template <typename T> struct IsReference_ { static constexpr bool value = false; };
template <typename T> struct IsReference_<T&> { static constexpr bool value = true; };
template <typename T> constexpr bool isReference() { return IsReference_<T>::value; }

Kenton Varda's avatar
Kenton Varda committed
296 297 298 299 300 301 302 303 304
// =======================================================================================
// Equivalents to std::move() and std::forward(), since these are very commonly needed and the
// std header <utility> pulls in lots of other stuff.
//
// We use abbreviated names mv and fwd because these helpers (especially mv) are so commonly used
// that the cost of typing more letters outweighs the cost of being slightly harder to understand
// when first encountered.

template<typename T> constexpr T&& mv(T& t) noexcept { return static_cast<T&&>(t); }
305
template<typename T> constexpr T&& fwd(NoInfer<T>& t) noexcept { return static_cast<T&&>(t); }
Kenton Varda's avatar
Kenton Varda committed
306

307
template <typename T, typename U>
308
inline constexpr auto min(T&& a, U&& b) -> decltype(a < b ? a : b) { return a < b ? a : b; }
309
template <typename T, typename U>
310
inline constexpr auto max(T&& a, U&& b) -> decltype(a > b ? a : b) { return a > b ? a : b; }
311

312 313 314 315 316 317 318 319 320
// =======================================================================================
// Manually invoking constructors and destructors
//
// ctor(x, ...) and dtor(x) invoke x's constructor or destructor, respectively.

// We want placement new, but we don't want to #include <new>.  operator new cannot be defined in
// a namespace, and defining it globally conflicts with the definition in <new>.  So we have to
// define a dummy type and an operator new that uses it.

321
namespace _ {  // private
322
struct PlacementNew {};
323
}  // namespace _ (private)
324 325
} // namespace kj

326
inline void* operator new(size_t, kj::_::PlacementNew, void* __p) noexcept {
327 328 329 330 331 332 333
  return __p;
}

namespace kj {

template <typename T, typename... Params>
inline void ctor(T& location, Params&&... params) {
334
  new (_::PlacementNew(), &location) T(kj::fwd<Params>(params)...);
335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368
}

template <typename T>
inline void dtor(T& location) {
  location.~T();
}

// =======================================================================================
// Maybe
//
// Use in cases where you want to indicate that a value may be null.  Using Maybe<T&> instead of T*
// forces the caller to handle the null case in order to satisfy the compiler, thus reliably
// preventing null pointer dereferences at runtime.
//
// Maybe<T> can be implicitly constructed from T and from nullptr.  Additionally, it can be
// implicitly constructed from T*, in which case the pointer is checked for nullness at runtime.
// To read the value of a Maybe<T>, do:
//
//    KJ_IF_MAYBE(value, someFuncReturningMaybe()) {
//      doSomething(*value);
//    } else {
//      maybeWasNull();
//    }
//
// KJ_IF_MAYBE's first parameter is a variable name which will be defined within the following
// block.  The variable will behave like a (guaranteed non-null) pointer to the Maybe's value,
// though it may or may not actually be a pointer.
//
// Note that Maybe<T&> actually just wraps a pointer, whereas Maybe<T> wraps a T and a boolean
// indicating nullness.

template <typename T>
class Maybe;

369
namespace _ {  // private
370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388

template <typename T>
class NullableValue {
  // Class whose interface behaves much like T*, but actually contains an instance of T and a
  // boolean flag indicating nullness.

public:
  inline NullableValue(NullableValue&& other) noexcept(noexcept(T(instance<T&&>())))
      : isSet(other.isSet) {
    if (isSet) {
      ctor(value, kj::mv(other.value));
    }
  }
  inline NullableValue(const NullableValue& other)
      : isSet(other.isSet) {
    if (isSet) {
      ctor(value, other.value);
    }
  }
389
  inline ~NullableValue() noexcept(noexcept(instance<T&>().~T())) {
390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407
    if (isSet) {
      dtor(value);
    }
  }

  inline T& operator*() { return value; }
  inline const T& operator*() const { return value; }
  inline T* operator->() { return &value; }
  inline const T* operator->() const { return &value; }
  inline operator T*() { return isSet ? &value : nullptr; }
  inline operator const T*() const { return isSet ? &value : nullptr; }

private:  // internal interface used by friends only
  inline NullableValue() noexcept: isSet(false) {}
  inline NullableValue(T&& t) noexcept(noexcept(T(instance<T&&>())))
      : isSet(true) {
    ctor(value, kj::mv(t));
  }
408 409 410 411
  inline NullableValue(T& t)
      : isSet(true) {
    ctor(value, t);
  }
412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455
  inline NullableValue(const T& t)
      : isSet(true) {
    ctor(value, t);
  }
  inline NullableValue(const T* t)
      : isSet(t != nullptr) {
    if (isSet) ctor(value, *t);
  }
  template <typename U>
  inline NullableValue(NullableValue<U>&& other) noexcept(noexcept(T(instance<U&&>())))
      : isSet(other.isSet) {
    if (isSet) {
      ctor(value, kj::mv(other.value));
    }
  }
  template <typename U>
  inline NullableValue(const NullableValue<U>& other)
      : isSet(other.isSet) {
    if (isSet) {
      ctor(value, other.value);
    }
  }
  template <typename U>
  inline NullableValue(const NullableValue<U&>& other)
      : isSet(other.isSet) {
    if (isSet) {
      ctor(value, *other.ptr);
    }
  }
  inline NullableValue(decltype(nullptr)): isSet(false) {}

  inline NullableValue& operator=(NullableValue&& other) {
    if (&other != this) {
      if (isSet) {
        dtor(value);
      }
      isSet = other.isSet;
      if (isSet) {
        ctor(value, kj::mv(other.value));
      }
    }
    return *this;
  }

456 457 458 459 460 461 462 463 464 465 466 467 468
  inline NullableValue& operator=(NullableValue& other) {
    if (&other != this) {
      if (isSet) {
        dtor(value);
      }
      isSet = other.isSet;
      if (isSet) {
        ctor(value, other.value);
      }
    }
    return *this;
  }

469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506
  inline NullableValue& operator=(const NullableValue& other) {
    if (&other != this) {
      if (isSet) {
        dtor(value);
      }
      isSet = other.isSet;
      if (isSet) {
        ctor(value, other.value);
      }
    }
    return *this;
  }

  inline bool operator==(decltype(nullptr)) const { return !isSet; }
  inline bool operator!=(decltype(nullptr)) const { return isSet; }

private:
  bool isSet;
  union {
    T value;
  };

  friend class kj::Maybe<T>;
  template <typename U>
  friend NullableValue<U>&& readMaybe(Maybe<U>&& maybe);
};

template <typename T>
inline NullableValue<T>&& readMaybe(Maybe<T>&& maybe) { return kj::mv(maybe.ptr); }
template <typename T>
inline T* readMaybe(Maybe<T>& maybe) { return maybe.ptr; }
template <typename T>
inline const T* readMaybe(const Maybe<T>& maybe) { return maybe.ptr; }
template <typename T>
inline T* readMaybe(Maybe<T&>&& maybe) { return maybe.ptr; }
template <typename T>
inline T* readMaybe(const Maybe<T&>& maybe) { return maybe.ptr; }

507
}  // namespace _ (private)
508

509
#define KJ_IF_MAYBE(name, exp) if (auto name = ::kj::_::readMaybe(exp))
510 511 512

template <typename T>
class Maybe {
513 514 515 516
  // A T, or nullptr.

  // IF YOU CHANGE THIS CLASS:  Note that there is a specialization of it in memory.h.

517 518 519
public:
  Maybe(): ptr(nullptr) {}
  Maybe(T&& t) noexcept(noexcept(T(instance<T&&>()))): ptr(kj::mv(t)) {}
520
  Maybe(T& t): ptr(t) {}
521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541
  Maybe(const T& t): ptr(t) {}
  Maybe(const T* t) noexcept: ptr(t) {}
  Maybe(Maybe&& other) noexcept(noexcept(T(instance<T&&>()))): ptr(kj::mv(other.ptr)) {}
  Maybe(const Maybe& other): ptr(other.ptr) {}

  template <typename U>
  Maybe(Maybe<U>&& other) noexcept(noexcept(T(instance<U&&>()))) {
    KJ_IF_MAYBE(val, kj::mv(other)) {
      ptr = *val;
    }
  }
  template <typename U>
  Maybe(const Maybe<U>& other) {
    KJ_IF_MAYBE(val, other) {
      ptr = *val;
    }
  }

  Maybe(decltype(nullptr)) noexcept: ptr(nullptr) {}

  inline Maybe& operator=(Maybe&& other) { ptr = kj::mv(other.ptr); return *this; }
542
  inline Maybe& operator=(Maybe& other) { ptr = other.ptr; return *this; }
543 544 545 546 547
  inline Maybe& operator=(const Maybe& other) { ptr = other.ptr; return *this; }

  inline bool operator==(decltype(nullptr)) const { return ptr == nullptr; }
  inline bool operator!=(decltype(nullptr)) const { return ptr != nullptr; }

548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567
  template <typename Func>
  auto map(Func&& f) -> Maybe<decltype(f(instance<T&>()))> {
    if (ptr == nullptr) {
      return nullptr;
    } else {
      return f(*ptr);
    }
  }

  template <typename Func>
  auto map(Func&& f) const -> Maybe<decltype(f(instance<const T&>()))> {
    if (ptr == nullptr) {
      return nullptr;
    } else {
      return f(*ptr);
    }
  }

  // TODO(someday):  Once it's safe to require GCC 4.8, use ref qualifiers to provide a version of
  //   map() that uses move semantics if *this is an rvalue.
568 569

private:
570
  _::NullableValue<T> ptr;
571 572 573 574

  template <typename U>
  friend class Maybe;
  template <typename U>
575
  friend _::NullableValue<U>&& _::readMaybe(Maybe<U>&& maybe);
576
  template <typename U>
577
  friend U* _::readMaybe(Maybe<U>& maybe);
578
  template <typename U>
579
  friend const U* _::readMaybe(const Maybe<U>& maybe);
580 581 582
};

template <typename T>
583
class Maybe<T&>: public DisallowConstCopyIfNotConst<T> {
584
public:
585
  Maybe() noexcept: ptr(nullptr) {}
586 587 588
  Maybe(T& t) noexcept: ptr(&t) {}
  Maybe(T* t) noexcept: ptr(t) {}

589 590 591 592 593
  template <typename U>
  inline Maybe(Maybe<U&>& other) noexcept: ptr(other.ptr) {}
  template <typename U>
  inline Maybe(const Maybe<const U&>& other) noexcept: ptr(other.ptr) {}
  inline Maybe(decltype(nullptr)) noexcept: ptr(nullptr) {}
594

595 596 597 598 599 600
  inline Maybe& operator=(T& other) noexcept { ptr = &other; }
  inline Maybe& operator=(T* other) noexcept { ptr = other; }
  template <typename U>
  inline Maybe& operator=(Maybe<U&>& other) noexcept { ptr = other.ptr; return *this; }
  template <typename U>
  inline Maybe& operator=(const Maybe<const U&>& other) noexcept { ptr = other.ptr; return *this; }
601 602 603 604

  inline bool operator==(decltype(nullptr)) const { return ptr == nullptr; }
  inline bool operator!=(decltype(nullptr)) const { return ptr != nullptr; }

605 606 607 608 609 610 611 612
  template <typename Func>
  auto map(Func&& f) -> Maybe<decltype(f(instance<T&>()))> {
    if (ptr == nullptr) {
      return nullptr;
    } else {
      return f(*ptr);
    }
  }
613 614 615 616 617 618 619

private:
  T* ptr;

  template <typename U>
  friend class Maybe;
  template <typename U>
620
  friend U* _::readMaybe(Maybe<U&>&& maybe);
621
  template <typename U>
622
  friend U* _::readMaybe(const Maybe<U&>& maybe);
623 624
};

625 626 627 628 629 630
// =======================================================================================
// ArrayPtr
//
// So common that we put it in common.h rather than array.h.

template <typename T>
631
class ArrayPtr: public DisallowConstCopyIfNotConst<T> {
632 633 634 635 636 637 638 639 640
  // A pointer to an array.  Includes a size.  Like any pointer, it doesn't own the target data,
  // and passing by value only copies the pointer, not the target.

public:
  inline constexpr ArrayPtr(): ptr(nullptr), size_(0) {}
  inline constexpr ArrayPtr(decltype(nullptr)): ptr(nullptr), size_(0) {}
  inline constexpr ArrayPtr(T* ptr, size_t size): ptr(ptr), size_(size) {}
  inline constexpr ArrayPtr(T* begin, T* end): ptr(begin), size_(end - begin) {}

Kenton Varda's avatar
Kenton Varda committed
641 642 643 644
  inline operator ArrayPtr<const T>() const {
    return ArrayPtr<const T>(ptr, size_);
  }
  inline ArrayPtr<const T> asConst() const {
645 646 647 648
    return ArrayPtr<const T>(ptr, size_);
  }

  inline size_t size() const { return size_; }
649 650 651 652 653
  inline const T& operator[](size_t index) const {
    KJ_IREQUIRE(index < size_, "Out-of-bounds ArrayPtr access.");
    return ptr[index];
  }
  inline T& operator[](size_t index) {
Kenton Varda's avatar
Kenton Varda committed
654
    KJ_IREQUIRE(index < size_, "Out-of-bounds ArrayPtr access.");
655 656 657
    return ptr[index];
  }

658 659 660 661 662 663 664 665
  inline T* begin() { return ptr; }
  inline T* end() { return ptr + size_; }
  inline T& front() { return *ptr; }
  inline T& back() { return *(ptr + size_ - 1); }
  inline const T* begin() const { return ptr; }
  inline const T* end() const { return ptr + size_; }
  inline const T& front() const { return *ptr; }
  inline const T& back() const { return *(ptr + size_ - 1); }
666

667 668 669 670 671
  inline ArrayPtr<const T> slice(size_t start, size_t end) const {
    KJ_IREQUIRE(start <= end && end <= size_, "Out-of-bounds ArrayPtr::slice().");
    return ArrayPtr<const T>(ptr + start, end - start);
  }
  inline ArrayPtr slice(size_t start, size_t end) {
Kenton Varda's avatar
Kenton Varda committed
672
    KJ_IREQUIRE(start <= end && end <= size_, "Out-of-bounds ArrayPtr::slice().");
673 674 675
    return ArrayPtr(ptr + start, end - start);
  }

676 677
  inline bool operator==(decltype(nullptr)) const { return size_ == 0; }
  inline bool operator!=(decltype(nullptr)) const { return size_ != 0; }
678

Kenton Varda's avatar
Kenton Varda committed
679 680 681 682 683 684 685 686 687
  inline bool operator==(const ArrayPtr& other) const {
    if (size_ != other.size_) return false;
    for (size_t i = 0; i < size_; i++) {
      if (ptr[i] != other[i]) return false;
    }
    return true;
  }
  inline bool operator!=(const ArrayPtr& other) const { return !(*this == other); }

688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704
private:
  T* ptr;
  size_t size_;
};

template <typename T>
inline constexpr ArrayPtr<T> arrayPtr(T* ptr, size_t size) {
  // Use this function to construct ArrayPtrs without writing out the type name.
  return ArrayPtr<T>(ptr, size);
}

template <typename T>
inline constexpr ArrayPtr<T> arrayPtr(T* begin, T* end) {
  // Use this function to construct ArrayPtrs without writing out the type name.
  return ArrayPtr<T>(begin, end);
}

Kenton Varda's avatar
Kenton Varda committed
705
// =======================================================================================
706
// Casts
Kenton Varda's avatar
Kenton Varda committed
707 708

template <typename To, typename From>
709 710 711
To implicitCast(From&& from) {
  // `implicitCast<T>(value)` casts `value` to type `T` only if the conversion is implicit.  Useful
  // for e.g. resolving ambiguous overloads without sacrificing type-safety.
Kenton Varda's avatar
Kenton Varda committed
712 713 714 715
  return kj::fwd<From>(from);
}

template <typename To, typename From>
716
Maybe<To&> dynamicDowncastIfAvailable(From& from) {
Kenton Varda's avatar
Kenton Varda committed
717 718 719 720 721 722
  // If RTTI is disabled, always returns nullptr.  Otherwise, works like dynamic_cast.  Useful
  // in situations where dynamic_cast could allow an optimization, but isn't strictly necessary
  // for correctness.  It is highly recommended that you try to arrange all your dynamic_casts
  // this way, as a dynamic_cast that is necessary for correctness implies a flaw in the interface
  // design.

723 724 725
  // Force a compile error if To is not a subtype of From.  Cross-casting is rare; if it is needed
  // we should have a separate cast function like dynamicCrosscastIfAvailable().
  if (false) {
726
    kj::implicitCast<From*>(kj::implicitCast<To*>(nullptr));
727 728
  }

Kenton Varda's avatar
Kenton Varda committed
729 730 731
#if KJ_NO_RTTI
  return nullptr;
#else
732
  return dynamic_cast<To*>(&from);
Kenton Varda's avatar
Kenton Varda committed
733 734 735 736
#endif
}

template <typename To, typename From>
737
To& downcast(From& from) {
Kenton Varda's avatar
Kenton Varda committed
738 739 740 741 742 743
  // Down-cast a value to a sub-type, asserting that the cast is valid.  In opt mode this is a
  // static_cast, but in debug mode (when RTTI is enabled) a dynamic_cast will be used to verify
  // that the value really has the requested type.

  // Force a compile error if To is not a subtype of From.
  if (false) {
744
    kj::implicitCast<From*>(kj::implicitCast<To*>(nullptr));
Kenton Varda's avatar
Kenton Varda committed
745 746 747
  }

#if !KJ_NO_RTTI
748
  KJ_IREQUIRE(dynamic_cast<To*>(&from) != nullptr, "Value cannot be downcast() to requested type.");
Kenton Varda's avatar
Kenton Varda committed
749 750
#endif

751
  return static_cast<To&>(from);
Kenton Varda's avatar
Kenton Varda committed
752 753
}

754 755 756 757 758 759 760 761
// =======================================================================================
// Defer

namespace _ {  // private

template <typename Func>
class Deferred {
public:
762 763 764 765
  inline Deferred(Func func): func(func), canceled(false) {}
  inline ~Deferred() { if (!canceled) func(); }
  KJ_DISALLOW_COPY(Deferred);

Kenton Varda's avatar
Kenton Varda committed
766
  // This move constructor is usually optimized away by the compiler.
767
  inline Deferred(Deferred&& other): func(kj::mv(other.func)), canceled(false) {
768 769
    other.canceled = true;
  }
770 771
private:
  Func func;
772
  bool canceled;
773 774
};

Kenton Varda's avatar
Kenton Varda committed
775 776
}  // namespace _ (private)

777
template <typename Func>
Kenton Varda's avatar
Kenton Varda committed
778 779 780 781 782 783 784
_::Deferred<Decay<Func>> defer(Func&& func) {
  // Returns an object which will invoke the given functor in its destructor.  The object is not
  // copyable but is movable with the semantics you'd expect.  Since the return type is private,
  // you need to assign to an `auto` variable.
  //
  // The KJ_DEFER macro provides slightly more convenient syntax for the common case where you
  // want some code to run at function exit.
785

Kenton Varda's avatar
Kenton Varda committed
786 787
  return _::Deferred<Decay<Func>>(kj::fwd<Func>(func));
}
788

Kenton Varda's avatar
Kenton Varda committed
789 790
#define KJ_DEFER(code) auto KJ_UNIQUE_NAME(_kjDefer) = ::kj::defer([&](){code;})
// Run the given code when the function exits, whether by return or exception.
791

Kenton Varda's avatar
Kenton Varda committed
792 793 794
}  // namespace kj

#endif  // KJ_COMMON_H_