common.h 52.5 KB
Newer Older
Kenton Varda's avatar
Kenton Varda committed
1 2
// Copyright (c) 2013-2014 Sandstorm Development Group, Inc. and contributors
// Licensed under the MIT License:
Kenton Varda's avatar
Kenton Varda committed
3
//
Kenton Varda's avatar
Kenton Varda committed
4 5 6 7 8 9
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
Kenton Varda's avatar
Kenton Varda committed
10
//
Kenton Varda's avatar
Kenton Varda committed
11 12
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
Kenton Varda's avatar
Kenton Varda committed
13
//
Kenton Varda's avatar
Kenton Varda committed
14 15 16 17 18 19 20
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
Kenton Varda's avatar
Kenton Varda committed
21 22 23 24 25 26 27 28

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

#ifndef KJ_COMMON_H_
#define KJ_COMMON_H_

29 30 31 32
#if defined(__GNUC__) && !KJ_HEADER_WARNINGS
#pragma GCC system_header
#endif

33
#ifndef KJ_NO_COMPILER_CHECK
34
#if __cplusplus < 201103L && !__CDT_PARSER__ && !_MSC_VER
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
#elif defined(_MSC_VER)
64 65 66
  #if _MSC_VER < 1900
    #error "You need Visual Studio 2015 or better to compile this code."
  #endif
67 68 69 70 71
#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
72 73
#endif

74 75 76
#include <stddef.h>
#include <initializer_list>

77 78 79 80 81 82 83 84
#if __linux__ && __cplusplus > 201200L
// Hack around stdlib bug with C++14 that exists on some Linux systems.
// Apparently in this mode the C library decides not to define gets() but the C++ library still
// tries to import it into the std namespace. This bug has been fixed at the source but is still
// widely present in the wild e.g. on Ubuntu 14.04.
#undef _GLIBCXX_HAVE_GETS
#endif

85
#if defined(_MSC_VER)
86 87 88
#ifndef NOMINMAX
#define NOMINMAX 1
#endif
89 90 91
#include <intrin.h>  // __popcnt
#endif

Kenton Varda's avatar
Kenton Varda committed
92 93 94 95 96 97 98 99 100 101
// =======================================================================================

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
102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117
// 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
118 119 120
  #endif
#endif

121 122 123
#if !defined(KJ_DEBUG) && !defined(KJ_NDEBUG)
// Heuristically decide whether to enable debug mode.  If DEBUG or NDEBUG is defined, use that.
// Otherwise, fall back to checking whether optimization is enabled.
124
#if defined(DEBUG) || defined(_DEBUG)
125
#define KJ_DEBUG
126 127 128 129 130 131 132
#elif defined(NDEBUG)
#define KJ_NDEBUG
#elif __OPTIMIZE__
#define KJ_NDEBUG
#else
#define KJ_DEBUG
#endif
133 134
#endif

Kenton Varda's avatar
Kenton Varda committed
135 136 137
#define KJ_DISALLOW_COPY(classname) \
  classname(const classname&) = delete; \
  classname& operator=(const classname&) = delete
Kenton Varda's avatar
Kenton Varda committed
138
// Deletes the implicit copy constructor and assignment operator.
Kenton Varda's avatar
Kenton Varda committed
139

140
#ifdef __GNUC__
141 142
#define KJ_LIKELY(condition) __builtin_expect(condition, true)
#define KJ_UNLIKELY(condition) __builtin_expect(condition, false)
Kenton Varda's avatar
Kenton Varda committed
143 144 145
// 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.
146 147 148 149
#else
#define KJ_LIKELY(condition) (condition)
#define KJ_UNLIKELY(condition) (condition)
#endif
Kenton Varda's avatar
Kenton Varda committed
150

151
#if defined(KJ_DEBUG) || __NO_INLINE__
152
#define KJ_ALWAYS_INLINE(...) inline __VA_ARGS__
Kenton Varda's avatar
Kenton Varda committed
153
// Don't force inline in debug mode.
154
#else
155
#if defined(_MSC_VER)
156
#define KJ_ALWAYS_INLINE(...) __forceinline __VA_ARGS__
157
#else
158
#define KJ_ALWAYS_INLINE(...) inline __VA_ARGS__ __attribute__((always_inline))
159
#endif
160
// Force a function to always be inlined.  Apply only to the prototype, not to the definition.
Kenton Varda's avatar
Kenton Varda committed
161 162
#endif

Kenton Varda's avatar
Kenton Varda committed
163 164 165 166 167 168
#if defined(_MSC_VER)
#define KJ_NOINLINE __declspec(noinline)
#else
#define KJ_NOINLINE __attribute__((noinline))
#endif

169 170
#if defined(_MSC_VER)
#define KJ_NORETURN(prototype) __declspec(noreturn) prototype
171 172 173 174 175
#define KJ_UNUSED
#define KJ_WARN_UNUSED_RESULT
// TODO(msvc): KJ_WARN_UNUSED_RESULT can use _Check_return_ on MSVC, but it's a prefix, so
//   wrapping the whole prototype is needed. http://msdn.microsoft.com/en-us/library/jj159529.aspx
//   Similarly, KJ_UNUSED could use __pragma(warning(suppress:...)), but again that's a prefix.
176 177
#else
#define KJ_NORETURN(prototype) prototype __attribute__((noreturn))
178
#define KJ_UNUSED __attribute__((unused))
179
#define KJ_WARN_UNUSED_RESULT __attribute__((warn_unused_result))
180
#endif
181

Kenton Varda's avatar
Kenton Varda committed
182
#if __clang__
183
#define KJ_UNUSED_MEMBER __attribute__((unused))
Kenton Varda's avatar
Kenton Varda committed
184 185
// 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
186
#else
Kenton Varda's avatar
Kenton Varda committed
187
#define KJ_UNUSED_MEMBER
Kenton Varda's avatar
Kenton Varda committed
188 189
#endif

190 191 192
#if __clang__
#define KJ_DEPRECATED(reason) \
    __attribute__((deprecated(reason)))
193 194
#define KJ_UNAVAILABLE(reason) \
    __attribute__((unavailable(reason)))
195
#elif __GNUC__
196 197
#define KJ_DEPRECATED(reason) \
    __attribute__((deprecated))
198
#define KJ_UNAVAILABLE(reason)
199 200
#else
#define KJ_DEPRECATED(reason)
201
#define KJ_UNAVAILABLE(reason)
202
// TODO(msvc): Again, here, MSVC prefers a prefix, __declspec(deprecated).
203 204
#endif

205
namespace _ {  // private
Kenton Varda's avatar
Kenton Varda committed
206

207
KJ_NORETURN(void inlineRequireFailure(
Kenton Varda's avatar
Kenton Varda committed
208
    const char* file, int line, const char* expectation, const char* macroArgs,
209
    const char* message = nullptr));
Kenton Varda's avatar
Kenton Varda committed
210

211
KJ_NORETURN(void unreachable());
Kenton Varda's avatar
Kenton Varda committed
212

213
}  // namespace _ (private)
Kenton Varda's avatar
Kenton Varda committed
214

215
#ifdef KJ_DEBUG
216 217 218
#if _MSC_VER
#define KJ_IREQUIRE(condition, ...) \
    if (KJ_LIKELY(condition)); else ::kj::_::inlineRequireFailure( \
219
        __FILE__, __LINE__, #condition, "" #__VA_ARGS__, __VA_ARGS__)
220 221 222 223 224
// Version of KJ_DREQUIRE() which is safe to use in headers that are #included by users.  Used to
// check preconditions inside inline methods.  KJ_IREQUIRE is particularly useful in that
// it will be enabled depending on whether the application is compiled in debug mode rather than
// whether libkj is.
#else
Kenton Varda's avatar
Kenton Varda committed
225
#define KJ_IREQUIRE(condition, ...) \
226
    if (KJ_LIKELY(condition)); else ::kj::_::inlineRequireFailure( \
Kenton Varda's avatar
Kenton Varda committed
227
        __FILE__, __LINE__, #condition, #__VA_ARGS__, ##__VA_ARGS__)
228
// Version of KJ_DREQUIRE() which is safe to use in headers that are #included by users.  Used to
Kenton Varda's avatar
Kenton Varda committed
229
// check preconditions inside inline methods.  KJ_IREQUIRE is particularly useful in that
Kenton Varda's avatar
Kenton Varda committed
230 231
// it will be enabled depending on whether the application is compiled in debug mode rather than
// whether libkj is.
232
#endif
233 234
#else
#define KJ_IREQUIRE(condition, ...)
Kenton Varda's avatar
Kenton Varda committed
235 236
#endif

237 238
#define KJ_IASSERT KJ_IREQUIRE

Kenton Varda's avatar
Kenton Varda committed
239 240 241 242 243 244 245 246 247 248
#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
249 250 251 252 253 254
// #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.
255
#if __GNUC__ && !__clang__
Kenton Varda's avatar
Kenton Varda committed
256 257
#define KJ_STACK_ARRAY(type, name, size, minStack, maxStack) \
  size_t name##_size = (size); \
258 259
  bool name##_isOnStack = name##_size <= (maxStack); \
  type name##_stack[name##_isOnStack ? size : 0]; \
Kenton Varda's avatar
Kenton Varda committed
260
  ::kj::Array<type> name##_heap = name##_isOnStack ? \
Kenton Varda's avatar
Kenton Varda committed
261
      nullptr : kj::heapArray<type>(name##_size); \
Kenton Varda's avatar
Kenton Varda committed
262 263 264 265 266
  ::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); \
267 268
  bool name##_isOnStack = name##_size <= (minStack); \
  type name##_stack[minStack]; \
Kenton Varda's avatar
Kenton Varda committed
269
  ::kj::Array<type> name##_heap = name##_isOnStack ? \
Kenton Varda's avatar
Kenton Varda committed
270
      nullptr : kj::heapArray<type>(name##_size); \
Kenton Varda's avatar
Kenton Varda committed
271 272 273 274
  ::kj::ArrayPtr<type> name = name##_isOnStack ? \
      kj::arrayPtr(name##_stack, name##_size) : name##_heap
#endif

275 276 277 278 279 280
#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.

281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306
#if _MSC_VER

#define KJ_CONSTEXPR(...) __VA_ARGS__
// Use in cases where MSVC barfs on constexpr. A replacement keyword (e.g. "const") can be
// provided, or just leave blank to remove the keyword entirely.
//
// TODO(msvc): Remove this hack once MSVC fully supports constexpr.

#ifndef __restrict__
#define __restrict__ __restrict
// TODO(msvc): Would it be better to define a KJ_RESTRICT macro?
#endif

#pragma warning(disable: 4521 4522)
// This warning complains when there are two copy constructors, one for a const reference and
// one for a non-const reference. It is often quite necessary to do this in wrapper templates,
// therefore this warning is dumb and we disable it.

#pragma warning(disable: 4458)
// Warns when a parameter name shadows a class member. Unfortunately my code does this a lot,
// since I don't use a special name format for members.

#else  // _MSC_VER
#define KJ_CONSTEXPR(...) constexpr
#endif

Kenton Varda's avatar
Kenton Varda committed
307 308 309
// =======================================================================================
// Template metaprogramming helpers.

310 311 312 313
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
314

315 316 317 318
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
319 320 321 322 323
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
324 325 326 327
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; };
328 329 330
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
331 332 333 334
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
335 336 337 338 339 340 341 342
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);

343 344 345 346
template <typename...> struct VoidSfinae_ { using Type = void; };
template <typename... Ts> using VoidSfinae = typename VoidSfinae_<Ts...>::Type;
// Note: VoidSfinae is std::void_t from C++17.

Kenton Varda's avatar
Kenton Varda committed
347 348 349 350 351
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&&>().

352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368
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.

369 370 371 372 373 374 375 376 377 378
#if CAPNP_DEBUG_TYPES
  // Alas! Declaring a defaulted non-const copy constructor tickles a bug which causes GCC and
  // Clang to disagree on ABI, using different calling conventions to pass this type, leading to
  // immediate segfaults. See:
  //     https://bugs.llvm.org/show_bug.cgi?id=23764
  //     https://gcc.gnu.org/bugzilla/show_bug.cgi?id=58074
  //
  // Because of this, we can't use this technique. We guard it by CAPNP_DEBUG_TYPES so that it
  // still applies to the Cap'n Proto developers during internal testing.

379
  DisallowConstCopy() = default;
380
  DisallowConstCopy(DisallowConstCopy&) = default;
381
  DisallowConstCopy(DisallowConstCopy&&) = default;
382
  DisallowConstCopy& operator=(DisallowConstCopy&) = default;
383
  DisallowConstCopy& operator=(DisallowConstCopy&&) = default;
384
#endif
385 386
};

387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404
#if _MSC_VER

#define KJ_CPCAP(obj) obj=::kj::cp(obj)
// TODO(msvc): MSVC refuses to invoke non-const versions of copy constructors in by-value lambda
// captures. Wrap your captured object in this macro to force the compiler to perform a copy.
// Example:
//
//   struct Foo: DisallowConstCopy {};
//   Foo foo;
//   auto lambda = [KJ_CPCAP(foo)] {};

#else

#define KJ_CPCAP(obj) obj
// Clang and gcc both already perform copy capturing correctly with non-const copy constructors.

#endif

405 406 407 408 409 410 411 412 413 414
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> {};

415 416 417 418
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; }

419 420 421 422 423 424 425
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
426

427 428 429
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;
430

431 432 433 434
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; }

435 436 437 438 439 440 441
template <typename From, typename To>
struct PropagateConst_ { typedef To Type; };
template <typename From, typename To>
struct PropagateConst_<const From, To> { typedef const To Type; };
template <typename From, typename To>
using PropagateConst = typename PropagateConst_<From, To>::Type;

Kenton Varda's avatar
Kenton Varda committed
442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457
namespace _ {  // private

template <typename T>
T refIfLvalue(T&&);

}  // namespace _ (private)

#define KJ_DECLTYPE_REF(exp) decltype(::kj::_::refIfLvalue(exp))
// Like decltype(exp), but if exp is an lvalue, produces a reference type.
//
//     int i;
//     decltype(i) i1(i);                         // i1 has type int.
//     KJ_DECLTYPE_REF(i + 1) i2(i + 1);          // i2 has type int.
//     KJ_DECLTYPE_REF(i) i3(i);                  // i3 has type int&.
//     KJ_DECLTYPE_REF(kj::mv(i)) i4(kj::mv(i));  // i4 has type int.

458 459 460 461
template <typename T, typename U> struct IsSameType_ { static constexpr bool value = false; };
template <typename T> struct IsSameType_<T, T> { static constexpr bool value = true; };
template <typename T, typename U> constexpr bool isSameType() { return IsSameType_<T, U>::value; }

462 463 464 465 466 467 468 469 470 471 472
template <typename T>
struct CanConvert_ {
  static int sfinae(T);
  static bool sfinae(...);
};

template <typename T, typename U>
constexpr bool canConvert() {
  return sizeof(CanConvert_<U>::sfinae(instance<T>())) == sizeof(int);
}

473
#if __GNUC__ && !__clang__ && __GNUC__ < 5
474 475 476 477 478
template <typename T>
constexpr bool canMemcpy() {
  // Returns true if T can be copied using memcpy instead of using the copy constructor or
  // assignment operator.

479 480 481 482 483 484
  // GCC 4 does not have __is_trivially_constructible and friends, and there doesn't seem to be
  // any reliable alternative. __has_trivial_copy() and __has_trivial_assign() return the right
  // thing at one point but later on they changed such that a deleted copy constructor was
  // considered "trivial" (apparently technically correct, though useless). So, on GCC 4 we give up
  // and assume we can't memcpy() at all, and must explicitly copy-construct everything.
  return false;
485
}
486
#define KJ_ASSERT_CAN_MEMCPY(T)
487 488 489 490 491 492
#else
template <typename T>
constexpr bool canMemcpy() {
  // Returns true if T can be copied using memcpy instead of using the copy constructor or
  // assignment operator.

493
  return __is_trivially_constructible(T, const T&) && __is_trivially_assignable(T, const T&);
494
}
495 496
#define KJ_ASSERT_CAN_MEMCPY(T) \
  static_assert(kj::canMemcpy<T>(), "this code expects this type to be memcpy()-able");
497 498
#endif

Kenton Varda's avatar
Kenton Varda committed
499 500 501 502 503 504 505 506 507
// =======================================================================================
// 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); }
508
template<typename T> constexpr T&& fwd(NoInfer<T>& t) noexcept { return static_cast<T&&>(t); }
Kenton Varda's avatar
Kenton Varda committed
509

510 511 512 513
template<typename T> constexpr T cp(T& t) noexcept { return t; }
template<typename T> constexpr T cp(const T& t) noexcept { return t; }
// Useful to force a copy, particularly to pass into a function that expects T&&.

514 515 516 517
template <typename T, typename U, bool takeT, bool uOK = true> struct ChooseType_;
template <typename T, typename U> struct ChooseType_<T, U, true, true> { typedef T Type; };
template <typename T, typename U> struct ChooseType_<T, U, true, false> { typedef T Type; };
template <typename T, typename U> struct ChooseType_<T, U, false, true> { typedef U Type; };
518 519

template <typename T, typename U>
520
using WiderType = typename ChooseType_<T, U, sizeof(T) >= sizeof(U)>::Type;
521

522
template <typename T, typename U>
523 524
inline constexpr auto min(T&& a, U&& b) -> WiderType<Decay<T>, Decay<U>> {
  return a < b ? WiderType<Decay<T>, Decay<U>>(a) : WiderType<Decay<T>, Decay<U>>(b);
525 526
}

527
template <typename T, typename U>
528 529
inline constexpr auto max(T&& a, U&& b) -> WiderType<Decay<T>, Decay<U>> {
  return a > b ? WiderType<Decay<T>, Decay<U>>(a) : WiderType<Decay<T>, Decay<U>>(b);
530
}
531

532 533 534 535 536 537 538
template <typename T, size_t s>
inline constexpr size_t size(T (&arr)[s]) { return s; }
template <typename T>
inline constexpr size_t size(T&& arr) { return arr.size(); }
// Returns the size of the parameter, whether the parameter is a regular C array or a container
// with a `.size()` method.

539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559
class MaxValue_ {
private:
  template <typename T>
  inline constexpr T maxSigned() const {
    return (1ull << (sizeof(T) * 8 - 1)) - 1;
  }
  template <typename T>
  inline constexpr T maxUnsigned() const {
    return ~static_cast<T>(0u);
  }

public:
#define _kJ_HANDLE_TYPE(T) \
  inline constexpr operator   signed T() const { return MaxValue_::maxSigned  <  signed T>(); } \
  inline constexpr operator unsigned T() const { return MaxValue_::maxUnsigned<unsigned T>(); }
  _kJ_HANDLE_TYPE(char)
  _kJ_HANDLE_TYPE(short)
  _kJ_HANDLE_TYPE(int)
  _kJ_HANDLE_TYPE(long)
  _kJ_HANDLE_TYPE(long long)
#undef _kJ_HANDLE_TYPE
Kenton Varda's avatar
Kenton Varda committed
560 561 562 563 564 565 566

  inline constexpr operator char() const {
    // `char` is different from both `signed char` and `unsigned char`, and may be signed or
    // unsigned on different platforms.  Ugh.
    return char(-1) < 0 ? MaxValue_::maxSigned<char>()
                        : MaxValue_::maxUnsigned<char>();
  }
567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589
};

class MinValue_ {
private:
  template <typename T>
  inline constexpr T minSigned() const {
    return 1ull << (sizeof(T) * 8 - 1);
  }
  template <typename T>
  inline constexpr T minUnsigned() const {
    return 0u;
  }

public:
#define _kJ_HANDLE_TYPE(T) \
  inline constexpr operator   signed T() const { return MinValue_::minSigned  <  signed T>(); } \
  inline constexpr operator unsigned T() const { return MinValue_::minUnsigned<unsigned T>(); }
  _kJ_HANDLE_TYPE(char)
  _kJ_HANDLE_TYPE(short)
  _kJ_HANDLE_TYPE(int)
  _kJ_HANDLE_TYPE(long)
  _kJ_HANDLE_TYPE(long long)
#undef _kJ_HANDLE_TYPE
Kenton Varda's avatar
Kenton Varda committed
590 591 592 593 594 595 596

  inline constexpr operator char() const {
    // `char` is different from both `signed char` and `unsigned char`, and may be signed or
    // unsigned on different platforms.  Ugh.
    return char(-1) < 0 ? MinValue_::minSigned<char>()
                        : MinValue_::minUnsigned<char>();
  }
597 598
};

599
static KJ_CONSTEXPR(const) MaxValue_ maxValue = MaxValue_();
600 601 602 603 604 605
// A special constant which, when cast to an integer type, takes on the maximum possible value of
// that type.  This is useful to use as e.g. a parameter to a function because it will be robust
// in the face of changes to the parameter's type.
//
// `char` is not supported, but `signed char` and `unsigned char` are.

606
static KJ_CONSTEXPR(const) MinValue_ minValue = MinValue_();
607 608 609 610 611 612
// A special constant which, when cast to an integer type, takes on the minimum possible value
// of that type.  This is useful to use as e.g. a parameter to a function because it will be robust
// in the face of changes to the parameter's type.
//
// `char` is not supported, but `signed char` and `unsigned char` are.

613 614 615 616 617
template <typename T>
inline bool operator==(T t, MaxValue_) { return t == Decay<T>(maxValue); }
template <typename T>
inline bool operator==(T t, MinValue_) { return t == Decay<T>(minValue); }

618 619 620 621 622 623 624 625 626 627 628 629 630 631 632
template <uint bits>
inline constexpr unsigned long long maxValueForBits() {
  // Get the maximum integer representable in the given number of bits.

  // 1ull << 64 is unfortunately undefined.
  return (bits == 64 ? 0 : (1ull << bits)) - 1;
}

struct ThrowOverflow {
  // Functor which throws an exception complaining about integer overflow. Usually this is used
  // with the interfaces in units.h, but is defined here because Cap'n Proto wants to avoid
  // including units.h when not using CAPNP_DEBUG_TYPES.
  void operator()() const;
};

633
#if __GNUC__
634 635
inline constexpr float inf() { return __builtin_huge_valf(); }
inline constexpr float nan() { return __builtin_nanf(""); }
636

637
#elif _MSC_VER
638 639 640 641 642 643 644 645 646 647 648 649 650 651 652

// Do what MSVC math.h does
#pragma warning(push)
#pragma warning(disable: 4756)  // "overflow in constant arithmetic"
inline constexpr float inf() { return (float)(1e300 * 1e300); }
#pragma warning(pop)

float nan();
// Unfortunatley, inf() * 0.0f produces a NaN with the sign bit set, whereas our preferred
// canonical NaN should not have the sign bit set. std::numeric_limits<float>::quiet_NaN()
// returns the correct NaN, but we don't want to #include that here. So, we give up and make
// this out-of-line on MSVC.
//
// TODO(msvc): Can we do better?

653 654 655
#else
#error "Not sure how to support your compiler."
#endif
656

657 658 659
inline constexpr bool isNaN(float f) { return f != f; }
inline constexpr bool isNaN(double f) { return f != f; }

660 661 662 663 664 665 666 667 668
inline int popCount(unsigned int x) {
#if defined(_MSC_VER)
  return __popcnt(x);
  // Note: __popcnt returns unsigned int, but the value is clearly guaranteed to fit into an int
#else
  return __builtin_popcount(x);
#endif
}

Kenton Varda's avatar
Kenton Varda committed
669 670 671 672 673 674 675
// =======================================================================================
// Useful fake containers

template <typename T>
class Range {
public:
  inline constexpr Range(const T& begin, const T& end): begin_(begin), end_(end) {}
676
  inline explicit constexpr Range(const T& end): begin_(0), end_(end) {}
Kenton Varda's avatar
Kenton Varda committed
677 678 679 680 681 682

  class Iterator {
  public:
    Iterator() = default;
    inline Iterator(const T& value): value(value) {}

683 684
    inline const T&  operator* () const { return value; }
    inline const T&  operator[](size_t index) const { return value + index; }
Kenton Varda's avatar
Kenton Varda committed
685
    inline Iterator& operator++() { ++value; return *this; }
686 687 688 689 690 691 692 693 694
    inline Iterator  operator++(int) { return Iterator(value++); }
    inline Iterator& operator--() { --value; return *this; }
    inline Iterator  operator--(int) { return Iterator(value--); }
    inline Iterator& operator+=(ptrdiff_t amount) { value += amount; return *this; }
    inline Iterator& operator-=(ptrdiff_t amount) { value -= amount; return *this; }
    inline Iterator  operator+ (ptrdiff_t amount) const { return Iterator(value + amount); }
    inline Iterator  operator- (ptrdiff_t amount) const { return Iterator(value - amount); }
    inline ptrdiff_t operator- (const Iterator& other) const { return value - other.value; }

Kenton Varda's avatar
Kenton Varda committed
695 696
    inline bool operator==(const Iterator& other) const { return value == other.value; }
    inline bool operator!=(const Iterator& other) const { return value != other.value; }
697 698 699 700
    inline bool operator<=(const Iterator& other) const { return value <= other.value; }
    inline bool operator>=(const Iterator& other) const { return value >= other.value; }
    inline bool operator< (const Iterator& other) const { return value <  other.value; }
    inline bool operator> (const Iterator& other) const { return value >  other.value; }
Kenton Varda's avatar
Kenton Varda committed
701 702 703 704 705 706 707 708 709 710 711 712 713 714 715

  private:
    T value;
  };

  inline Iterator begin() const { return Iterator(begin_); }
  inline Iterator end() const { return Iterator(end_); }

  inline auto size() const -> decltype(instance<T>() - instance<T>()) { return end_ - begin_; }

private:
  T begin_;
  T end_;
};

716 717 718 719 720
template <typename T, typename U>
inline constexpr Range<WiderType<Decay<T>, Decay<U>>> range(T begin, U end) {
  return Range<WiderType<Decay<T>, Decay<U>>>(begin, end);
}

Kenton Varda's avatar
Kenton Varda committed
721
template <typename T>
722
inline constexpr Range<Decay<T>> range(T begin, T end) { return Range<Decay<T>>(begin, end); }
Kenton Varda's avatar
Kenton Varda committed
723 724 725 726 727 728
// Returns a fake iterable container containing all values of T from `begin` (inclusive) to `end`
// (exclusive).  Example:
//
//     // Prints 1, 2, 3, 4, 5, 6, 7, 8, 9.
//     for (int i: kj::range(1, 10)) { print(i); }

729 730 731 732 733 734 735 736
template <typename T>
inline constexpr Range<Decay<T>> zeroTo(T end) { return Range<Decay<T>>(end); }
// Returns a fake iterable container containing all values of T from zero (inclusive) to `end`
// (exclusive).  Example:
//
//     // Prints 0, 1, 2, 3, 4, 5, 6, 7, 8, 9.
//     for (int i: kj::zeroTo(10)) { print(i); }

737 738 739 740 741 742 743 744 745
template <typename T>
inline constexpr Range<size_t> indices(T&& container) {
  // Shortcut for iterating over the indices of a container:
  //
  //     for (size_t i: kj::indices(myArray)) { handle(myArray[i]); }

  return range<size_t>(0, kj::size(container));
}

Kenton Varda's avatar
Kenton Varda committed
746 747 748 749 750 751 752 753 754 755
template <typename T>
class Repeat {
public:
  inline constexpr Repeat(const T& value, size_t count): value(value), count(count) {}

  class Iterator {
  public:
    Iterator() = default;
    inline Iterator(const T& value, size_t index): value(value), index(index) {}

756 757
    inline const T&  operator* () const { return value; }
    inline const T&  operator[](ptrdiff_t index) const { return value; }
Kenton Varda's avatar
Kenton Varda committed
758
    inline Iterator& operator++() { ++index; return *this; }
759 760 761 762 763 764 765 766 767
    inline Iterator  operator++(int) { return Iterator(value, index++); }
    inline Iterator& operator--() { --index; return *this; }
    inline Iterator  operator--(int) { return Iterator(value, index--); }
    inline Iterator& operator+=(ptrdiff_t amount) { index += amount; return *this; }
    inline Iterator& operator-=(ptrdiff_t amount) { index -= amount; return *this; }
    inline Iterator  operator+ (ptrdiff_t amount) const { return Iterator(value, index + amount); }
    inline Iterator  operator- (ptrdiff_t amount) const { return Iterator(value, index - amount); }
    inline ptrdiff_t operator- (const Iterator& other) const { return index - other.index; }

Kenton Varda's avatar
Kenton Varda committed
768 769
    inline bool operator==(const Iterator& other) const { return index == other.index; }
    inline bool operator!=(const Iterator& other) const { return index != other.index; }
770 771 772 773
    inline bool operator<=(const Iterator& other) const { return index <= other.index; }
    inline bool operator>=(const Iterator& other) const { return index >= other.index; }
    inline bool operator< (const Iterator& other) const { return index <  other.index; }
    inline bool operator> (const Iterator& other) const { return index >  other.index; }
Kenton Varda's avatar
Kenton Varda committed
774 775 776 777 778 779 780 781 782 783

  private:
    T value;
    size_t index;
  };

  inline Iterator begin() const { return Iterator(value, 0); }
  inline Iterator end() const { return Iterator(value, count); }

  inline size_t size() const { return count; }
784
  inline const T& operator[](ptrdiff_t) const { return value; }
Kenton Varda's avatar
Kenton Varda committed
785 786 787 788 789 790 791 792 793 794 795 796 797 798

private:
  T value;
  size_t count;
};

template <typename T>
inline constexpr Repeat<Decay<T>> repeat(T&& value, size_t count) {
  // Returns a fake iterable which contains `count` repeats of `value`.  Useful for e.g. creating
  // a bunch of spaces:  `kj::repeat(' ', indent * 2)`

  return Repeat<Decay<T>>(value, count);
}

799 800 801 802 803 804 805 806 807
// =======================================================================================
// 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.

808
namespace _ {  // private
809
struct PlacementNew {};
810
}  // namespace _ (private)
811 812
} // namespace kj

813
inline void* operator new(size_t, kj::_::PlacementNew, void* __p) noexcept {
814 815 816
  return __p;
}

817 818
inline void operator delete(void*, kj::_::PlacementNew, void* __p) noexcept {}

819 820 821 822
namespace kj {

template <typename T, typename... Params>
inline void ctor(T& location, Params&&... params) {
823
  new (_::PlacementNew(), &location) T(kj::fwd<Params>(params)...);
824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857
}

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;

858
namespace _ {  // private
859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877

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);
    }
  }
878 879 880 881 882 883
  inline NullableValue(NullableValue& other)
      : isSet(other.isSet) {
    if (isSet) {
      ctor(value, other.value);
    }
  }
884 885 886 887 888 889 890 891 892
  inline ~NullableValue()
#if _MSC_VER
      // TODO(msvc): MSVC has a hard time with noexcept specifier expressions that are more complex
      //   than `true` or `false`. We had a workaround for VS2015, but VS2017 regressed.
      noexcept(false)
#else
      noexcept(noexcept(instance<T&>().~T()))
#endif
  {
893 894 895 896 897
    if (isSet) {
      dtor(value);
    }
  }

898 899 900 901
  inline T& operator*() & { return value; }
  inline const T& operator*() const & { return value; }
  inline T&& operator*() && { return kj::mv(value); }
  inline const T&& operator*() const && { return kj::mv(value); }
902 903 904 905 906
  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; }

907
  template <typename... Params>
908
  inline T& emplace(Params&&... params) {
909 910 911 912 913 914
    if (isSet) {
      isSet = false;
      dtor(value);
    }
    ctor(value, kj::fwd<Params>(params)...);
    isSet = true;
915
    return value;
916 917
  }

918 919 920 921 922
  inline NullableValue() noexcept: isSet(false) {}
  inline NullableValue(T&& t) noexcept(noexcept(T(instance<T&&>())))
      : isSet(true) {
    ctor(value, kj::mv(t));
  }
923 924 925 926
  inline NullableValue(T& t)
      : isSet(true) {
    ctor(value, t);
  }
927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959
  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) {
960
      // Careful about throwing destructors/constructors here.
961
      if (isSet) {
962
        isSet = false;
963 964
        dtor(value);
      }
965
      if (other.isSet) {
966
        ctor(value, kj::mv(other.value));
967
        isSet = true;
968 969 970 971 972
      }
    }
    return *this;
  }

973 974
  inline NullableValue& operator=(NullableValue& other) {
    if (&other != this) {
975
      // Careful about throwing destructors/constructors here.
976
      if (isSet) {
977
        isSet = false;
978 979
        dtor(value);
      }
980
      if (other.isSet) {
981
        ctor(value, other.value);
982
        isSet = true;
983 984 985 986 987
      }
    }
    return *this;
  }

988 989
  inline NullableValue& operator=(const NullableValue& other) {
    if (&other != this) {
990
      // Careful about throwing destructors/constructors here.
991
      if (isSet) {
992
        isSet = false;
993 994
        dtor(value);
      }
995
      if (other.isSet) {
996
        ctor(value, other.value);
997
        isSet = true;
998 999 1000 1001 1002 1003 1004 1005 1006 1007
      }
    }
    return *this;
  }

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

private:
  bool isSet;
1008 1009 1010 1011 1012 1013 1014 1015

#if _MSC_VER
#pragma warning(push)
#pragma warning(disable: 4624)
// Warns that the anonymous union has a deleted destructor when T is non-trivial. This warning
// seems broken.
#endif

1016 1017 1018 1019
  union {
    T value;
  };

1020 1021 1022 1023
#if _MSC_VER
#pragma warning(pop)
#endif

1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039
  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; }

1040 1041 1042 1043
template <typename T>
inline T* readMaybe(T* ptr) { return ptr; }
// Allow KJ_IF_MAYBE to work on regular pointers.

1044
}  // namespace _ (private)
1045

1046
#define KJ_IF_MAYBE(name, exp) if (auto name = ::kj::_::readMaybe(exp))
1047 1048 1049

template <typename T>
class Maybe {
1050 1051 1052 1053
  // A T, or nullptr.

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

1054 1055 1056
public:
  Maybe(): ptr(nullptr) {}
  Maybe(T&& t) noexcept(noexcept(T(instance<T&&>()))): ptr(kj::mv(t)) {}
1057
  Maybe(T& t): ptr(t) {}
1058 1059 1060 1061
  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) {}
1062
  Maybe(Maybe& other): ptr(other.ptr) {}
1063 1064 1065 1066

  template <typename U>
  Maybe(Maybe<U>&& other) noexcept(noexcept(T(instance<U&&>()))) {
    KJ_IF_MAYBE(val, kj::mv(other)) {
1067
      ptr.emplace(kj::mv(*val));
1068 1069 1070 1071 1072
    }
  }
  template <typename U>
  Maybe(const Maybe<U>& other) {
    KJ_IF_MAYBE(val, other) {
1073
      ptr.emplace(*val);
1074 1075 1076 1077 1078
    }
  }

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

1079
  template <typename... Params>
1080
  inline T& emplace(Params&&... params) {
1081 1082
    // Replace this Maybe's content with a new value constructed by passing the given parametrs to
    // T's constructor. This can be used to initialize a Maybe without copying or even moving a T.
1083
    // Returns a reference to the newly-constructed value.
1084

1085
    return ptr.emplace(kj::fwd<Params>(params)...);
1086 1087
  }

1088
  inline Maybe& operator=(Maybe&& other) { ptr = kj::mv(other.ptr); return *this; }
1089
  inline Maybe& operator=(Maybe& other) { ptr = other.ptr; return *this; }
1090 1091 1092 1093 1094
  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; }

1095
  T& orDefault(T& defaultValue) & {
1096 1097 1098 1099 1100 1101
    if (ptr == nullptr) {
      return defaultValue;
    } else {
      return *ptr;
    }
  }
1102
  const T& orDefault(const T& defaultValue) const & {
1103 1104 1105 1106 1107 1108
    if (ptr == nullptr) {
      return defaultValue;
    } else {
      return *ptr;
    }
  }
1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122
  T&& orDefault(T&& defaultValue) && {
    if (ptr == nullptr) {
      return kj::mv(defaultValue);
    } else {
      return kj::mv(*ptr);
    }
  }
  const T&& orDefault(const T&& defaultValue) const && {
    if (ptr == nullptr) {
      return kj::mv(defaultValue);
    } else {
      return kj::mv(*ptr);
    }
  }
1123

1124
  template <typename Func>
1125
  auto map(Func&& f) & -> Maybe<decltype(f(instance<T&>()))> {
1126 1127 1128 1129 1130 1131 1132 1133
    if (ptr == nullptr) {
      return nullptr;
    } else {
      return f(*ptr);
    }
  }

  template <typename Func>
1134
  auto map(Func&& f) const & -> Maybe<decltype(f(instance<const T&>()))> {
1135 1136 1137 1138 1139 1140 1141
    if (ptr == nullptr) {
      return nullptr;
    } else {
      return f(*ptr);
    }
  }

1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158
  template <typename Func>
  auto map(Func&& f) && -> Maybe<decltype(f(instance<T&&>()))> {
    if (ptr == nullptr) {
      return nullptr;
    } else {
      return f(kj::mv(*ptr));
    }
  }

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

private:
1161
  _::NullableValue<T> ptr;
1162 1163 1164 1165

  template <typename U>
  friend class Maybe;
  template <typename U>
1166
  friend _::NullableValue<U>&& _::readMaybe(Maybe<U>&& maybe);
1167
  template <typename U>
1168
  friend U* _::readMaybe(Maybe<U>& maybe);
1169
  template <typename U>
1170
  friend const U* _::readMaybe(const Maybe<U>& maybe);
1171 1172 1173
};

template <typename T>
1174
class Maybe<T&>: public DisallowConstCopyIfNotConst<T> {
1175
public:
1176
  Maybe() noexcept: ptr(nullptr) {}
1177 1178 1179
  Maybe(T& t) noexcept: ptr(&t) {}
  Maybe(T* t) noexcept: ptr(t) {}

1180 1181 1182
  template <typename U>
  inline Maybe(Maybe<U&>& other) noexcept: ptr(other.ptr) {}
  template <typename U>
1183
  inline Maybe(const Maybe<U&>& other) noexcept: ptr(const_cast<const U*>(other.ptr)) {}
1184
  inline Maybe(decltype(nullptr)) noexcept: ptr(nullptr) {}
1185

1186 1187
  inline Maybe& operator=(T& other) noexcept { ptr = &other; return *this; }
  inline Maybe& operator=(T* other) noexcept { ptr = other; return *this; }
1188 1189 1190 1191
  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; }
1192 1193 1194 1195

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

1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210
  T& orDefault(T& defaultValue) {
    if (ptr == nullptr) {
      return defaultValue;
    } else {
      return *ptr;
    }
  }
  const T& orDefault(const T& defaultValue) const {
    if (ptr == nullptr) {
      return defaultValue;
    } else {
      return *ptr;
    }
  }

1211 1212 1213 1214 1215 1216 1217 1218
  template <typename Func>
  auto map(Func&& f) -> Maybe<decltype(f(instance<T&>()))> {
    if (ptr == nullptr) {
      return nullptr;
    } else {
      return f(*ptr);
    }
  }
1219 1220 1221 1222 1223 1224 1225

private:
  T* ptr;

  template <typename U>
  friend class Maybe;
  template <typename U>
1226
  friend U* _::readMaybe(Maybe<U&>&& maybe);
1227
  template <typename U>
1228
  friend U* _::readMaybe(const Maybe<U&>& maybe);
1229 1230
};

1231 1232 1233 1234 1235 1236
// =======================================================================================
// ArrayPtr
//
// So common that we put it in common.h rather than array.h.

template <typename T>
1237
class ArrayPtr: public DisallowConstCopyIfNotConst<T> {
1238 1239 1240 1241 1242 1243 1244 1245
  // 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) {}
1246
  inline KJ_CONSTEXPR() ArrayPtr(::std::initializer_list<RemoveConstOrDisable<T>> init)
1247
      : ptr(init.begin()), size_(init.size()) {}
1248

1249
  template <size_t size>
1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274
  inline constexpr ArrayPtr(T (&native)[size]): ptr(native), size_(size) {
    // Construct an ArrayPtr from a native C-style array.
    //
    // We disable this constructor for const char arrays because otherwise you would be able to
    // implicitly convert a character literal to ArrayPtr<const char>, which sounds really great,
    // except that the NUL terminator would be included, which probably isn't what you intended.
    //
    // TODO(someday): Maybe we should support character literals but explicitly chop off the NUL
    //   terminator. This could do the wrong thing if someone tries to construct an
    //   ArrayPtr<const char> from a non-NUL-terminated char array, but evidence suggests that all
    //   real use cases are in fact intending to remove the NUL terminator. It's convenient to be
    //   able to specify ArrayPtr<const char> as a parameter type and be able to accept strings
    //   as input in addition to arrays. Currently, you'll need overloading to support string
    //   literals in this case, but if you overload StringPtr, then you'll find that several
    //   conversions (e.g. from String and from a literal char array) become ambiguous! You end up
    //   having to overload for literal char arrays specifically which is cumbersome.

    static_assert(!isSameType<T, const char>(),
        "Can't implicitly convert literal char array to ArrayPtr because we don't know if "
        "you meant to include the NUL terminator. We may change this in the future to "
        "automatically drop the NUL terminator. For now, try explicitly converting to StringPtr, "
        "which can in turn implicitly convert to ArrayPtr<const char>.");
    static_assert(!isSameType<T, const char16_t>(), "see above");
    static_assert(!isSameType<T, const char32_t>(), "see above");
  }
1275

Kenton Varda's avatar
Kenton Varda committed
1276 1277 1278 1279
  inline operator ArrayPtr<const T>() const {
    return ArrayPtr<const T>(ptr, size_);
  }
  inline ArrayPtr<const T> asConst() const {
1280 1281 1282 1283
    return ArrayPtr<const T>(ptr, size_);
  }

  inline size_t size() const { return size_; }
1284 1285 1286 1287 1288
  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
1289
    KJ_IREQUIRE(index < size_, "Out-of-bounds ArrayPtr access.");
1290 1291 1292
    return ptr[index];
  }

1293 1294 1295 1296 1297 1298 1299 1300
  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); }
1301

1302 1303 1304 1305 1306
  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
1307
    KJ_IREQUIRE(start <= end && end <= size_, "Out-of-bounds ArrayPtr::slice().");
1308 1309 1310
    return ArrayPtr(ptr + start, end - start);
  }

1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321
  inline ArrayPtr<PropagateConst<T, byte>> asBytes() const {
    // Reinterpret the array as a byte array. This is explicitly legal under C++ aliasing
    // rules.
    return { reinterpret_cast<PropagateConst<T, byte>*>(ptr), size_ * sizeof(T) };
  }
  inline ArrayPtr<PropagateConst<T, char>> asChars() const {
    // Reinterpret the array as a char array. This is explicitly legal under C++ aliasing
    // rules.
    return { reinterpret_cast<PropagateConst<T, char>*>(ptr), size_ * sizeof(T) };
  }

1322 1323
  inline bool operator==(decltype(nullptr)) const { return size_ == 0; }
  inline bool operator!=(decltype(nullptr)) const { return size_ != 0; }
1324

Kenton Varda's avatar
Kenton Varda committed
1325 1326 1327 1328 1329 1330 1331 1332 1333
  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); }

1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344
  template <typename U>
  inline bool operator==(const ArrayPtr<U>& 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;
  }
  template <typename U>
  inline bool operator!=(const ArrayPtr<U>& other) const { return !(*this == other); }

1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361
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
1362
// =======================================================================================
1363
// Casts
Kenton Varda's avatar
Kenton Varda committed
1364 1365

template <typename To, typename From>
1366 1367 1368
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
1369 1370 1371 1372
  return kj::fwd<From>(from);
}

template <typename To, typename From>
1373
Maybe<To&> dynamicDowncastIfAvailable(From& from) {
Kenton Varda's avatar
Kenton Varda committed
1374 1375 1376 1377 1378 1379
  // 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.

1380 1381 1382
  // 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) {
1383
    kj::implicitCast<From*>(kj::implicitCast<To*>(nullptr));
1384 1385
  }

Kenton Varda's avatar
Kenton Varda committed
1386 1387 1388
#if KJ_NO_RTTI
  return nullptr;
#else
1389
  return dynamic_cast<To*>(&from);
Kenton Varda's avatar
Kenton Varda committed
1390 1391 1392 1393
#endif
}

template <typename To, typename From>
1394
To& downcast(From& from) {
Kenton Varda's avatar
Kenton Varda committed
1395 1396 1397 1398 1399 1400
  // 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) {
1401
    kj::implicitCast<From*>(kj::implicitCast<To*>(nullptr));
Kenton Varda's avatar
Kenton Varda committed
1402 1403 1404
  }

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

1408
  return static_cast<To&>(from);
Kenton Varda's avatar
Kenton Varda committed
1409 1410
}

1411 1412 1413 1414 1415 1416 1417 1418
// =======================================================================================
// Defer

namespace _ {  // private

template <typename Func>
class Deferred {
public:
1419
  inline Deferred(Func&& func): func(kj::fwd<Func>(func)), canceled(false) {}
1420
  inline ~Deferred() noexcept(false) { if (!canceled) func(); }
1421 1422
  KJ_DISALLOW_COPY(Deferred);

Kenton Varda's avatar
Kenton Varda committed
1423
  // This move constructor is usually optimized away by the compiler.
1424
  inline Deferred(Deferred&& other): func(kj::mv(other.func)), canceled(false) {
1425 1426
    other.canceled = true;
  }
1427 1428
private:
  Func func;
1429
  bool canceled;
1430 1431
};

Kenton Varda's avatar
Kenton Varda committed
1432 1433
}  // namespace _ (private)

1434
template <typename Func>
1435
_::Deferred<Func> defer(Func&& func) {
Kenton Varda's avatar
Kenton Varda committed
1436 1437 1438 1439 1440
  // 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
1441
  // want some code to run at current scope exit.
1442

1443
  return _::Deferred<Func>(kj::fwd<Func>(func));
Kenton Varda's avatar
Kenton Varda committed
1444
}
1445

Kenton Varda's avatar
Kenton Varda committed
1446 1447
#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.
1448

Kenton Varda's avatar
Kenton Varda committed
1449 1450 1451
}  // namespace kj

#endif  // KJ_COMMON_H_