summaryrefslogtreecommitdiff
path: root/mfbt
diff options
context:
space:
mode:
authorLorry Tar Creator <lorry-tar-importer@baserock.org>2013-12-11 22:24:18 +0000
committer <>2014-07-24 09:30:59 +0000
commit59e2936f588aa945e8dcd6c737523c299067e9d0 (patch)
tree97e74980cc54baa19de5faa11f5a50a0121a48ea /mfbt
downloadmozjs24-master.tar.gz
Imported from /home/lorry/working-area/delta_mozilla_mozjs24/mozjs-24.2.0.tar.bz2.HEADmozjs-24.2.0master
Diffstat (limited to 'mfbt')
-rw-r--r--mfbt/Assertions.h387
-rw-r--r--mfbt/Atomics.h960
-rw-r--r--mfbt/Attributes.h409
-rw-r--r--mfbt/BloomFilter.h234
-rw-r--r--mfbt/Casting.h201
-rw-r--r--mfbt/Char16.h56
-rw-r--r--mfbt/CheckedInt.h878
-rw-r--r--mfbt/Compiler.h31
-rw-r--r--mfbt/Constants.h15
-rw-r--r--mfbt/DebugOnly.h77
-rw-r--r--mfbt/Endian.h639
-rw-r--r--mfbt/EnumSet.h175
-rw-r--r--mfbt/FloatingPoint.h196
-rw-r--r--mfbt/GuardObjects.h150
-rw-r--r--mfbt/HashFunctions.cpp38
-rw-r--r--mfbt/HashFunctions.h359
-rw-r--r--mfbt/Likely.h22
-rw-r--r--mfbt/LinkedList.h429
-rw-r--r--mfbt/MSStdInt.h247
-rw-r--r--mfbt/Makefile.in28
-rw-r--r--mfbt/MathAlgorithms.h147
-rw-r--r--mfbt/MemoryChecking.h71
-rw-r--r--mfbt/NullPtr.h48
-rw-r--r--mfbt/PodOperations.h159
-rw-r--r--mfbt/Poison.cpp206
-rw-r--r--mfbt/Poison.h61
-rw-r--r--mfbt/Range.h49
-rw-r--r--mfbt/RangedPtr.h254
-rw-r--r--mfbt/RefPtr.h449
-rw-r--r--mfbt/SHA1.cpp327
-rw-r--r--mfbt/SHA1.h61
-rw-r--r--mfbt/STYLE383
-rw-r--r--mfbt/Scoped.h271
-rw-r--r--mfbt/SplayTree.h285
-rw-r--r--mfbt/StandardInteger.h43
-rw-r--r--mfbt/ThreadLocal.h147
-rw-r--r--mfbt/TypeTraits.h668
-rw-r--r--mfbt/TypedEnum.h213
-rw-r--r--mfbt/Types.h144
-rw-r--r--mfbt/Util.h335
-rw-r--r--mfbt/WeakPtr.h190
-rw-r--r--mfbt/decimal/Decimal.cpp1054
-rw-r--r--mfbt/decimal/Decimal.h213
-rw-r--r--mfbt/decimal/LICENSE-APPLE21
-rw-r--r--mfbt/decimal/LICENSE-LGPL-2481
-rw-r--r--mfbt/decimal/LICENSE-LGPL-2.1502
-rw-r--r--mfbt/decimal/comparison-with-nan.patch67
-rw-r--r--mfbt/decimal/floor-ceiling.patch89
-rw-r--r--mfbt/decimal/mfbt-abi-markers.patch150
-rw-r--r--mfbt/decimal/moz-decimal-utils.h109
-rw-r--r--mfbt/decimal/to-moz-dependencies.patch333
-rwxr-xr-xmfbt/decimal/update.sh66
-rw-r--r--mfbt/decimal/zero-serialization.patch22
-rw-r--r--mfbt/double-conversion/LICENSE26
-rw-r--r--mfbt/double-conversion/README11
-rw-r--r--mfbt/double-conversion/add-mfbt-api-markers.patch94
-rw-r--r--mfbt/double-conversion/bignum-dtoa.cc640
-rw-r--r--mfbt/double-conversion/bignum-dtoa.h84
-rw-r--r--mfbt/double-conversion/bignum.cc764
-rw-r--r--mfbt/double-conversion/bignum.h145
-rw-r--r--mfbt/double-conversion/cached-powers.cc175
-rw-r--r--mfbt/double-conversion/cached-powers.h64
-rw-r--r--mfbt/double-conversion/diy-fp.cc57
-rw-r--r--mfbt/double-conversion/diy-fp.h118
-rw-r--r--mfbt/double-conversion/double-conversion.cc889
-rw-r--r--mfbt/double-conversion/double-conversion.h537
-rw-r--r--mfbt/double-conversion/fast-dtoa.cc664
-rw-r--r--mfbt/double-conversion/fast-dtoa.h88
-rw-r--r--mfbt/double-conversion/fixed-dtoa.cc402
-rw-r--r--mfbt/double-conversion/fixed-dtoa.h56
-rw-r--r--mfbt/double-conversion/ieee.h398
-rw-r--r--mfbt/double-conversion/strtod.cc554
-rw-r--r--mfbt/double-conversion/strtod.h45
-rwxr-xr-xmfbt/double-conversion/update.sh20
-rw-r--r--mfbt/double-conversion/use-StandardInteger.patch29
-rw-r--r--mfbt/double-conversion/utils.h297
-rw-r--r--mfbt/exported_headers.mk49
-rw-r--r--mfbt/moz.build12
-rw-r--r--mfbt/sources.mk37
-rw-r--r--mfbt/tests/Makefile.in47
-rw-r--r--mfbt/tests/TestAtomics.cpp159
-rw-r--r--mfbt/tests/TestBloomFilter.cpp102
-rw-r--r--mfbt/tests/TestCasting.cpp107
-rw-r--r--mfbt/tests/TestCheckedInt.cpp567
-rw-r--r--mfbt/tests/TestEndian.cpp398
-rw-r--r--mfbt/tests/TestEnumSet.cpp232
-rw-r--r--mfbt/tests/TestPoisonArea.cpp654
-rw-r--r--mfbt/tests/TestSHA1.cpp204
-rw-r--r--mfbt/tests/TestTypeTraits.cpp213
-rw-r--r--mfbt/tests/TestWeakPtr.cpp77
-rw-r--r--mfbt/tests/moz.build6
91 files changed, 22170 insertions, 0 deletions
diff --git a/mfbt/Assertions.h b/mfbt/Assertions.h
new file mode 100644
index 0000000..5ead7f4
--- /dev/null
+++ b/mfbt/Assertions.h
@@ -0,0 +1,387 @@
+/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+/* Implementations of runtime and static assertion macros for C and C++. */
+
+#ifndef mozilla_Assertions_h_
+#define mozilla_Assertions_h_
+
+#include "mozilla/Attributes.h"
+#include "mozilla/Compiler.h"
+#include "mozilla/Likely.h"
+
+#include <stddef.h>
+#include <stdio.h>
+#include <stdlib.h>
+#ifdef WIN32
+ /*
+ * TerminateProcess and GetCurrentProcess are defined in <winbase.h>, which
+ * further depends on <windef.h>. We hardcode these few definitions manually
+ * because those headers clutter the global namespace with a significant
+ * number of undesired macros and symbols.
+ */
+# ifdef __cplusplus
+ extern "C" {
+# endif
+ __declspec(dllimport) int __stdcall
+ TerminateProcess(void* hProcess, unsigned int uExitCode);
+ __declspec(dllimport) void* __stdcall GetCurrentProcess(void);
+# ifdef __cplusplus
+ }
+# endif
+#else
+# include <signal.h>
+#endif
+#ifdef ANDROID
+# include <android/log.h>
+#endif
+
+/*
+ * MOZ_STATIC_ASSERT may be used to assert a condition *at compile time*. This
+ * can be useful when you make certain assumptions about what must hold for
+ * optimal, or even correct, behavior. For example, you might assert that the
+ * size of a struct is a multiple of the target architecture's word size:
+ *
+ * struct S { ... };
+ * MOZ_STATIC_ASSERT(sizeof(S) % sizeof(size_t) == 0,
+ * "S should be a multiple of word size for efficiency");
+ *
+ * This macro can be used in any location where both an extern declaration and a
+ * typedef could be used.
+ *
+ * Be aware of the gcc 4.2 concerns noted further down when writing patches that
+ * use this macro, particularly if a patch only bounces on OS X.
+ */
+#ifdef __cplusplus
+# if defined(__clang__)
+# ifndef __has_extension
+# define __has_extension __has_feature /* compatibility, for older versions of clang */
+# endif
+# if __has_extension(cxx_static_assert)
+# define MOZ_STATIC_ASSERT(cond, reason) static_assert((cond), reason)
+# endif
+# elif defined(__GNUC__)
+# if (defined(__GXX_EXPERIMENTAL_CXX0X__) || __cplusplus >= 201103L)
+# define MOZ_STATIC_ASSERT(cond, reason) static_assert((cond), reason)
+# endif
+# elif defined(_MSC_VER)
+# if _MSC_VER >= 1600 /* MSVC 10 */
+# define MOZ_STATIC_ASSERT(cond, reason) static_assert((cond), reason)
+# endif
+# elif defined(__HP_aCC)
+# if __HP_aCC >= 62500 && defined(_HP_CXX0x_SOURCE)
+# define MOZ_STATIC_ASSERT(cond, reason) static_assert((cond), reason)
+# endif
+# endif
+#endif
+#ifndef MOZ_STATIC_ASSERT
+ /*
+ * Some of the definitions below create an otherwise-unused typedef. This
+ * triggers compiler warnings with some versions of gcc, so mark the typedefs
+ * as permissibly-unused to disable the warnings.
+ */
+# if defined(__GNUC__)
+# define MOZ_STATIC_ASSERT_UNUSED_ATTRIBUTE __attribute__((unused))
+# else
+# define MOZ_STATIC_ASSERT_UNUSED_ATTRIBUTE /* nothing */
+# endif
+# define MOZ_STATIC_ASSERT_GLUE1(x, y) x##y
+# define MOZ_STATIC_ASSERT_GLUE(x, y) MOZ_STATIC_ASSERT_GLUE1(x, y)
+# if defined(__SUNPRO_CC)
+ /*
+ * The Sun Studio C++ compiler is buggy when declaring, inside a function,
+ * another extern'd function with an array argument whose length contains a
+ * sizeof, triggering the error message "sizeof expression not accepted as
+ * size of array parameter". This bug (6688515, not public yet) would hit
+ * defining moz_static_assert as a function, so we always define an extern
+ * array for Sun Studio.
+ *
+ * We include the line number in the symbol name in a best-effort attempt
+ * to avoid conflicts (see below).
+ */
+# define MOZ_STATIC_ASSERT(cond, reason) \
+ extern char MOZ_STATIC_ASSERT_GLUE(moz_static_assert, __LINE__)[(cond) ? 1 : -1]
+# elif defined(__COUNTER__)
+ /*
+ * If there was no preferred alternative, use a compiler-agnostic version.
+ *
+ * Note that the non-__COUNTER__ version has a bug in C++: it can't be used
+ * in both |extern "C"| and normal C++ in the same translation unit. (Alas
+ * |extern "C"| isn't allowed in a function.) The only affected compiler
+ * we really care about is gcc 4.2. For that compiler and others like it,
+ * we include the line number in the function name to do the best we can to
+ * avoid conflicts. These should be rare: a conflict would require use of
+ * MOZ_STATIC_ASSERT on the same line in separate files in the same
+ * translation unit, *and* the uses would have to be in code with
+ * different linkage, *and* the first observed use must be in C++-linkage
+ * code.
+ */
+# define MOZ_STATIC_ASSERT(cond, reason) \
+ typedef int MOZ_STATIC_ASSERT_GLUE(moz_static_assert, __COUNTER__)[(cond) ? 1 : -1] MOZ_STATIC_ASSERT_UNUSED_ATTRIBUTE
+# else
+# define MOZ_STATIC_ASSERT(cond, reason) \
+ extern void MOZ_STATIC_ASSERT_GLUE(moz_static_assert, __LINE__)(int arg[(cond) ? 1 : -1]) MOZ_STATIC_ASSERT_UNUSED_ATTRIBUTE
+# endif
+#endif
+
+#define MOZ_STATIC_ASSERT_IF(cond, expr, reason) MOZ_STATIC_ASSERT(!(cond) || (expr), reason)
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/*
+ * MOZ_CRASH crashes the program, plain and simple, in a Breakpad-compatible
+ * way, in both debug and release builds.
+ *
+ * MOZ_CRASH is a good solution for "handling" failure cases when you're
+ * unwilling or unable to handle them more cleanly -- for OOM, for likely memory
+ * corruption, and so on. It's also a good solution if you need safe behavior
+ * in release builds as well as debug builds. But if the failure is one that
+ * should be debugged and fixed, MOZ_ASSERT is generally preferable.
+ */
+#if defined(_MSC_VER)
+ /*
+ * On MSVC use the __debugbreak compiler intrinsic, which produces an inline
+ * (not nested in a system function) breakpoint. This distinctively invokes
+ * Breakpad without requiring system library symbols on all stack-processing
+ * machines, as a nested breakpoint would require. We use TerminateProcess
+ * with the exit code aborting would generate because we don't want to invoke
+ * atexit handlers, destructors, library unload handlers, and so on when our
+ * process might be in a compromised state. We don't use abort() because
+ * it'd cause Windows to annoyingly pop up the process error dialog multiple
+ * times. See bug 345118 and bug 426163.
+ *
+ * (Technically these are Windows requirements, not MSVC requirements. But
+ * practically you need MSVC for debugging, and we only ship builds created
+ * by MSVC, so doing it this way reduces complexity.)
+ */
+# ifdef __cplusplus
+# define MOZ_CRASH() \
+ do { \
+ __debugbreak(); \
+ *((volatile int*) NULL) = 123; \
+ ::TerminateProcess(::GetCurrentProcess(), 3); \
+ } while (0)
+# else
+# define MOZ_CRASH() \
+ do { \
+ __debugbreak(); \
+ *((volatile int*) NULL) = 123; \
+ TerminateProcess(GetCurrentProcess(), 3); \
+ } while (0)
+# endif
+#else
+# ifdef __cplusplus
+# define MOZ_CRASH() \
+ do { \
+ *((volatile int*) NULL) = 123; \
+ ::abort(); \
+ } while (0)
+# else
+# define MOZ_CRASH() \
+ do { \
+ *((volatile int*) NULL) = 123; \
+ abort(); \
+ } while (0)
+# endif
+#endif
+
+/*
+ * Prints |s| as an assertion failure (using file and ln as the location of the
+ * assertion) to the standard debug-output channel.
+ *
+ * Usually you should use MOZ_ASSERT instead of this method. This method is
+ * primarily for internal use in this header, and only secondarily for use in
+ * implementing release-build assertions.
+ */
+static MOZ_ALWAYS_INLINE void
+MOZ_ReportAssertionFailure(const char* s, const char* file, int ln)
+{
+#ifdef ANDROID
+ __android_log_print(ANDROID_LOG_FATAL, "MOZ_Assert",
+ "Assertion failure: %s, at %s:%d\n", s, file, ln);
+#else
+ fprintf(stderr, "Assertion failure: %s, at %s:%d\n", s, file, ln);
+ fflush(stderr);
+#endif
+}
+
+#ifdef __cplusplus
+} /* extern "C" */
+#endif
+
+/*
+ * MOZ_ASSERT(expr [, explanation-string]) asserts that |expr| must be truthy in
+ * debug builds. If it is, execution continues. Otherwise, an error message
+ * including the expression and the explanation-string (if provided) is printed,
+ * an attempt is made to invoke any existing debugger, and execution halts.
+ * MOZ_ASSERT is fatal: no recovery is possible. Do not assert a condition
+ * which can correctly be falsy.
+ *
+ * The optional explanation-string, if provided, must be a string literal
+ * explaining the assertion. It is intended for use with assertions whose
+ * correctness or rationale is non-obvious, and for assertions where the "real"
+ * condition being tested is best described prosaically. Don't provide an
+ * explanation if it's not actually helpful.
+ *
+ * // No explanation needed: pointer arguments often must not be NULL.
+ * MOZ_ASSERT(arg);
+ *
+ * // An explanation can be helpful to explain exactly how we know an
+ * // assertion is valid.
+ * MOZ_ASSERT(state == WAITING_FOR_RESPONSE,
+ * "given that <thingA> and <thingB>, we must have...");
+ *
+ * // Or it might disambiguate multiple identical (save for their location)
+ * // assertions of the same expression.
+ * MOZ_ASSERT(getSlot(PRIMITIVE_THIS_SLOT).isUndefined(),
+ * "we already set [[PrimitiveThis]] for this Boolean object");
+ * MOZ_ASSERT(getSlot(PRIMITIVE_THIS_SLOT).isUndefined(),
+ * "we already set [[PrimitiveThis]] for this String object");
+ *
+ * MOZ_ASSERT has no effect in non-debug builds. It is designed to catch bugs
+ * *only* during debugging, not "in the field".
+ */
+#ifdef DEBUG
+ /* First the single-argument form. */
+# define MOZ_ASSERT_HELPER1(expr) \
+ do { \
+ if (MOZ_UNLIKELY(!(expr))) { \
+ MOZ_ReportAssertionFailure(#expr, __FILE__, __LINE__); \
+ MOZ_CRASH(); \
+ } \
+ } while (0)
+ /* Now the two-argument form. */
+# define MOZ_ASSERT_HELPER2(expr, explain) \
+ do { \
+ if (MOZ_UNLIKELY(!(expr))) { \
+ MOZ_ReportAssertionFailure(#expr " (" explain ")", __FILE__, __LINE__); \
+ MOZ_CRASH(); \
+ } \
+ } while (0)
+ /* And now, helper macrology up the wazoo. */
+ /*
+ * Count the number of arguments passed to MOZ_ASSERT, very carefully
+ * tiptoeing around an MSVC bug where it improperly expands __VA_ARGS__ as a
+ * single token in argument lists. See these URLs for details:
+ *
+ * http://connect.microsoft.com/VisualStudio/feedback/details/380090/variadic-macro-replacement
+ * http://cplusplus.co.il/2010/07/17/variadic-macro-to-count-number-of-arguments/#comment-644
+ */
+# define MOZ_COUNT_ASSERT_ARGS_IMPL2(_1, _2, count, ...) \
+ count
+# define MOZ_COUNT_ASSERT_ARGS_IMPL(args) \
+ MOZ_COUNT_ASSERT_ARGS_IMPL2 args
+# define MOZ_COUNT_ASSERT_ARGS(...) \
+ MOZ_COUNT_ASSERT_ARGS_IMPL((__VA_ARGS__, 2, 1, 0))
+ /* Pick the right helper macro to invoke. */
+# define MOZ_ASSERT_CHOOSE_HELPER2(count) MOZ_ASSERT_HELPER##count
+# define MOZ_ASSERT_CHOOSE_HELPER1(count) MOZ_ASSERT_CHOOSE_HELPER2(count)
+# define MOZ_ASSERT_CHOOSE_HELPER(count) MOZ_ASSERT_CHOOSE_HELPER1(count)
+ /* The actual macro. */
+# define MOZ_ASSERT_GLUE(x, y) x y
+# define MOZ_ASSERT(...) \
+ MOZ_ASSERT_GLUE(MOZ_ASSERT_CHOOSE_HELPER(MOZ_COUNT_ASSERT_ARGS(__VA_ARGS__)), \
+ (__VA_ARGS__))
+#else
+# define MOZ_ASSERT(...) do { } while(0)
+#endif /* DEBUG */
+
+/*
+ * MOZ_ASSERT_IF(cond1, cond2) is equivalent to MOZ_ASSERT(cond2) if cond1 is
+ * true.
+ *
+ * MOZ_ASSERT_IF(isPrime(num), num == 2 || isOdd(num));
+ *
+ * As with MOZ_ASSERT, MOZ_ASSERT_IF has effect only in debug builds. It is
+ * designed to catch bugs during debugging, not "in the field".
+ */
+#ifdef DEBUG
+# define MOZ_ASSERT_IF(cond, expr) \
+ do { \
+ if (cond) \
+ MOZ_ASSERT(expr); \
+ } while (0)
+#else
+# define MOZ_ASSERT_IF(cond, expr) do { } while (0)
+#endif
+
+/*
+ * MOZ_NOT_REACHED_MARKER() expands to an expression which states that it is
+ * undefined behavior for execution to reach this point. No guarantees are made
+ * about what will happen if this is reached at runtime. Most code should
+ * probably use the higher level MOZ_NOT_REACHED, which uses this when
+ * appropriate.
+ */
+#if defined(__clang__)
+# define MOZ_NOT_REACHED_MARKER() __builtin_unreachable()
+#elif defined(__GNUC__)
+ /*
+ * __builtin_unreachable() was implemented in gcc 4.5. If we don't have
+ * that, call a noreturn function; abort() will do nicely. Qualify the call
+ * in C++ in case there's another abort() visible in local scope.
+ */
+# if MOZ_GCC_VERSION_AT_LEAST(4, 5, 0)
+# define MOZ_NOT_REACHED_MARKER() __builtin_unreachable()
+# else
+# ifdef __cplusplus
+# define MOZ_NOT_REACHED_MARKER() ::abort()
+# else
+# define MOZ_NOT_REACHED_MARKER() abort()
+# endif
+# endif
+#elif defined(_MSC_VER)
+# define MOZ_NOT_REACHED_MARKER() __assume(0)
+#else
+# ifdef __cplusplus
+# define MOZ_NOT_REACHED_MARKER() ::abort()
+# else
+# define MOZ_NOT_REACHED_MARKER() abort()
+# endif
+#endif
+
+/*
+ * MOZ_NOT_REACHED(reason) indicates that the given point can't be reached
+ * during execution: simply reaching that point in execution is a bug. It takes
+ * as an argument an error message indicating the reason why that point should
+ * not have been reachable.
+ *
+ * // ...in a language parser...
+ * void handle(BooleanLiteralNode node)
+ * {
+ * if (node.isTrue())
+ * handleTrueLiteral();
+ * else if (node.isFalse())
+ * handleFalseLiteral();
+ * else
+ * MOZ_NOT_REACHED("boolean literal that's not true or false?");
+ * }
+ */
+#if defined(DEBUG)
+# define MOZ_NOT_REACHED(reason) \
+ do { \
+ MOZ_ASSERT(false, reason); \
+ MOZ_NOT_REACHED_MARKER(); \
+ } while (0)
+#else
+# define MOZ_NOT_REACHED(reason) MOZ_NOT_REACHED_MARKER()
+#endif
+
+/*
+ * MOZ_ALWAYS_TRUE(expr) and MOZ_ALWAYS_FALSE(expr) always evaluate the provided
+ * expression, in debug builds and in release builds both. Then, in debug
+ * builds only, the value of the expression is asserted either true or false
+ * using MOZ_ASSERT.
+ */
+#ifdef DEBUG
+# define MOZ_ALWAYS_TRUE(expr) MOZ_ASSERT((expr))
+# define MOZ_ALWAYS_FALSE(expr) MOZ_ASSERT(!(expr))
+#else
+# define MOZ_ALWAYS_TRUE(expr) ((void)(expr))
+# define MOZ_ALWAYS_FALSE(expr) ((void)(expr))
+#endif
+
+#endif /* mozilla_Assertions_h_ */
diff --git a/mfbt/Atomics.h b/mfbt/Atomics.h
new file mode 100644
index 0000000..b9eaae2
--- /dev/null
+++ b/mfbt/Atomics.h
@@ -0,0 +1,960 @@
+/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+/*
+ * Implements (almost always) lock-free atomic operations. The operations here
+ * are a subset of that which can be found in C++11's <atomic> header, with a
+ * different API to enforce consistent memory ordering constraints.
+ *
+ * Anyone caught using |volatile| for inter-thread memory safety needs to be
+ * sent a copy of this header and the C++11 standard.
+ */
+
+#ifndef mozilla_Atomics_h_
+#define mozilla_Atomics_h_
+
+#include "mozilla/Assertions.h"
+#include "mozilla/TypeTraits.h"
+
+#include <stdint.h>
+
+/*
+ * Our minimum deployment target on clang/OS X is OS X 10.6, whose SDK
+ * does not have <atomic>. So be sure to check for <atomic> support
+ * along with C++0x support.
+ */
+#if defined(__clang__)
+ /*
+ * clang doesn't like libstdc++'s version of <atomic> before GCC 4.7,
+ * due to the loose typing of the __sync_* family of functions done by
+ * GCC. We do not have a particularly good way to detect this sort of
+ * case at this point, so just assume that if we're on a Linux system,
+ * we can't use the system's <atomic>.
+ *
+ * OpenBSD uses an old libstdc++ 4.2.1 and thus doesnt have <atomic>.
+ */
+# if !defined(__linux__) && !defined(__OpenBSD__) && \
+ (__cplusplus >= 201103L || defined(__GXX_EXPERIMENTAL_CXX0X__)) && \
+ __has_include(<atomic>)
+# define MOZ_HAVE_CXX11_ATOMICS
+# endif
+/*
+ * Android uses a different C++ standard library that does not provide
+ * support for <atomic>
+ */
+#elif defined(__GNUC__) && !defined(__ANDROID__)
+# include "mozilla/Compiler.h"
+# if (defined(__GXX_EXPERIMENTAL_CXX0X__) || __cplusplus >= 201103L) && \
+ MOZ_GCC_VERSION_AT_LEAST(4, 5, 2)
+# define MOZ_HAVE_CXX11_ATOMICS
+# endif
+#elif defined(_MSC_VER) && _MSC_VER >= 1700
+# define MOZ_HAVE_CXX11_ATOMICS
+#endif
+
+namespace mozilla {
+
+/**
+ * An enum of memory ordering possibilities for atomics.
+ *
+ * Memory ordering is the observable state of distinct values in memory.
+ * (It's a separate concept from atomicity, which concerns whether an
+ * operation can ever be observed in an intermediate state. Don't
+ * conflate the two!) Given a sequence of operations in source code on
+ * memory, it is *not* always the case that, at all times and on all
+ * cores, those operations will appear to have occurred in that exact
+ * sequence. First, the compiler might reorder that sequence, if it
+ * thinks another ordering will be more efficient. Second, the CPU may
+ * not expose so consistent a view of memory. CPUs will often perform
+ * their own instruction reordering, above and beyond that performed by
+ * the compiler. And each core has its own memory caches, and accesses
+ * (reads and writes both) to "memory" may only resolve to out-of-date
+ * cache entries -- not to the "most recently" performed operation in
+ * some global sense. Any access to a value that may be used by
+ * multiple threads, potentially across multiple cores, must therefore
+ * have a memory ordering imposed on it, for all code on all
+ * threads/cores to have a sufficiently coherent worldview.
+ *
+ * http://gcc.gnu.org/wiki/Atomic/GCCMM/AtomicSync and
+ * http://en.cppreference.com/w/cpp/atomic/memory_order go into more
+ * detail on all this, including examples of how each mode works.
+ *
+ * Note that for simplicity and practicality, not all of the modes in
+ * C++11 are supported. The missing C++11 modes are either subsumed by
+ * the modes we provide below, or not relevant for the CPUs we support
+ * in Gecko. These three modes are confusing enough as it is!
+ */
+enum MemoryOrdering {
+ /*
+ * Relaxed ordering is the simplest memory ordering: none at all.
+ * When the result of a write is observed, nothing may be inferred
+ * about other memory. Writes ostensibly performed "before" on the
+ * writing thread may not yet be visible. Writes performed "after" on
+ * the writing thread may already be visible, if the compiler or CPU
+ * reordered them. (The latter can happen if reads and/or writes get
+ * held up in per-processor caches.) Relaxed ordering means
+ * operations can always use cached values (as long as the actual
+ * updates to atomic values actually occur, correctly, eventually), so
+ * it's usually the fastest sort of atomic access. For this reason,
+ * *it's also the most dangerous kind of access*.
+ *
+ * Relaxed ordering is good for things like process-wide statistics
+ * counters that don't need to be consistent with anything else, so
+ * long as updates themselves are atomic. (And so long as any
+ * observations of that value can tolerate being out-of-date -- if you
+ * need some sort of up-to-date value, you need some sort of other
+ * synchronizing operation.) It's *not* good for locks, mutexes,
+ * reference counts, etc. that mediate access to other memory, or must
+ * be observably consistent with other memory.
+ *
+ * x86 architectures don't take advantage of the optimization
+ * opportunities that relaxed ordering permits. Thus it's possible
+ * that using relaxed ordering will "work" on x86 but fail elsewhere
+ * (ARM, say, which *does* implement non-sequentially-consistent
+ * relaxed ordering semantics). Be extra-careful using relaxed
+ * ordering if you can't easily test non-x86 architectures!
+ */
+ Relaxed,
+ /*
+ * When an atomic value is updated with ReleaseAcquire ordering, and
+ * that new value is observed with ReleaseAcquire ordering, prior
+ * writes (atomic or not) are also observable. What ReleaseAcquire
+ * *doesn't* give you is any observable ordering guarantees for
+ * ReleaseAcquire-ordered operations on different objects. For
+ * example, if there are two cores that each perform ReleaseAcquire
+ * operations on separate objects, each core may or may not observe
+ * the operations made by the other core. The only way the cores can
+ * be synchronized with ReleaseAcquire is if they both
+ * ReleaseAcquire-access the same object. This implies that you can't
+ * necessarily describe some global total ordering of ReleaseAcquire
+ * operations.
+ *
+ * ReleaseAcquire ordering is good for (as the name implies) atomic
+ * operations on values controlling ownership of things: reference
+ * counts, mutexes, and the like. However, if you are thinking about
+ * using these to implement your own locks or mutexes, you should take
+ * a good, hard look at actual lock or mutex primitives first.
+ */
+ ReleaseAcquire,
+ /*
+ * When an atomic value is updated with SequentiallyConsistent
+ * ordering, all writes observable when the update is observed, just
+ * as with ReleaseAcquire ordering. But, furthermore, a global total
+ * ordering of SequentiallyConsistent operations *can* be described.
+ * For example, if two cores perform SequentiallyConsistent operations
+ * on separate objects, one core will observably perform its update
+ * (and all previous operations will have completed), then the other
+ * core will observably perform its update (and all previous
+ * operations will have completed). (Although those previous
+ * operations aren't themselves ordered -- they could be intermixed,
+ * or ordered if they occur on atomic values with ordering
+ * requirements.) SequentiallyConsistent is the *simplest and safest*
+ * ordering of atomic operations -- it's always as if one operation
+ * happens, then another, then another, in some order -- and every
+ * core observes updates to happen in that single order. Because it
+ * has the most synchronization requirements, operations ordered this
+ * way also tend to be slowest.
+ *
+ * SequentiallyConsistent ordering can be desirable when multiple
+ * threads observe objects, and they all have to agree on the
+ * observable order of changes to them. People expect
+ * SequentiallyConsistent ordering, even if they shouldn't, when
+ * writing code, atomic or otherwise. SequentiallyConsistent is also
+ * the ordering of choice when designing lockless data structures. If
+ * you don't know what order to use, use this one.
+ */
+ SequentiallyConsistent,
+};
+
+} // namespace mozilla
+
+// Build up the underlying intrinsics.
+#ifdef MOZ_HAVE_CXX11_ATOMICS
+
+# include <atomic>
+
+namespace mozilla {
+namespace detail {
+
+template<MemoryOrdering Order> struct AtomicOrderConstraints;
+
+template<>
+struct AtomicOrderConstraints<Relaxed>
+{
+ static const std::memory_order AtomicRMWOrder = std::memory_order_relaxed;
+ static const std::memory_order LoadOrder = std::memory_order_relaxed;
+ static const std::memory_order StoreOrder = std::memory_order_relaxed;
+};
+
+template<>
+struct AtomicOrderConstraints<ReleaseAcquire>
+{
+ static const std::memory_order AtomicRMWOrder = std::memory_order_acq_rel;
+ static const std::memory_order LoadOrder = std::memory_order_acquire;
+ static const std::memory_order StoreOrder = std::memory_order_release;
+};
+
+template<>
+struct AtomicOrderConstraints<SequentiallyConsistent>
+{
+ static const std::memory_order AtomicRMWOrder = std::memory_order_seq_cst;
+ static const std::memory_order LoadOrder = std::memory_order_seq_cst;
+ static const std::memory_order StoreOrder = std::memory_order_seq_cst;
+};
+
+template<typename T, MemoryOrdering Order>
+struct IntrinsicBase
+{
+ typedef std::atomic<T> ValueType;
+ typedef AtomicOrderConstraints<Order> OrderedOp;
+};
+
+template<typename T, MemoryOrdering Order>
+struct IntrinsicMemoryOps : public IntrinsicBase<T, Order>
+{
+ typedef IntrinsicBase<T, Order> Base;
+ static T load(const typename Base::ValueType& ptr) {
+ return ptr.load(Base::OrderedOp::LoadOrder);
+ }
+ static void store(typename Base::ValueType& ptr, T val) {
+ ptr.store(val, Base::OrderedOp::StoreOrder);
+ }
+ static T exchange(typename Base::ValueType& ptr, T val) {
+ return ptr.exchange(val, Base::OrderedOp::AtomicRMWOrder);
+ }
+ static bool compareExchange(typename Base::ValueType& ptr, T oldVal, T newVal) {
+ return ptr.compare_exchange_strong(oldVal, newVal, Base::OrderedOp::AtomicRMWOrder);
+ }
+};
+
+template<typename T, MemoryOrdering Order>
+struct IntrinsicAddSub : public IntrinsicBase<T, Order>
+{
+ typedef IntrinsicBase<T, Order> Base;
+ static T add(typename Base::ValueType& ptr, T val) {
+ return ptr.fetch_add(val, Base::OrderedOp::AtomicRMWOrder);
+ }
+ static T sub(typename Base::ValueType& ptr, T val) {
+ return ptr.fetch_sub(val, Base::OrderedOp::AtomicRMWOrder);
+ }
+};
+
+template<typename T, MemoryOrdering Order>
+struct IntrinsicAddSub<T*, Order> : public IntrinsicBase<T*, Order>
+{
+ typedef IntrinsicBase<T*, Order> Base;
+ static T* add(typename Base::ValueType& ptr, ptrdiff_t val) {
+ return ptr.fetch_add(fixupAddend(val), Base::OrderedOp::AtomicRMWOrder);
+ }
+ static T* sub(typename Base::ValueType& ptr, ptrdiff_t val) {
+ return ptr.fetch_sub(fixupAddend(val), Base::OrderedOp::AtomicRMWOrder);
+ }
+ private:
+ /*
+ * GCC 4.6's <atomic> header has a bug where adding X to an
+ * atomic<T*> is not the same as adding X to a T*. Hence the need
+ * for this function to provide the correct addend.
+ */
+ static ptrdiff_t fixupAddend(ptrdiff_t val) {
+#if defined(__clang__) || defined(_MSC_VER)
+ return val;
+#elif defined(__GNUC__) && MOZ_GCC_VERSION_AT_LEAST(4, 6, 0) && \
+ !MOZ_GCC_VERSION_AT_LEAST(4, 7, 0)
+ return val * sizeof(T);
+#else
+ return val;
+#endif
+ }
+};
+
+template<typename T, MemoryOrdering Order>
+struct IntrinsicIncDec : public IntrinsicAddSub<T, Order>
+{
+ typedef IntrinsicBase<T, Order> Base;
+ static T inc(typename Base::ValueType& ptr) {
+ return IntrinsicAddSub<T, Order>::add(ptr, 1);
+ }
+ static T dec(typename Base::ValueType& ptr) {
+ return IntrinsicAddSub<T, Order>::sub(ptr, 1);
+ }
+};
+
+template<typename T, MemoryOrdering Order>
+struct AtomicIntrinsics : public IntrinsicMemoryOps<T, Order>,
+ public IntrinsicIncDec<T, Order>
+{
+ typedef IntrinsicBase<T, Order> Base;
+ static T or_(typename Base::ValueType& ptr, T val) {
+ return ptr.fetch_or(val, Base::OrderedOp::AtomicRMWOrder);
+ }
+ static T xor_(typename Base::ValueType& ptr, T val) {
+ return ptr.fetch_xor(val, Base::OrderedOp::AtomicRMWOrder);
+ }
+ static T and_(typename Base::ValueType& ptr, T val) {
+ return ptr.fetch_and(val, Base::OrderedOp::AtomicRMWOrder);
+ }
+};
+
+template<typename T, MemoryOrdering Order>
+struct AtomicIntrinsics<T*, Order>
+ : public IntrinsicMemoryOps<T*, Order>, public IntrinsicIncDec<T*, Order>
+{
+};
+
+} // namespace detail
+} // namespace mozilla
+
+#elif defined(__GNUC__)
+
+namespace mozilla {
+namespace detail {
+
+/*
+ * The __sync_* family of intrinsics is documented here:
+ *
+ * http://gcc.gnu.org/onlinedocs/gcc-4.6.4/gcc/Atomic-Builtins.html
+ *
+ * While these intrinsics are deprecated in favor of the newer __atomic_*
+ * family of intrincs:
+ *
+ * http://gcc.gnu.org/onlinedocs/gcc-4.7.3/gcc/_005f_005fatomic-Builtins.html
+ *
+ * any GCC version that supports the __atomic_* intrinsics will also support
+ * the <atomic> header and so will be handled above. We provide a version of
+ * atomics using the __sync_* intrinsics to support older versions of GCC.
+ *
+ * All __sync_* intrinsics that we use below act as full memory barriers, for
+ * both compiler and hardware reordering, except for __sync_lock_test_and_set,
+ * which is a only an acquire barrier. When we call __sync_lock_test_and_set,
+ * we add a barrier above it as appropriate.
+ */
+
+template<MemoryOrdering Order> struct Barrier;
+
+/*
+ * Some processors (in particular, x86) don't require quite so many calls to
+ * __sync_sychronize as our specializations of Barrier produce. If
+ * performance turns out to be an issue, defining these specializations
+ * on a per-processor basis would be a good first tuning step.
+ */
+
+template<>
+struct Barrier<Relaxed>
+{
+ static void beforeLoad() {}
+ static void afterLoad() {}
+ static void beforeStore() {}
+ static void afterStore() {}
+};
+
+template<>
+struct Barrier<ReleaseAcquire>
+{
+ static void beforeLoad() {}
+ static void afterLoad() { __sync_synchronize(); }
+ static void beforeStore() { __sync_synchronize(); }
+ static void afterStore() {}
+};
+
+template<>
+struct Barrier<SequentiallyConsistent>
+{
+ static void beforeLoad() { __sync_synchronize(); }
+ static void afterLoad() { __sync_synchronize(); }
+ static void beforeStore() { __sync_synchronize(); }
+ static void afterStore() { __sync_synchronize(); }
+};
+
+template<typename T, MemoryOrdering Order>
+struct IntrinsicMemoryOps
+{
+ static T load(const T& ptr) {
+ Barrier<Order>::beforeLoad();
+ T val = ptr;
+ Barrier<Order>::afterLoad();
+ return val;
+ }
+ static void store(T& ptr, T val) {
+ Barrier<Order>::beforeStore();
+ ptr = val;
+ Barrier<Order>::afterStore();
+ }
+ static T exchange(T& ptr, T val) {
+ // __sync_lock_test_and_set is only an acquire barrier; loads and stores
+ // can't be moved up from after to before it, but they can be moved down
+ // from before to after it. We may want a stricter ordering, so we need
+ // an explicit barrier.
+
+ Barrier<Order>::beforeStore();
+ return __sync_lock_test_and_set(&ptr, val);
+ }
+ static bool compareExchange(T& ptr, T oldVal, T newVal) {
+ return __sync_bool_compare_and_swap(&ptr, oldVal, newVal);
+ }
+};
+
+template<typename T>
+struct IntrinsicAddSub
+{
+ typedef T ValueType;
+ static T add(T& ptr, T val) {
+ return __sync_fetch_and_add(&ptr, val);
+ }
+ static T sub(T& ptr, T val) {
+ return __sync_fetch_and_sub(&ptr, val);
+ }
+};
+
+template<typename T>
+struct IntrinsicAddSub<T*>
+{
+ typedef T* ValueType;
+ /*
+ * The reinterpret_casts are needed so that
+ * __sync_fetch_and_{add,sub} will properly type-check.
+ *
+ * Also, these functions do not provide standard semantics for
+ * pointer types, so we need to adjust the addend.
+ */
+ static ValueType add(ValueType& ptr, ptrdiff_t val) {
+ ValueType amount = reinterpret_cast<ValueType>(val * sizeof(T));
+ return __sync_fetch_and_add(&ptr, amount);
+ }
+ static ValueType sub(ValueType& ptr, ptrdiff_t val) {
+ ValueType amount = reinterpret_cast<ValueType>(val * sizeof(T));
+ return __sync_fetch_and_sub(&ptr, amount);
+ }
+};
+
+template<typename T>
+struct IntrinsicIncDec : public IntrinsicAddSub<T>
+{
+ static T inc(T& ptr) { return IntrinsicAddSub<T>::add(ptr, 1); }
+ static T dec(T& ptr) { return IntrinsicAddSub<T>::sub(ptr, 1); }
+};
+
+template<typename T, MemoryOrdering Order>
+struct AtomicIntrinsics : public IntrinsicMemoryOps<T, Order>,
+ public IntrinsicIncDec<T>
+{
+ static T or_(T& ptr, T val) {
+ return __sync_fetch_and_or(&ptr, val);
+ }
+ static T xor_(T& ptr, T val) {
+ return __sync_fetch_and_xor(&ptr, val);
+ }
+ static T and_(T& ptr, T val) {
+ return __sync_fetch_and_and(&ptr, val);
+ }
+};
+
+template<typename T, MemoryOrdering Order>
+struct AtomicIntrinsics<T*, Order> : public IntrinsicMemoryOps<T*, Order>,
+ public IntrinsicIncDec<T*>
+{
+};
+
+} // namespace detail
+} // namespace mozilla
+
+#elif defined(_MSC_VER)
+
+/*
+ * Windows comes with a full complement of atomic operations.
+ * Unfortunately, most of those aren't available for Windows XP (even if
+ * the compiler supports intrinsics for them), which is the oldest
+ * version of Windows we support. Therefore, we only provide operations
+ * on 32-bit datatypes for 32-bit Windows versions; for 64-bit Windows
+ * versions, we support 64-bit datatypes as well.
+ *
+ * To avoid namespace pollution issues, we declare whatever functions we
+ * need ourselves.
+ */
+
+extern "C" {
+long __cdecl _InterlockedExchangeAdd(long volatile* dst, long value);
+long __cdecl _InterlockedOr(long volatile* dst, long value);
+long __cdecl _InterlockedXor(long volatile* dst, long value);
+long __cdecl _InterlockedAnd(long volatile* dst, long value);
+long __cdecl _InterlockedExchange(long volatile *dst, long value);
+long __cdecl _InterlockedCompareExchange(long volatile *dst, long newVal, long oldVal);
+}
+
+# pragma intrinsic(_InterlockedExchangeAdd)
+# pragma intrinsic(_InterlockedOr)
+# pragma intrinsic(_InterlockedXor)
+# pragma intrinsic(_InterlockedAnd)
+# pragma intrinsic(_InterlockedExchange)
+# pragma intrinsic(_InterlockedCompareExchange)
+
+namespace mozilla {
+namespace detail {
+
+# if !defined(_M_IX86) && !defined(_M_X64)
+ /*
+ * The implementations below are optimized for x86ish systems. You
+ * will have to modify them if you are porting to Windows on a
+ * different architecture.
+ */
+# error "Unknown CPU type"
+# endif
+
+/*
+ * The PrimitiveIntrinsics template should define |Type|, the datatype of size
+ * DataSize upon which we operate, and the following eight functions.
+ *
+ * static Type add(Type* ptr, Type val);
+ * static Type sub(Type* ptr, Type val);
+ * static Type or_(Type* ptr, Type val);
+ * static Type xor_(Type* ptr, Type val);
+ * static Type and_(Type* ptr, Type val);
+ *
+ * These functions perform the obvious operation on the value contained in
+ * |*ptr| combined with |val| and return the value previously stored in
+ * |*ptr|.
+ *
+ * static void store(Type* ptr, Type val);
+ *
+ * This function atomically stores |val| into |*ptr| and must provide a full
+ * memory fence after the store to prevent compiler and hardware instruction
+ * reordering. It should also act as a compiler barrier to prevent reads and
+ * writes from moving to after the store.
+ *
+ * static Type exchange(Type* ptr, Type val);
+ *
+ * This function atomically stores |val| into |*ptr| and returns the previous
+ * contents of *ptr;
+ *
+ * static bool compareExchange(Type* ptr, Type oldVal, Type newVal);
+ *
+ * This function atomically performs the following operation:
+ *
+ * if (*ptr == oldVal) {
+ * *ptr = newVal;
+ * return true;
+ * } else {
+ * return false;
+ * }
+ *
+ */
+template<size_t DataSize> struct PrimitiveIntrinsics;
+
+template<>
+struct PrimitiveIntrinsics<4>
+{
+ typedef long Type;
+
+ static Type add(Type* ptr, Type val) {
+ return _InterlockedExchangeAdd(ptr, val);
+ }
+ static Type sub(Type* ptr, Type val) {
+ /*
+ * _InterlockedExchangeSubtract isn't available before Windows 7,
+ * and we must support Windows XP.
+ */
+ return _InterlockedExchangeAdd(ptr, -val);
+ }
+ static Type or_(Type* ptr, Type val) {
+ return _InterlockedOr(ptr, val);
+ }
+ static Type xor_(Type* ptr, Type val) {
+ return _InterlockedXor(ptr, val);
+ }
+ static Type and_(Type* ptr, Type val) {
+ return _InterlockedAnd(ptr, val);
+ }
+ static void store(Type* ptr, Type val) {
+ _InterlockedExchange(ptr, val);
+ }
+ static Type exchange(Type* ptr, Type val) {
+ return _InterlockedExchange(ptr, val);
+ }
+ static bool compareExchange(Type* ptr, Type oldVal, Type newVal) {
+ return _InterlockedCompareExchange(ptr, newVal, oldVal) == oldVal;
+ }
+};
+
+# if defined(_M_X64)
+
+extern "C" {
+long long __cdecl _InterlockedExchangeAdd64(long long volatile* dst,
+ long long value);
+long long __cdecl _InterlockedOr64(long long volatile* dst,
+ long long value);
+long long __cdecl _InterlockedXor64(long long volatile* dst,
+ long long value);
+long long __cdecl _InterlockedAnd64(long long volatile* dst,
+ long long value);
+long long __cdecl _InterlockedExchange64(long long volatile* dst,
+ long long value);
+long long __cdecl _InterlockedCompareExchange64(long long volatile* dst,
+ long long newVal,
+ long long oldVal);
+}
+
+# pragma intrinsic(_InterlockedExchangeAdd64)
+# pragma intrinsic(_InterlockedOr64)
+# pragma intrinsic(_InterlockedXor64)
+# pragma intrinsic(_InterlockedAnd64)
+# pragma intrinsic(_InterlockedExchange64)
+# pragma intrinsic(_InterlockedCompareExchange64)
+
+template <>
+struct PrimitiveIntrinsics<8>
+{
+ typedef __int64 Type;
+
+ static Type add(Type* ptr, Type val) {
+ return _InterlockedExchangeAdd64(ptr, val);
+ }
+ static Type sub(Type* ptr, Type val) {
+ /*
+ * There is no _InterlockedExchangeSubtract64.
+ */
+ return _InterlockedExchangeAdd64(ptr, -val);
+ }
+ static Type or_(Type* ptr, Type val) {
+ return _InterlockedOr64(ptr, val);
+ }
+ static Type xor_(Type* ptr, Type val) {
+ return _InterlockedXor64(ptr, val);
+ }
+ static Type and_(Type* ptr, Type val) {
+ return _InterlockedAnd64(ptr, val);
+ }
+ static void store(Type* ptr, Type val) {
+ _InterlockedExchange64(ptr, val);
+ }
+ static Type exchange(Type* ptr, Type val) {
+ return _InterlockedExchange64(ptr, val);
+ }
+ static bool compareExchange(Type* ptr, Type oldVal, Type newVal) {
+ return _InterlockedCompareExchange64(ptr, newVal, oldVal) == oldVal;
+ }
+};
+
+# endif
+
+extern "C" { void _ReadWriteBarrier(); }
+
+# pragma intrinsic(_ReadWriteBarrier)
+
+template<MemoryOrdering Order> struct Barrier;
+
+/*
+ * We do not provide an afterStore method in Barrier, as Relaxed and
+ * ReleaseAcquire orderings do not require one, and the required barrier
+ * for SequentiallyConsistent is handled by PrimitiveIntrinsics.
+ */
+
+template<>
+struct Barrier<Relaxed>
+{
+ static void beforeLoad() {}
+ static void afterLoad() {}
+ static void beforeStore() {}
+};
+
+template<>
+struct Barrier<ReleaseAcquire>
+{
+ static void beforeLoad() {}
+ static void afterLoad() { _ReadWriteBarrier(); }
+ static void beforeStore() { _ReadWriteBarrier(); }
+};
+
+template<>
+struct Barrier<SequentiallyConsistent>
+{
+ static void beforeLoad() { _ReadWriteBarrier(); }
+ static void afterLoad() { _ReadWriteBarrier(); }
+ static void beforeStore() { _ReadWriteBarrier(); }
+};
+
+template<typename PrimType, typename T>
+struct CastHelper
+{
+ static PrimType toPrimType(T val) { return static_cast<PrimType>(val); }
+ static T fromPrimType(PrimType val) { return static_cast<T>(val); }
+};
+
+template<typename PrimType, typename T>
+struct CastHelper<PrimType, T*>
+{
+ static PrimType toPrimType(T* val) { return reinterpret_cast<PrimType>(val); }
+ static T* fromPrimType(PrimType val) { return reinterpret_cast<T*>(val); }
+};
+
+template<typename T>
+struct IntrinsicBase
+{
+ typedef T ValueType;
+ typedef PrimitiveIntrinsics<sizeof(T)> Primitives;
+ typedef typename Primitives::Type PrimType;
+ MOZ_STATIC_ASSERT(sizeof(PrimType) == sizeof(T),
+ "Selection of PrimitiveIntrinsics was wrong");
+ typedef CastHelper<PrimType, T> Cast;
+};
+
+template<typename T, MemoryOrdering Order>
+struct IntrinsicMemoryOps : public IntrinsicBase<T>
+{
+ static ValueType load(const ValueType& ptr) {
+ Barrier<Order>::beforeLoad();
+ ValueType val = ptr;
+ Barrier<Order>::afterLoad();
+ return val;
+ }
+ static void store(ValueType& ptr, ValueType val) {
+ // For SequentiallyConsistent, Primitives::store() will generate the
+ // proper memory fence. Everything else just needs a barrier before
+ // the store.
+ if (Order == SequentiallyConsistent) {
+ Primitives::store(reinterpret_cast<PrimType*>(&ptr),
+ Cast::toPrimType(val));
+ } else {
+ Barrier<Order>::beforeStore();
+ ptr = val;
+ }
+ }
+ static ValueType exchange(ValueType& ptr, ValueType val) {
+ PrimType oldval =
+ Primitives::exchange(reinterpret_cast<PrimType*>(&ptr),
+ Cast::toPrimType(val));
+ return Cast::fromPrimType(oldval);
+ }
+ static bool compareExchange(ValueType& ptr, ValueType oldVal, ValueType newVal) {
+ return Primitives::compareExchange(reinterpret_cast<PrimType*>(&ptr),
+ Cast::toPrimType(oldVal),
+ Cast::toPrimType(newVal));
+ }
+};
+
+template<typename T>
+struct IntrinsicApplyHelper : public IntrinsicBase<T>
+{
+ typedef PrimType (*BinaryOp)(PrimType*, PrimType);
+ typedef PrimType (*UnaryOp)(PrimType*);
+
+ static ValueType applyBinaryFunction(BinaryOp op, ValueType& ptr,
+ ValueType val) {
+ PrimType* primTypePtr = reinterpret_cast<PrimType*>(&ptr);
+ PrimType primTypeVal = Cast::toPrimType(val);
+ return Cast::fromPrimType(op(primTypePtr, primTypeVal));
+ }
+
+ static ValueType applyUnaryFunction(UnaryOp op, ValueType& ptr) {
+ PrimType* primTypePtr = reinterpret_cast<PrimType*>(&ptr);
+ return Cast::fromPrimType(op(primTypePtr));
+ }
+};
+
+template<typename T>
+struct IntrinsicAddSub : public IntrinsicApplyHelper<T>
+{
+ static ValueType add(ValueType& ptr, ValueType val) {
+ return applyBinaryFunction(&Primitives::add, ptr, val);
+ }
+ static ValueType sub(ValueType& ptr, ValueType val) {
+ return applyBinaryFunction(&Primitives::sub, ptr, val);
+ }
+};
+
+template<typename T>
+struct IntrinsicAddSub<T*> : public IntrinsicApplyHelper<T*>
+{
+ static ValueType add(ValueType& ptr, ptrdiff_t amount) {
+ return applyBinaryFunction(&Primitives::add, ptr,
+ (ValueType)(amount * sizeof(ValueType)));
+ }
+ static ValueType sub(ValueType& ptr, ptrdiff_t amount) {
+ return applyBinaryFunction(&Primitives::sub, ptr,
+ (ValueType)(amount * sizeof(ValueType)));
+ }
+};
+
+template<typename T>
+struct IntrinsicIncDec : public IntrinsicAddSub<T>
+{
+ static ValueType inc(ValueType& ptr) { return add(ptr, 1); }
+ static ValueType dec(ValueType& ptr) { return sub(ptr, 1); }
+};
+
+template<typename T, MemoryOrdering Order>
+struct AtomicIntrinsics : public IntrinsicMemoryOps<T, Order>,
+ public IntrinsicIncDec<T>
+{
+ static ValueType or_(ValueType& ptr, T val) {
+ return applyBinaryFunction(&Primitives::or_, ptr, val);
+ }
+ static ValueType xor_(ValueType& ptr, T val) {
+ return applyBinaryFunction(&Primitives::xor_, ptr, val);
+ }
+ static ValueType and_(ValueType& ptr, T val) {
+ return applyBinaryFunction(&Primitives::and_, ptr, val);
+ }
+};
+
+template<typename T, MemoryOrdering Order>
+struct AtomicIntrinsics<T*, Order> : public IntrinsicMemoryOps<T*, Order>,
+ public IntrinsicIncDec<T*>
+{
+};
+
+} // namespace detail
+} // namespace mozilla
+
+#else
+# error "Atomic compiler intrinsics are not supported on your platform"
+#endif
+
+namespace mozilla {
+
+namespace detail {
+
+template<typename T, MemoryOrdering Order>
+class AtomicBase
+{
+ protected:
+ typedef typename detail::AtomicIntrinsics<T, Order> Intrinsics;
+ typename Intrinsics::ValueType mValue;
+
+ public:
+ AtomicBase() : mValue() {}
+ AtomicBase(T aInit) { Intrinsics::store(mValue, aInit); }
+
+ T operator++(int) { return Intrinsics::inc(mValue); }
+ T operator--(int) { return Intrinsics::dec(mValue); }
+ T operator++() { return Intrinsics::inc(mValue) + 1; }
+ T operator--() { return Intrinsics::dec(mValue) - 1; }
+
+ operator T() const { return Intrinsics::load(mValue); }
+
+ /**
+ * Performs an atomic swap operation. aValue is stored and the previous
+ * value of this variable is returned.
+ */
+ T exchange(T aValue) {
+ return Intrinsics::exchange(mValue, aValue);
+ }
+ /**
+ * Performs an atomic compare-and-swap operation and returns true if it
+ * succeeded. This is equivalent to atomically doing
+ *
+ * if (mValue == aOldValue) {
+ * mValue = aNewValue;
+ * return true;
+ * } else {
+ * return false;
+ * }
+ */
+ bool compareExchange(T aOldValue, T aNewValue) {
+ return Intrinsics::compareExchange(mValue, aOldValue, aNewValue);
+ }
+
+ private:
+ template<MemoryOrdering AnyOrder>
+ AtomicBase(const AtomicBase<T, AnyOrder>& aCopy) MOZ_DELETE;
+};
+
+} // namespace detail
+
+/**
+ * A wrapper for a type that enforces that all memory accesses are atomic.
+ *
+ * In general, where a variable |T foo| exists, |Atomic<T> foo| can be
+ * used in its place. In addition to atomic store and load operations,
+ * compound assignment and increment/decrement operators are implemented
+ * which perform the corresponding read-modify-write operation
+ * atomically. Finally, an atomic swap method is provided.
+ *
+ * Atomic accesses are sequentially consistent by default. You should
+ * use the default unless you are tall enough to ride the
+ * memory-ordering roller coaster (if you're not sure, you aren't) and
+ * you have a compelling reason to do otherwise.
+ *
+ * There is one exception to the case of atomic memory accesses: providing an
+ * initial value of the atomic value is not guaranteed to be atomic. This is a
+ * deliberate design choice that enables static atomic variables to be declared
+ * without introducing extra static constructors.
+ */
+template<typename T, MemoryOrdering Order = SequentiallyConsistent>
+class Atomic : public detail::AtomicBase<T, Order>
+{
+ // We only support 32-bit types on 32-bit Windows, which constrains our
+ // implementation elsewhere. But we support pointer-sized types everywhere.
+ MOZ_STATIC_ASSERT(sizeof(T) == 4 || (sizeof(uintptr_t) == 8 && sizeof(T) == 8),
+ "mozilla/Atomics.h only supports 32-bit and pointer-sized types");
+ // Regardless of the OS, we only support integral types here.
+ MOZ_STATIC_ASSERT(IsIntegral<T>::value, "can only have integral atomic variables");
+
+ typedef typename detail::AtomicBase<T, Order> Base;
+
+ public:
+ Atomic() : detail::AtomicBase<T, Order>() {}
+ Atomic(T aInit) : detail::AtomicBase<T, Order>(aInit) {}
+
+ T operator+=(T delta) { return Base::Intrinsics::add(Base::mValue, delta) + delta; }
+ T operator-=(T delta) { return Base::Intrinsics::sub(Base::mValue, delta) - delta; }
+ T operator|=(T val) { return Base::Intrinsics::or_(Base::mValue, val) | val; }
+ T operator^=(T val) { return Base::Intrinsics::xor_(Base::mValue, val) ^ val; }
+ T operator&=(T val) { return Base::Intrinsics::and_(Base::mValue, val) & val; }
+
+ T operator=(T aValue) {
+ Base::Intrinsics::store(Base::mValue, aValue);
+ return aValue;
+ }
+
+ private:
+ Atomic(Atomic<T, Order>& aOther) MOZ_DELETE;
+};
+
+/**
+ * A partial specialization of Atomic for pointer variables.
+ *
+ * Like Atomic<T>, Atomic<T*> is equivalent in most respects to a regular T*
+ * variable. An atomic compare-and-swap primitive for pointer variables is
+ * provided, as are atomic increment and decement operators. Also provided
+ * are the compound assignment operators for addition and subtraction.
+ * Atomic swap (via exchange()) is included as well.
+ *
+ * Atomic accesses are sequentially consistent by default. You should
+ * use the default unless you are tall enough to ride the
+ * memory-ordering roller coaster (if you're not sure, you aren't) and
+ * you have a compelling reason to do otherwise.
+ *
+ * There is one exception to the case of atomic memory accesses: providing an
+ * initial value of the atomic value is not guaranteed to be atomic. This is a
+ * deliberate design choice that enables static atomic variables to be declared
+ * without introducing extra static constructors.
+ */
+template<typename T, MemoryOrdering Order>
+class Atomic<T*, Order> : public detail::AtomicBase<T*, Order>
+{
+ typedef typename detail::AtomicBase<T*, Order> Base;
+
+ public:
+ Atomic() : detail::AtomicBase<T*, Order>() {}
+ Atomic(T* aInit) : detail::AtomicBase<T*, Order>(aInit) {}
+
+ T* operator +=(ptrdiff_t delta) {
+ return Base::Intrinsics::add(Base::mValue, delta) + delta;
+ }
+ T* operator -=(ptrdiff_t delta) {
+ return Base::Intrinsics::sub(Base::mValue, delta) - delta;
+ }
+
+ T* operator=(T* aValue) {
+ Base::Intrinsics::store(Base::mValue, aValue);
+ return aValue;
+ }
+
+ private:
+ Atomic(Atomic<T*, Order>& aOther) MOZ_DELETE;
+};
+
+} // namespace mozilla
+
+#endif /* mozilla_Atomics_h_ */
diff --git a/mfbt/Attributes.h b/mfbt/Attributes.h
new file mode 100644
index 0000000..3f27765
--- /dev/null
+++ b/mfbt/Attributes.h
@@ -0,0 +1,409 @@
+/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+/* Implementations of various class and method modifier attributes. */
+
+#ifndef mozilla_Attributes_h_
+#define mozilla_Attributes_h_
+
+#include "mozilla/Compiler.h"
+
+/*
+ * MOZ_INLINE is a macro which expands to tell the compiler that the method
+ * decorated with it should be inlined. This macro is usable from C and C++
+ * code, even though C89 does not support the |inline| keyword. The compiler
+ * may ignore this directive if it chooses.
+ */
+#if defined(__cplusplus)
+# define MOZ_INLINE inline
+#elif defined(_MSC_VER)
+# define MOZ_INLINE __inline
+#elif defined(__GNUC__)
+# define MOZ_INLINE __inline__
+#else
+# define MOZ_INLINE inline
+#endif
+
+/*
+ * MOZ_ALWAYS_INLINE is a macro which expands to tell the compiler that the
+ * method decorated with it must be inlined, even if the compiler thinks
+ * otherwise. This is only a (much) stronger version of the MOZ_INLINE hint:
+ * compilers are not guaranteed to respect it (although they're much more likely
+ * to do so).
+ *
+ * The MOZ_ALWAYS_INLINE_EVEN_DEBUG macro is yet stronger. It tells the
+ * compiler to inline even in DEBUG builds. It should be used very rarely.
+ */
+#if defined(_MSC_VER)
+# define MOZ_ALWAYS_INLINE_EVEN_DEBUG __forceinline
+#elif defined(__GNUC__)
+# define MOZ_ALWAYS_INLINE_EVEN_DEBUG __attribute__((always_inline)) MOZ_INLINE
+#else
+# define MOZ_ALWAYS_INLINE_EVEN_DEBUG MOZ_INLINE
+#endif
+
+#if defined(DEBUG)
+# define MOZ_ALWAYS_INLINE MOZ_INLINE
+#else
+# define MOZ_ALWAYS_INLINE MOZ_ALWAYS_INLINE_EVEN_DEBUG
+#endif
+
+/*
+ * g++ requires -std=c++0x or -std=gnu++0x to support C++11 functionality
+ * without warnings (functionality used by the macros below). These modes are
+ * detectable by checking whether __GXX_EXPERIMENTAL_CXX0X__ is defined or, more
+ * standardly, by checking whether __cplusplus has a C++11 or greater value.
+ * Current versions of g++ do not correctly set __cplusplus, so we check both
+ * for forward compatibility.
+ */
+#if defined(__clang__)
+ /*
+ * Per Clang documentation, "Note that marketing version numbers should not
+ * be used to check for language features, as different vendors use different
+ * numbering schemes. Instead, use the feature checking macros."
+ */
+# ifndef __has_extension
+# define __has_extension __has_feature /* compatibility, for older versions of clang */
+# endif
+# if __has_extension(cxx_constexpr)
+# define MOZ_HAVE_CXX11_CONSTEXPR
+# endif
+# if __has_extension(cxx_deleted_functions)
+# define MOZ_HAVE_CXX11_DELETE
+# endif
+# if __has_extension(cxx_override_control)
+# define MOZ_HAVE_CXX11_OVERRIDE
+# define MOZ_HAVE_CXX11_FINAL final
+# endif
+# if __has_attribute(noinline)
+# define MOZ_HAVE_NEVER_INLINE __attribute__((noinline))
+# endif
+# if __has_attribute(noreturn)
+# define MOZ_HAVE_NORETURN __attribute__((noreturn))
+# endif
+#elif defined(__GNUC__)
+# if defined(__GXX_EXPERIMENTAL_CXX0X__) || __cplusplus >= 201103L
+# if MOZ_GCC_VERSION_AT_LEAST(4, 7, 0)
+# define MOZ_HAVE_CXX11_OVERRIDE
+# define MOZ_HAVE_CXX11_FINAL final
+# endif
+# if MOZ_GCC_VERSION_AT_LEAST(4, 6, 0)
+# define MOZ_HAVE_CXX11_CONSTEXPR
+# endif
+# define MOZ_HAVE_CXX11_DELETE
+# else
+ /* __final is a non-C++11 GCC synonym for 'final', per GCC r176655. */
+# if MOZ_GCC_VERSION_AT_LEAST(4, 7, 0)
+# define MOZ_HAVE_CXX11_FINAL __final
+# endif
+# endif
+# define MOZ_HAVE_NEVER_INLINE __attribute__((noinline))
+# define MOZ_HAVE_NORETURN __attribute__((noreturn))
+#elif defined(_MSC_VER)
+# if _MSC_VER >= 1700
+# define MOZ_HAVE_CXX11_FINAL final
+# else
+ /* MSVC <= 10 used to spell "final" as "sealed". */
+# define MOZ_HAVE_CXX11_FINAL sealed
+# endif
+# define MOZ_HAVE_CXX11_OVERRIDE
+# define MOZ_HAVE_NEVER_INLINE __declspec(noinline)
+# define MOZ_HAVE_NORETURN __declspec(noreturn)
+#endif
+
+/*
+ * The MOZ_CONSTEXPR specifier declares that a C++11 compiler can evaluate a
+ * function at compile time. A constexpr function cannot examine any values
+ * except its arguments and can have no side effects except its return value.
+ */
+#ifdef MOZ_HAVE_CXX11_CONSTEXPR
+# define MOZ_CONSTEXPR constexpr
+#else
+# define MOZ_CONSTEXPR /* no support */
+#endif
+
+/*
+ * MOZ_NEVER_INLINE is a macro which expands to tell the compiler that the
+ * method decorated with it must never be inlined, even if the compiler would
+ * otherwise choose to inline the method. Compilers aren't absolutely
+ * guaranteed to support this, but most do.
+ */
+#if defined(MOZ_HAVE_NEVER_INLINE)
+# define MOZ_NEVER_INLINE MOZ_HAVE_NEVER_INLINE
+#else
+# define MOZ_NEVER_INLINE /* no support */
+#endif
+
+/*
+ * MOZ_NORETURN, specified at the start of a function declaration, indicates
+ * that the given function does not return. (The function definition does not
+ * need to be annotated.)
+ *
+ * MOZ_NORETURN void abort(const char* msg);
+ *
+ * This modifier permits the compiler to optimize code assuming a call to such a
+ * function will never return. It also enables the compiler to avoid spurious
+ * warnings about not initializing variables, or about any other seemingly-dodgy
+ * operations performed after the function returns.
+ *
+ * This modifier does not affect the corresponding function's linking behavior.
+ */
+#if defined(MOZ_HAVE_NORETURN)
+# define MOZ_NORETURN MOZ_HAVE_NORETURN
+#else
+# define MOZ_NORETURN /* no support */
+#endif
+
+/*
+ * MOZ_ASAN_BLACKLIST is a macro to tell AddressSanitizer (a compile-time
+ * instrumentation shipped with Clang) to not instrument the annotated function.
+ * Furthermore, it will prevent the compiler from inlining the function because
+ * inlining currently breaks the blacklisting mechanism of AddressSanitizer.
+ */
+#if defined(MOZ_ASAN)
+# define MOZ_ASAN_BLACKLIST MOZ_NEVER_INLINE __attribute__((no_address_safety_analysis))
+# else
+# define MOZ_ASAN_BLACKLIST
+#endif
+
+
+#ifdef __cplusplus
+
+/*
+ * MOZ_DELETE, specified immediately prior to the ';' terminating an undefined-
+ * method declaration, attempts to delete that method from the corresponding
+ * class. An attempt to use the method will always produce an error *at compile
+ * time* (instead of sometimes as late as link time) when this macro can be
+ * implemented. For example, you can use MOZ_DELETE to produce classes with no
+ * implicit copy constructor or assignment operator:
+ *
+ * struct NonCopyable
+ * {
+ * private:
+ * NonCopyable(const NonCopyable& other) MOZ_DELETE;
+ * void operator=(const NonCopyable& other) MOZ_DELETE;
+ * };
+ *
+ * If MOZ_DELETE can't be implemented for the current compiler, use of the
+ * annotated method will still cause an error, but the error might occur at link
+ * time in some cases rather than at compile time.
+ *
+ * MOZ_DELETE relies on C++11 functionality not universally implemented. As a
+ * backstop, method declarations using MOZ_DELETE should be private.
+ */
+#if defined(MOZ_HAVE_CXX11_DELETE)
+# define MOZ_DELETE = delete
+#else
+# define MOZ_DELETE /* no support */
+#endif
+
+/*
+ * MOZ_OVERRIDE explicitly indicates that a virtual member function in a class
+ * overrides a member function of a base class, rather than potentially being a
+ * new member function. MOZ_OVERRIDE should be placed immediately before the
+ * ';' terminating the member function's declaration, or before '= 0;' if the
+ * member function is pure. If the member function is defined in the class
+ * definition, it should appear before the opening brace of the function body.
+ *
+ * class Base
+ * {
+ * public:
+ * virtual void f() = 0;
+ * };
+ * class Derived1 : public Base
+ * {
+ * public:
+ * virtual void f() MOZ_OVERRIDE;
+ * };
+ * class Derived2 : public Base
+ * {
+ * public:
+ * virtual void f() MOZ_OVERRIDE = 0;
+ * };
+ * class Derived3 : public Base
+ * {
+ * public:
+ * virtual void f() MOZ_OVERRIDE { }
+ * };
+ *
+ * In compilers supporting C++11 override controls, MOZ_OVERRIDE *requires* that
+ * the function marked with it override a member function of a base class: it
+ * is a compile error if it does not. Otherwise MOZ_OVERRIDE does not affect
+ * semantics and merely documents the override relationship to the reader (but
+ * of course must still be used correctly to not break C++11 compilers).
+ */
+#if defined(MOZ_HAVE_CXX11_OVERRIDE)
+# define MOZ_OVERRIDE override
+#else
+# define MOZ_OVERRIDE /* no support */
+#endif
+
+/*
+ * MOZ_FINAL indicates that some functionality cannot be overridden through
+ * inheritance. It can be used to annotate either classes/structs or virtual
+ * member functions.
+ *
+ * To annotate a class/struct with MOZ_FINAL, place MOZ_FINAL immediately after
+ * the name of the class, before the list of classes from which it derives (if
+ * any) and before its opening brace. MOZ_FINAL must not be used to annotate
+ * unnamed classes or structs. (With some compilers, and with C++11 proper, the
+ * underlying expansion is ambiguous with specifying a class name.)
+ *
+ * class Base MOZ_FINAL
+ * {
+ * public:
+ * Base();
+ * ~Base();
+ * virtual void f() { }
+ * };
+ * // This will be an error in some compilers:
+ * class Derived : public Base
+ * {
+ * public:
+ * ~Derived() { }
+ * };
+ *
+ * One particularly common reason to specify MOZ_FINAL upon a class is to tell
+ * the compiler that it's not dangerous for it to have a non-virtual destructor
+ * yet have one or more virtual functions, silencing the warning it might emit
+ * in this case. Suppose Base above weren't annotated with MOZ_FINAL. Because
+ * ~Base() is non-virtual, an attempt to delete a Derived* through a Base*
+ * wouldn't call ~Derived(), so any cleanup ~Derived() might do wouldn't happen.
+ * (Formally C++ says behavior is undefined, but compilers will likely just call
+ * ~Base() and not ~Derived().) Specifying MOZ_FINAL tells the compiler that
+ * it's safe for the destructor to be non-virtual.
+ *
+ * In compilers implementing final controls, it is an error to inherit from a
+ * class annotated with MOZ_FINAL. In other compilers it serves only as
+ * documentation.
+ *
+ * To annotate a virtual member function with MOZ_FINAL, place MOZ_FINAL
+ * immediately before the ';' terminating the member function's declaration, or
+ * before '= 0;' if the member function is pure. If the member function is
+ * defined in the class definition, it should appear before the opening brace of
+ * the function body. (This placement is identical to that for MOZ_OVERRIDE.
+ * If both are used, they should appear in the order 'MOZ_FINAL MOZ_OVERRIDE'
+ * for consistency.)
+ *
+ * class Base
+ * {
+ * public:
+ * virtual void f() MOZ_FINAL;
+ * };
+ * class Derived
+ * {
+ * public:
+ * // This will be an error in some compilers:
+ * virtual void f();
+ * };
+ *
+ * In compilers implementing final controls, it is an error for a derived class
+ * to override a method annotated with MOZ_FINAL. In other compilers it serves
+ * only as documentation.
+ */
+#if defined(MOZ_HAVE_CXX11_FINAL)
+# define MOZ_FINAL MOZ_HAVE_CXX11_FINAL
+#else
+# define MOZ_FINAL /* no support */
+#endif
+
+/**
+ * MOZ_WARN_UNUSED_RESULT tells the compiler to emit a warning if a function's
+ * return value is not used by the caller.
+ *
+ * Place this attribute at the very beginning of a function definition. For
+ * example, write
+ *
+ * MOZ_WARN_UNUSED_RESULT int foo();
+ *
+ * or
+ *
+ * MOZ_WARN_UNUSED_RESULT int foo() { return 42; }
+ */
+#if defined(__GNUC__) || defined(__clang__)
+# define MOZ_WARN_UNUSED_RESULT __attribute__ ((warn_unused_result))
+#else
+# define MOZ_WARN_UNUSED_RESULT
+#endif
+
+/*
+ * The following macros are attributes that support the static analysis plugin
+ * included with Mozilla, and will be implemented (when such support is enabled)
+ * as C++11 attributes. Since such attributes are legal pretty much everywhere
+ * and have subtly different semantics depending on their placement, the
+ * following is a guide on where to place the attributes.
+ *
+ * Attributes that apply to a struct or class precede the name of the class:
+ * (Note that this is different from the placement of MOZ_FINAL for classes!)
+ *
+ * class MOZ_CLASS_ATTRIBUTE SomeClass {};
+ *
+ * Attributes that apply to functions follow the parentheses and const
+ * qualifiers but precede MOZ_FINAL, MOZ_OVERRIDE and the function body:
+ *
+ * void DeclaredFunction() MOZ_FUNCTION_ATTRIBUTE;
+ * void SomeFunction() MOZ_FUNCTION_ATTRIBUTE {}
+ * void PureFunction() const MOZ_FUNCTION_ATTRIBUTE = 0;
+ * void OverriddenFunction() MOZ_FUNCTION_ATTIRBUTE MOZ_OVERRIDE;
+ *
+ * Attributes that apply to variables or parameters follow the variable's name:
+ *
+ * int variable MOZ_VARIABLE_ATTRIBUTE;
+ *
+ * Attributes that apply to types follow the type name:
+ *
+ * typedef int MOZ_TYPE_ATTRIBUTE MagicInt;
+ * int MOZ_TYPE_ATTRIBUTE someVariable;
+ * int * MOZ_TYPE_ATTRIBUTE magicPtrInt;
+ * int MOZ_TYPE_ATTRIBUTE * ptrToMagicInt;
+ *
+ * Attributes that apply to statements precede the statement:
+ *
+ * MOZ_IF_ATTRIBUTE if (x == 0)
+ * MOZ_DO_ATTRIBUTE do { } while(0);
+ *
+ * Attributes that apply to labels precede the label:
+ *
+ * MOZ_LABEL_ATTRIBUTE target:
+ * goto target;
+ * MOZ_CASE_ATTRIBUTE case 5:
+ * MOZ_DEFAULT_ATTRIBUTE default:
+ *
+ * The static analyses that are performed by the plugin are as follows:
+ *
+ * MOZ_MUST_OVERRIDE: Applies to all C++ member functions. All immediate
+ * subclasses must provide an exact override of this method; if a subclass
+ * does not override this method, the compiler will emit an error. This
+ * attribute is not limited to virtual methods, so if it is applied to a
+ * nonvirtual method and the subclass does not provide an equivalent
+ * definition, the compiler will emit an error.
+ * MOZ_STACK_CLASS: Applies to all classes. Any class with this annotation is
+ * expected to live on the stack, so it is a compile-time error to use it, or
+ * an array of such objects, as a global or static variable, or as the type of
+ * a new expression (unless placement new is being used). If a member of
+ * another class uses this class, or if another class inherits from this
+ * class, then it is considered to be a stack class as well, although this
+ * attribute need not be provided in such cases.
+ * MOZ_NONHEAP_CLASS: Applies to all classes. Any class with this annotation is
+ * expected to live on the stack or in static storage, so it is a compile-time
+ * error to use it, or an array of such objects, as the type of a new
+ * expression (unless placement new is being used). If a member of another
+ * class uses this class, or if another class inherits from this class, then
+ * it is considered to be a non-heap class as well, although this attribute
+ * need not be provided in such cases.
+ */
+#ifdef MOZ_CLANG_PLUGIN
+# define MOZ_MUST_OVERRIDE __attribute__((annotate("moz_must_override")))
+# define MOZ_STACK_CLASS __attribute__((annotate("moz_stack_class")))
+# define MOZ_NONHEAP_CLASS __attribute__((annotate("moz_nonheap_class")))
+#else
+# define MOZ_MUST_OVERRIDE /* nothing */
+# define MOZ_STACK_CLASS /* nothing */
+# define MOZ_NONHEAP_CLASS /* nothing */
+#endif /* MOZ_CLANG_PLUGIN */
+
+#endif /* __cplusplus */
+
+#endif /* mozilla_Attributes_h_ */
diff --git a/mfbt/BloomFilter.h b/mfbt/BloomFilter.h
new file mode 100644
index 0000000..8680ef2
--- /dev/null
+++ b/mfbt/BloomFilter.h
@@ -0,0 +1,234 @@
+/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+/*
+ * A counting Bloom filter implementation. This allows consumers to
+ * do fast probabilistic "is item X in set Y?" testing which will
+ * never answer "no" when the correct answer is "yes" (but might
+ * incorrectly answer "yes" when the correct answer is "no").
+ */
+
+#ifndef mozilla_BloomFilter_h_
+#define mozilla_BloomFilter_h_
+
+#include "mozilla/Assertions.h"
+#include "mozilla/Likely.h"
+#include "mozilla/StandardInteger.h"
+#include "mozilla/Util.h"
+
+#include <string.h>
+
+namespace mozilla {
+
+/*
+ * This class implements a counting Bloom filter as described at
+ * <http://en.wikipedia.org/wiki/Bloom_filter#Counting_filters>, with
+ * 8-bit counters. This allows quick probabilistic answers to the
+ * question "is object X in set Y?" where the contents of Y might not
+ * be time-invariant. The probabilistic nature of the test means that
+ * sometimes the answer will be "yes" when it should be "no". If the
+ * answer is "no", then X is guaranteed not to be in Y.
+ *
+ * The filter is parametrized on KeySize, which is the size of the key
+ * generated by each of hash functions used by the filter, in bits,
+ * and the type of object T being added and removed. T must implement
+ * a |uint32_t hash() const| method which returns a uint32_t hash key
+ * that will be used to generate the two separate hash functions for
+ * the Bloom filter. This hash key MUST be well-distributed for good
+ * results! KeySize is not allowed to be larger than 16.
+ *
+ * The filter uses exactly 2**KeySize bytes of memory. From now on we
+ * will refer to the memory used by the filter as M.
+ *
+ * The expected rate of incorrect "yes" answers depends on M and on
+ * the number N of objects in set Y. As long as N is small compared
+ * to M, the rate of such answers is expected to be approximately
+ * 4*(N/M)**2 for this filter. In practice, if Y has a few hundred
+ * elements then using a KeySize of 12 gives a reasonably low
+ * incorrect answer rate. A KeySize of 12 has the additional benefit
+ * of using exactly one page for the filter in typical hardware
+ * configurations.
+ */
+
+template<unsigned KeySize, class T>
+class BloomFilter
+{
+ /*
+ * A counting Bloom filter with 8-bit counters. For now we assume
+ * that having two hash functions is enough, but we may revisit that
+ * decision later.
+ *
+ * The filter uses an array with 2**KeySize entries.
+ *
+ * Assuming a well-distributed hash function, a Bloom filter with
+ * array size M containing N elements and
+ * using k hash function has expected false positive rate exactly
+ *
+ * $ (1 - (1 - 1/M)^{kN})^k $
+ *
+ * because each array slot has a
+ *
+ * $ (1 - 1/M)^{kN} $
+ *
+ * chance of being 0, and the expected false positive rate is the
+ * probability that all of the k hash functions will hit a nonzero
+ * slot.
+ *
+ * For reasonable assumptions (M large, kN large, which should both
+ * hold if we're worried about false positives) about M and kN this
+ * becomes approximately
+ *
+ * $$ (1 - \exp(-kN/M))^k $$
+ *
+ * For our special case of k == 2, that's $(1 - \exp(-2N/M))^2$,
+ * or in other words
+ *
+ * $$ N/M = -0.5 * \ln(1 - \sqrt(r)) $$
+ *
+ * where r is the false positive rate. This can be used to compute
+ * the desired KeySize for a given load N and false positive rate r.
+ *
+ * If N/M is assumed small, then the false positive rate can
+ * further be approximated as 4*N^2/M^2. So increasing KeySize by
+ * 1, which doubles M, reduces the false positive rate by about a
+ * factor of 4, and a false positive rate of 1% corresponds to
+ * about M/N == 20.
+ *
+ * What this means in practice is that for a few hundred keys using a
+ * KeySize of 12 gives false positive rates on the order of 0.25-4%.
+ *
+ * Similarly, using a KeySize of 10 would lead to a 4% false
+ * positive rate for N == 100 and to quite bad false positive
+ * rates for larger N.
+ */
+ public:
+ BloomFilter() {
+ MOZ_STATIC_ASSERT(KeySize <= keyShift, "KeySize too big");
+
+ // Should we have a custom operator new using calloc instead and
+ // require that we're allocated via the operator?
+ clear();
+ }
+
+ /*
+ * Clear the filter. This should be done before reusing it, because
+ * just removing all items doesn't clear counters that hit the upper
+ * bound.
+ */
+ void clear();
+
+ /*
+ * Add an item to the filter.
+ */
+ void add(const T* t);
+
+ /*
+ * Remove an item from the filter.
+ */
+ void remove(const T* t);
+
+ /*
+ * Check whether the filter might contain an item. This can
+ * sometimes return true even if the item is not in the filter,
+ * but will never return false for items that are actually in the
+ * filter.
+ */
+ bool mightContain(const T* t) const;
+
+ /*
+ * Methods for add/remove/contain when we already have a hash computed
+ */
+ void add(uint32_t hash);
+ void remove(uint32_t hash);
+ bool mightContain(uint32_t hash) const;
+
+ private:
+ static const size_t arraySize = (1 << KeySize);
+ static const uint32_t keyMask = (1 << KeySize) - 1;
+ static const uint32_t keyShift = 16;
+
+ static uint32_t hash1(uint32_t hash) { return hash & keyMask; }
+ static uint32_t hash2(uint32_t hash) { return (hash >> keyShift) & keyMask; }
+
+ uint8_t& firstSlot(uint32_t hash) { return counters[hash1(hash)]; }
+ uint8_t& secondSlot(uint32_t hash) { return counters[hash2(hash)]; }
+ const uint8_t& firstSlot(uint32_t hash) const { return counters[hash1(hash)]; }
+ const uint8_t& secondSlot(uint32_t hash) const { return counters[hash2(hash)]; }
+
+ static bool full(const uint8_t& slot) { return slot == UINT8_MAX; }
+
+ uint8_t counters[arraySize];
+};
+
+template<unsigned KeySize, class T>
+inline void
+BloomFilter<KeySize, T>::clear()
+{
+ memset(counters, 0, arraySize);
+}
+
+template<unsigned KeySize, class T>
+inline void
+BloomFilter<KeySize, T>::add(uint32_t hash)
+{
+ uint8_t& slot1 = firstSlot(hash);
+ if (MOZ_LIKELY(!full(slot1)))
+ ++slot1;
+
+ uint8_t& slot2 = secondSlot(hash);
+ if (MOZ_LIKELY(!full(slot2)))
+ ++slot2;
+}
+
+template<unsigned KeySize, class T>
+MOZ_ALWAYS_INLINE void
+BloomFilter<KeySize, T>::add(const T* t)
+{
+ uint32_t hash = t->hash();
+ return add(hash);
+}
+
+template<unsigned KeySize, class T>
+inline void
+BloomFilter<KeySize, T>::remove(uint32_t hash)
+{
+ // If the slots are full, we don't know whether we bumped them to be
+ // there when we added or not, so just leave them full.
+ uint8_t& slot1 = firstSlot(hash);
+ if (MOZ_LIKELY(!full(slot1)))
+ --slot1;
+
+ uint8_t& slot2 = secondSlot(hash);
+ if (MOZ_LIKELY(!full(slot2)))
+ --slot2;
+}
+
+template<unsigned KeySize, class T>
+MOZ_ALWAYS_INLINE void
+BloomFilter<KeySize, T>::remove(const T* t)
+{
+ uint32_t hash = t->hash();
+ remove(hash);
+}
+
+template<unsigned KeySize, class T>
+MOZ_ALWAYS_INLINE bool
+BloomFilter<KeySize, T>::mightContain(uint32_t hash) const
+{
+ // Check that all the slots for this hash contain something
+ return firstSlot(hash) && secondSlot(hash);
+}
+
+template<unsigned KeySize, class T>
+MOZ_ALWAYS_INLINE bool
+BloomFilter<KeySize, T>::mightContain(const T* t) const
+{
+ uint32_t hash = t->hash();
+ return mightContain(hash);
+}
+
+} // namespace mozilla
+
+#endif /* mozilla_BloomFilter_h_ */
diff --git a/mfbt/Casting.h b/mfbt/Casting.h
new file mode 100644
index 0000000..99b5d81
--- /dev/null
+++ b/mfbt/Casting.h
@@ -0,0 +1,201 @@
+/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+/* Cast operations to supplement the built-in casting operations. */
+
+#ifndef mozilla_Casting_h_
+#define mozilla_Casting_h_
+
+#include "mozilla/Assertions.h"
+#include "mozilla/TypeTraits.h"
+
+#include <limits.h>
+
+namespace mozilla {
+
+/**
+ * Return a value of type |To|, containing the underlying bit pattern of |from|.
+ *
+ * |To| and |From| must be types of the same size; be careful of cross-platform
+ * size differences, or this might fail to compile on some but not all
+ * platforms.
+ */
+template<typename To, typename From>
+inline To
+BitwiseCast(const From from)
+{
+ MOZ_STATIC_ASSERT(sizeof(From) == sizeof(To),
+ "To and From must have the same size");
+ union {
+ From from;
+ To to;
+ } u;
+ u.from = from;
+ return u.to;
+}
+
+namespace detail {
+
+enum ToSignedness { ToIsSigned, ToIsUnsigned };
+enum FromSignedness { FromIsSigned, FromIsUnsigned };
+
+template<typename From,
+ typename To,
+ FromSignedness = IsSigned<From>::value ? FromIsSigned : FromIsUnsigned,
+ ToSignedness = IsSigned<To>::value ? ToIsSigned : ToIsUnsigned>
+struct BoundsCheckImpl;
+
+// Implicit conversions on operands to binary operations make this all a bit
+// hard to verify. Attempt to ease the pain below by *only* comparing values
+// that are obviously the same type (and will undergo no further conversions),
+// even when it's not strictly necessary, for explicitness.
+
+enum UUComparison { FromIsBigger, FromIsNotBigger };
+
+// Unsigned-to-unsigned range check
+
+template<typename From, typename To,
+ UUComparison = (sizeof(From) > sizeof(To)) ? FromIsBigger : FromIsNotBigger>
+struct UnsignedUnsignedCheck;
+
+template<typename From, typename To>
+struct UnsignedUnsignedCheck<From, To, FromIsBigger>
+{
+ public:
+ static bool checkBounds(const From from) {
+ return from <= From(To(-1));
+ }
+};
+
+template<typename From, typename To>
+struct UnsignedUnsignedCheck<From, To, FromIsNotBigger>
+{
+ public:
+ static bool checkBounds(const From from) {
+ return true;
+ }
+};
+
+template<typename From, typename To>
+struct BoundsCheckImpl<From, To, FromIsUnsigned, ToIsUnsigned>
+{
+ public:
+ static bool checkBounds(const From from) {
+ return UnsignedUnsignedCheck<From, To>::checkBounds(from);
+ }
+};
+
+// Signed-to-unsigned range check
+
+template<typename From, typename To>
+struct BoundsCheckImpl<From, To, FromIsSigned, ToIsUnsigned>
+{
+ public:
+ static bool checkBounds(const From from) {
+ if (from < 0)
+ return false;
+ if (sizeof(To) >= sizeof(From))
+ return true;
+ return from <= From(To(-1));
+ }
+};
+
+// Unsigned-to-signed range check
+
+enum USComparison { FromIsSmaller, FromIsNotSmaller };
+
+template<typename From, typename To,
+ USComparison = (sizeof(From) < sizeof(To)) ? FromIsSmaller : FromIsNotSmaller>
+struct UnsignedSignedCheck;
+
+template<typename From, typename To>
+struct UnsignedSignedCheck<From, To, FromIsSmaller>
+{
+ public:
+ static bool checkBounds(const From from) {
+ return true;
+ }
+};
+
+template<typename From, typename To>
+struct UnsignedSignedCheck<From, To, FromIsNotSmaller>
+{
+ public:
+ static bool checkBounds(const From from) {
+ const To MaxValue = To((1ULL << (CHAR_BIT * sizeof(To) - 1)) - 1);
+ return from <= From(MaxValue);
+ }
+};
+
+template<typename From, typename To>
+struct BoundsCheckImpl<From, To, FromIsUnsigned, ToIsSigned>
+{
+ public:
+ static bool checkBounds(const From from) {
+ return UnsignedSignedCheck<From, To>::checkBounds(from);
+ }
+};
+
+// Signed-to-signed range check
+
+template<typename From, typename To>
+struct BoundsCheckImpl<From, To, FromIsSigned, ToIsSigned>
+{
+ public:
+ static bool checkBounds(const From from) {
+ if (sizeof(From) <= sizeof(To))
+ return true;
+ const To MaxValue = To((1ULL << (CHAR_BIT * sizeof(To) - 1)) - 1);
+ const To MinValue = -MaxValue - To(1);
+ return From(MinValue) <= from &&
+ From(from) <= From(MaxValue);
+ }
+};
+
+template<typename From, typename To,
+ bool TypesAreIntegral = IsIntegral<From>::value && IsIntegral<To>::value>
+class BoundsChecker;
+
+template<typename From>
+class BoundsChecker<From, From, true>
+{
+ public:
+ static bool checkBounds(const From from) { return true; }
+};
+
+template<typename From, typename To>
+class BoundsChecker<From, To, true>
+{
+ public:
+ static bool checkBounds(const From from) {
+ return BoundsCheckImpl<From, To>::checkBounds(from);
+ }
+};
+
+template<typename From, typename To>
+inline bool
+IsInBounds(const From from)
+{
+ return BoundsChecker<From, To>::checkBounds(from);
+}
+
+} // namespace detail
+
+/**
+ * Cast a value of integral type |From| to a value of integral type |To|,
+ * asserting that the cast will be a safe cast per C++ (that is, that |to| is in
+ * the range of values permitted for the type |From|).
+ */
+template<typename To, typename From>
+inline To
+SafeCast(const From from)
+{
+ MOZ_ASSERT((detail::IsInBounds<From, To>(from)));
+ return static_cast<To>(from);
+}
+
+} // namespace mozilla
+
+#endif /* mozilla_Casting_h_ */
diff --git a/mfbt/Char16.h b/mfbt/Char16.h
new file mode 100644
index 0000000..c6f9f87
--- /dev/null
+++ b/mfbt/Char16.h
@@ -0,0 +1,56 @@
+/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+/* Implements a UTF-16 character type. */
+
+#ifndef mozilla_Char16_h_
+#define mozilla_Char16_h_
+
+#include "mozilla/Assertions.h"
+
+/*
+ * C11 and C++11 introduce a char16_t type and support for UTF-16 string and
+ * character literals. C++11's char16_t is a distinct builtin type. C11's
+ * char16_t is a typedef for uint_least16_t. Technically, char16_t is a 16-bit
+ * code unit of a Unicode code point, not a "character".
+ *
+ * For now, Char16.h only supports C++ because we don't want mix different C
+ * and C++ definitions of char16_t in the same code base.
+ */
+
+#ifdef _MSC_VER
+ /*
+ * C++11 says char16_t is a distinct builtin type, but Windows's yvals.h
+ * typedefs char16_t as an unsigned short. We would like to alias char16_t
+ * to Windows's 16-bit wchar_t so we can declare UTF-16 literals as constant
+ * expressions (and pass char16_t pointers to Windows APIs). We #define our
+ * char16_t as a macro to override yval.h's typedef of the same name.
+ */
+# define MOZ_UTF16_HELPER(s) L##s
+# include <yvals.h>
+# define char16_t wchar_t
+#elif defined(__cplusplus) && \
+ (__cplusplus >= 201103L || defined(__GXX_EXPERIMENTAL_CXX0X__))
+ /* C++11 has a builtin char16_t type. */
+# define MOZ_UTF16_HELPER(s) u##s
+#else
+# error "Char16.h requires C++11 (or something like it) for UTF-16 support."
+#endif
+
+/*
+ * Macro arguments used in concatenation or stringification won't be expanded.
+ * Therefore, in order for |MOZ_UTF16(FOO)| to work as expected (which is to
+ * expand |FOO| before doing whatever |MOZ_UTF16| needs to do to it) a helper
+ * macro, |MOZ_UTF16_HELPER| needs to be inserted in between to allow the macro
+ * argument to expand. See "3.10.6 Separate Expansion of Macro Arguments" of the
+ * CPP manual for a more accurate and precise explanation.
+ */
+#define MOZ_UTF16(s) MOZ_UTF16_HELPER(s)
+
+MOZ_STATIC_ASSERT(sizeof(char16_t) == 2, "Is char16_t type 16 bits?");
+MOZ_STATIC_ASSERT(sizeof(MOZ_UTF16('A')) == 2, "Is char literal 16 bits?");
+MOZ_STATIC_ASSERT(sizeof(MOZ_UTF16("")[0]) == 2, "Is string char 16 bits?");
+
+#endif /* mozilla_Char16_h_ */
diff --git a/mfbt/CheckedInt.h b/mfbt/CheckedInt.h
new file mode 100644
index 0000000..e0c0ebe
--- /dev/null
+++ b/mfbt/CheckedInt.h
@@ -0,0 +1,878 @@
+/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+/* Provides checked integers, detecting integer overflow and divide-by-0. */
+
+#ifndef mozilla_CheckedInt_h_
+#define mozilla_CheckedInt_h_
+
+// Enable relying of Mozilla's MFBT for possibly-available C++11 features
+#define MOZ_CHECKEDINT_USE_MFBT
+
+#ifdef MOZ_CHECKEDINT_USE_MFBT
+# include "mozilla/Assertions.h"
+# include "mozilla/StandardInteger.h"
+#else
+# include <cassert>
+# include <stdint.h>
+# define MOZ_STATIC_ASSERT(cond, reason) assert((cond) && reason)
+# define MOZ_ASSERT(cond, reason) assert((cond) && reason)
+# define MOZ_DELETE
+#endif
+
+#include <climits>
+#include <cstddef>
+
+namespace mozilla {
+
+template<typename T> class CheckedInt;
+
+namespace detail {
+
+/*
+ * Step 1: manually record supported types
+ *
+ * What's nontrivial here is that there are different families of integer
+ * types: basic integer types and stdint types. It is merrily undefined which
+ * types from one family may be just typedefs for a type from another family.
+ *
+ * For example, on GCC 4.6, aside from the basic integer types, the only other
+ * type that isn't just a typedef for some of them, is int8_t.
+ */
+
+struct UnsupportedType {};
+
+template<typename IntegerType>
+struct IsSupportedPass2
+{
+ static const bool value = false;
+};
+
+template<typename IntegerType>
+struct IsSupported
+{
+ static const bool value = IsSupportedPass2<IntegerType>::value;
+};
+
+template<>
+struct IsSupported<int8_t>
+{ static const bool value = true; };
+
+template<>
+struct IsSupported<uint8_t>
+{ static const bool value = true; };
+
+template<>
+struct IsSupported<int16_t>
+{ static const bool value = true; };
+
+template<>
+struct IsSupported<uint16_t>
+{ static const bool value = true; };
+
+template<>
+struct IsSupported<int32_t>
+{ static const bool value = true; };
+
+template<>
+struct IsSupported<uint32_t>
+{ static const bool value = true; };
+
+template<>
+struct IsSupported<int64_t>
+{ static const bool value = true; };
+
+template<>
+struct IsSupported<uint64_t>
+{ static const bool value = true; };
+
+
+template<>
+struct IsSupportedPass2<char>
+{ static const bool value = true; };
+
+template<>
+struct IsSupportedPass2<signed char>
+{ static const bool value = true; };
+
+template<>
+struct IsSupportedPass2<unsigned char>
+{ static const bool value = true; };
+
+template<>
+struct IsSupportedPass2<short>
+{ static const bool value = true; };
+
+template<>
+struct IsSupportedPass2<unsigned short>
+{ static const bool value = true; };
+
+template<>
+struct IsSupportedPass2<int>
+{ static const bool value = true; };
+
+template<>
+struct IsSupportedPass2<unsigned int>
+{ static const bool value = true; };
+
+template<>
+struct IsSupportedPass2<long>
+{ static const bool value = true; };
+
+template<>
+struct IsSupportedPass2<unsigned long>
+{ static const bool value = true; };
+
+template<>
+struct IsSupportedPass2<long long>
+{ static const bool value = true; };
+
+template<>
+struct IsSupportedPass2<unsigned long long>
+{ static const bool value = true; };
+
+/*
+ * Step 2: some integer-traits kind of stuff.
+ */
+
+template<size_t Size, bool Signedness>
+struct StdintTypeForSizeAndSignedness
+{};
+
+template<>
+struct StdintTypeForSizeAndSignedness<1, true>
+{ typedef int8_t Type; };
+
+template<>
+struct StdintTypeForSizeAndSignedness<1, false>
+{ typedef uint8_t Type; };
+
+template<>
+struct StdintTypeForSizeAndSignedness<2, true>
+{ typedef int16_t Type; };
+
+template<>
+struct StdintTypeForSizeAndSignedness<2, false>
+{ typedef uint16_t Type; };
+
+template<>
+struct StdintTypeForSizeAndSignedness<4, true>
+{ typedef int32_t Type; };
+
+template<>
+struct StdintTypeForSizeAndSignedness<4, false>
+{ typedef uint32_t Type; };
+
+template<>
+struct StdintTypeForSizeAndSignedness<8, true>
+{ typedef int64_t Type; };
+
+template<>
+struct StdintTypeForSizeAndSignedness<8, false>
+{ typedef uint64_t Type; };
+
+template<typename IntegerType>
+struct UnsignedType
+{
+ typedef typename StdintTypeForSizeAndSignedness<sizeof(IntegerType),
+ false>::Type Type;
+};
+
+template<typename IntegerType>
+struct IsSigned
+{
+ static const bool value = IntegerType(-1) <= IntegerType(0);
+};
+
+template<typename IntegerType, size_t Size = sizeof(IntegerType)>
+struct TwiceBiggerType
+{
+ typedef typename StdintTypeForSizeAndSignedness<
+ sizeof(IntegerType) * 2,
+ IsSigned<IntegerType>::value
+ >::Type Type;
+};
+
+template<typename IntegerType>
+struct TwiceBiggerType<IntegerType, 8>
+{
+ typedef UnsupportedType Type;
+};
+
+template<typename IntegerType>
+struct PositionOfSignBit
+{
+ static const size_t value = CHAR_BIT * sizeof(IntegerType) - 1;
+};
+
+template<typename IntegerType>
+struct MinValue
+{
+ private:
+ typedef typename UnsignedType<IntegerType>::Type UnsignedIntegerType;
+ static const size_t PosOfSignBit = PositionOfSignBit<IntegerType>::value;
+
+ public:
+ // Bitwise ops may return a larger type, that's why we cast explicitly.
+ // In C++, left bit shifts on signed values is undefined by the standard
+ // unless the shifted value is representable.
+ // Notice that signed-to-unsigned conversions are always well-defined in
+ // the standard as the value congruent to 2**n, as expected. By contrast,
+ // unsigned-to-signed is only well-defined if the value is representable.
+ static const IntegerType value =
+ IsSigned<IntegerType>::value
+ ? IntegerType(UnsignedIntegerType(1) << PosOfSignBit)
+ : IntegerType(0);
+};
+
+template<typename IntegerType>
+struct MaxValue
+{
+ // Tricksy, but covered by the unit test.
+ // Relies heavily on the type of MinValue<IntegerType>::value
+ // being IntegerType.
+ static const IntegerType value = ~MinValue<IntegerType>::value;
+};
+
+/*
+ * Step 3: Implement the actual validity checks.
+ *
+ * Ideas taken from IntegerLib, code different.
+ */
+
+template<typename T>
+inline bool
+HasSignBit(T x)
+{
+ // In C++, right bit shifts on negative values is undefined by the standard.
+ // Notice that signed-to-unsigned conversions are always well-defined in the
+ // standard, as the value congruent modulo 2**n as expected. By contrast,
+ // unsigned-to-signed is only well-defined if the value is representable.
+ return bool(typename UnsignedType<T>::Type(x)
+ >> PositionOfSignBit<T>::value);
+}
+
+// Bitwise ops may return a larger type, so it's good to use this inline
+// helper guaranteeing that the result is really of type T.
+template<typename T>
+inline T
+BinaryComplement(T x)
+{
+ return ~x;
+}
+
+template<typename T,
+ typename U,
+ bool IsTSigned = IsSigned<T>::value,
+ bool IsUSigned = IsSigned<U>::value>
+struct DoesRangeContainRange
+{
+};
+
+template<typename T, typename U, bool Signedness>
+struct DoesRangeContainRange<T, U, Signedness, Signedness>
+{
+ static const bool value = sizeof(T) >= sizeof(U);
+};
+
+template<typename T, typename U>
+struct DoesRangeContainRange<T, U, true, false>
+{
+ static const bool value = sizeof(T) > sizeof(U);
+};
+
+template<typename T, typename U>
+struct DoesRangeContainRange<T, U, false, true>
+{
+ static const bool value = false;
+};
+
+template<typename T,
+ typename U,
+ bool IsTSigned = IsSigned<T>::value,
+ bool IsUSigned = IsSigned<U>::value,
+ bool DoesTRangeContainURange = DoesRangeContainRange<T, U>::value>
+struct IsInRangeImpl {};
+
+template<typename T, typename U, bool IsTSigned, bool IsUSigned>
+struct IsInRangeImpl<T, U, IsTSigned, IsUSigned, true>
+{
+ static bool run(U)
+ {
+ return true;
+ }
+};
+
+template<typename T, typename U>
+struct IsInRangeImpl<T, U, true, true, false>
+{
+ static bool run(U x)
+ {
+ return x <= MaxValue<T>::value && x >= MinValue<T>::value;
+ }
+};
+
+template<typename T, typename U>
+struct IsInRangeImpl<T, U, false, false, false>
+{
+ static bool run(U x)
+ {
+ return x <= MaxValue<T>::value;
+ }
+};
+
+template<typename T, typename U>
+struct IsInRangeImpl<T, U, true, false, false>
+{
+ static bool run(U x)
+ {
+ return sizeof(T) > sizeof(U) || x <= U(MaxValue<T>::value);
+ }
+};
+
+template<typename T, typename U>
+struct IsInRangeImpl<T, U, false, true, false>
+{
+ static bool run(U x)
+ {
+ return sizeof(T) >= sizeof(U)
+ ? x >= 0
+ : x >= 0 && x <= U(MaxValue<T>::value);
+ }
+};
+
+template<typename T, typename U>
+inline bool
+IsInRange(U x)
+{
+ return IsInRangeImpl<T, U>::run(x);
+}
+
+template<typename T>
+inline bool
+IsAddValid(T x, T y)
+{
+ // Addition is valid if the sign of x+y is equal to either that of x or that
+ // of y. Since the value of x+y is undefined if we have a signed type, we
+ // compute it using the unsigned type of the same size.
+ // Beware! These bitwise operations can return a larger integer type,
+ // if T was a small type like int8_t, so we explicitly cast to T.
+
+ typename UnsignedType<T>::Type ux = x;
+ typename UnsignedType<T>::Type uy = y;
+ typename UnsignedType<T>::Type result = ux + uy;
+ return IsSigned<T>::value
+ ? HasSignBit(BinaryComplement(T((result ^ x) & (result ^ y))))
+ : BinaryComplement(x) >= y;
+}
+
+template<typename T>
+inline bool
+IsSubValid(T x, T y)
+{
+ // Subtraction is valid if either x and y have same sign, or x-y and x have
+ // same sign. Since the value of x-y is undefined if we have a signed type,
+ // we compute it using the unsigned type of the same size.
+ typename UnsignedType<T>::Type ux = x;
+ typename UnsignedType<T>::Type uy = y;
+ typename UnsignedType<T>::Type result = ux - uy;
+
+ return IsSigned<T>::value
+ ? HasSignBit(BinaryComplement(T((result ^ x) & (x ^ y))))
+ : x >= y;
+}
+
+template<typename T,
+ bool IsTSigned = IsSigned<T>::value,
+ bool TwiceBiggerTypeIsSupported =
+ IsSupported<typename TwiceBiggerType<T>::Type>::value>
+struct IsMulValidImpl {};
+
+template<typename T, bool IsTSigned>
+struct IsMulValidImpl<T, IsTSigned, true>
+{
+ static bool run(T x, T y)
+ {
+ typedef typename TwiceBiggerType<T>::Type TwiceBiggerType;
+ TwiceBiggerType product = TwiceBiggerType(x) * TwiceBiggerType(y);
+ return IsInRange<T>(product);
+ }
+};
+
+template<typename T>
+struct IsMulValidImpl<T, true, false>
+{
+ static bool run(T x, T y)
+ {
+ const T max = MaxValue<T>::value;
+ const T min = MinValue<T>::value;
+
+ if (x == 0 || y == 0)
+ return true;
+
+ if (x > 0) {
+ return y > 0
+ ? x <= max / y
+ : y >= min / x;
+ }
+
+ // If we reach this point, we know that x < 0.
+ return y > 0
+ ? x >= min / y
+ : y >= max / x;
+ }
+};
+
+template<typename T>
+struct IsMulValidImpl<T, false, false>
+{
+ static bool run(T x, T y)
+ {
+ return y == 0 || x <= MaxValue<T>::value / y;
+ }
+};
+
+template<typename T>
+inline bool
+IsMulValid(T x, T y)
+{
+ return IsMulValidImpl<T>::run(x, y);
+}
+
+template<typename T>
+inline bool
+IsDivValid(T x, T y)
+{
+ // Keep in mind that in the signed case, min/-1 is invalid because abs(min)>max.
+ return y != 0 &&
+ !(IsSigned<T>::value && x == MinValue<T>::value && y == T(-1));
+}
+
+template<typename T, bool IsTSigned = IsSigned<T>::value>
+struct IsModValidImpl;
+
+template<typename T>
+inline bool
+IsModValid(T x, T y)
+{
+ return IsModValidImpl<T>::run(x, y);
+}
+
+/*
+ * Mod is pretty simple.
+ * For now, let's just use the ANSI C definition:
+ * If x or y are negative, the results are implementation defined.
+ * Consider these invalid.
+ * Undefined for y=0.
+ * The result will never exceed either x or y.
+ *
+ * Checking that x>=0 is a warning when T is unsigned.
+ */
+
+template<typename T>
+struct IsModValidImpl<T, false> {
+ static inline bool run(T x, T y) {
+ return y >= 1;
+ }
+};
+
+template<typename T>
+struct IsModValidImpl<T, true> {
+ static inline bool run(T x, T y) {
+ if (x < 0)
+ return false;
+
+ return y >= 1;
+ }
+};
+
+template<typename T, bool IsSigned = IsSigned<T>::value>
+struct NegateImpl;
+
+template<typename T>
+struct NegateImpl<T, false>
+{
+ static CheckedInt<T> negate(const CheckedInt<T>& val)
+ {
+ // Handle negation separately for signed/unsigned, for simpler code and to
+ // avoid an MSVC warning negating an unsigned value.
+ return CheckedInt<T>(0, val.isValid() && val.mValue == 0);
+ }
+};
+
+template<typename T>
+struct NegateImpl<T, true>
+{
+ static CheckedInt<T> negate(const CheckedInt<T>& val)
+ {
+ // Watch out for the min-value, which (with twos-complement) can't be
+ // negated as -min-value is then (max-value + 1).
+ if (!val.isValid() || val.mValue == MinValue<T>::value)
+ return CheckedInt<T>(val.mValue, false);
+ return CheckedInt<T>(-val.mValue, true);
+ }
+};
+
+} // namespace detail
+
+
+/*
+ * Step 4: Now define the CheckedInt class.
+ */
+
+/**
+ * @class CheckedInt
+ * @brief Integer wrapper class checking for integer overflow and other errors
+ * @param T the integer type to wrap. Can be any type among the following:
+ * - any basic integer type such as |int|
+ * - any stdint type such as |int8_t|
+ *
+ * This class implements guarded integer arithmetic. Do a computation, check
+ * that isValid() returns true, you then have a guarantee that no problem, such
+ * as integer overflow, happened during this computation, and you can call
+ * value() to get the plain integer value.
+ *
+ * The arithmetic operators in this class are guaranteed not to raise a signal
+ * (e.g. in case of a division by zero).
+ *
+ * For example, suppose that you want to implement a function that computes
+ * (x+y)/z, that doesn't crash if z==0, and that reports on error (divide by
+ * zero or integer overflow). You could code it as follows:
+ @code
+ bool computeXPlusYOverZ(int x, int y, int z, int *result)
+ {
+ CheckedInt<int> checkedResult = (CheckedInt<int>(x) + y) / z;
+ if (checkedResult.isValid()) {
+ *result = checkedResult.value();
+ return true;
+ } else {
+ return false;
+ }
+ }
+ @endcode
+ *
+ * Implicit conversion from plain integers to checked integers is allowed. The
+ * plain integer is checked to be in range before being casted to the
+ * destination type. This means that the following lines all compile, and the
+ * resulting CheckedInts are correctly detected as valid or invalid:
+ * @code
+ // 1 is of type int, is found to be in range for uint8_t, x is valid
+ CheckedInt<uint8_t> x(1);
+ // -1 is of type int, is found not to be in range for uint8_t, x is invalid
+ CheckedInt<uint8_t> x(-1);
+ // -1 is of type int, is found to be in range for int8_t, x is valid
+ CheckedInt<int8_t> x(-1);
+ // 1000 is of type int16_t, is found not to be in range for int8_t,
+ // x is invalid
+ CheckedInt<int8_t> x(int16_t(1000));
+ // 3123456789 is of type uint32_t, is found not to be in range for int32_t,
+ // x is invalid
+ CheckedInt<int32_t> x(uint32_t(3123456789));
+ * @endcode
+ * Implicit conversion from
+ * checked integers to plain integers is not allowed. As shown in the
+ * above example, to get the value of a checked integer as a normal integer,
+ * call value().
+ *
+ * Arithmetic operations between checked and plain integers is allowed; the
+ * result type is the type of the checked integer.
+ *
+ * Checked integers of different types cannot be used in the same arithmetic
+ * expression.
+ *
+ * There are convenience typedefs for all stdint types, of the following form
+ * (these are just 2 examples):
+ @code
+ typedef CheckedInt<int32_t> CheckedInt32;
+ typedef CheckedInt<uint16_t> CheckedUint16;
+ @endcode
+ */
+template<typename T>
+class CheckedInt
+{
+ protected:
+ T mValue;
+ bool mIsValid;
+
+ template<typename U>
+ CheckedInt(U value, bool isValid) : mValue(value), mIsValid(isValid)
+ {
+ MOZ_STATIC_ASSERT(detail::IsSupported<T>::value &&
+ detail::IsSupported<U>::value,
+ "This type is not supported by CheckedInt");
+ }
+
+ friend class detail::NegateImpl<T>;
+
+ public:
+ /**
+ * Constructs a checked integer with given @a value. The checked integer is
+ * initialized as valid or invalid depending on whether the @a value
+ * is in range.
+ *
+ * This constructor is not explicit. Instead, the type of its argument is a
+ * separate template parameter, ensuring that no conversion is performed
+ * before this constructor is actually called. As explained in the above
+ * documentation for class CheckedInt, this constructor checks that its
+ * argument is valid.
+ */
+ template<typename U>
+ CheckedInt(U value)
+ : mValue(T(value)),
+ mIsValid(detail::IsInRange<T>(value))
+ {
+ MOZ_STATIC_ASSERT(detail::IsSupported<T>::value &&
+ detail::IsSupported<U>::value,
+ "This type is not supported by CheckedInt");
+ }
+
+ template<typename U>
+ friend class CheckedInt;
+
+ template<typename U>
+ CheckedInt<U> toChecked() const
+ {
+ CheckedInt<U> ret(mValue);
+ ret.mIsValid = ret.mIsValid && mIsValid;
+ return ret;
+ }
+
+ /** Constructs a valid checked integer with initial value 0 */
+ CheckedInt() : mValue(0), mIsValid(true)
+ {
+ MOZ_STATIC_ASSERT(detail::IsSupported<T>::value,
+ "This type is not supported by CheckedInt");
+ }
+
+ /** @returns the actual value */
+ T value() const
+ {
+ MOZ_ASSERT(mIsValid, "Invalid checked integer (division by zero or integer overflow)");
+ return mValue;
+ }
+
+ /**
+ * @returns true if the checked integer is valid, i.e. is not the result
+ * of an invalid operation or of an operation involving an invalid checked
+ * integer
+ */
+ bool isValid() const
+ {
+ return mIsValid;
+ }
+
+ template<typename U>
+ friend CheckedInt<U> operator +(const CheckedInt<U>& lhs,
+ const CheckedInt<U>& rhs);
+ template<typename U>
+ CheckedInt& operator +=(U rhs);
+
+ template<typename U>
+ friend CheckedInt<U> operator -(const CheckedInt<U>& lhs,
+ const CheckedInt<U>& rhs);
+ template<typename U>
+ CheckedInt& operator -=(U rhs);
+
+ template<typename U>
+ friend CheckedInt<U> operator *(const CheckedInt<U>& lhs,
+ const CheckedInt<U>& rhs);
+ template<typename U>
+ CheckedInt& operator *=(U rhs);
+
+ template<typename U>
+ friend CheckedInt<U> operator /(const CheckedInt<U>& lhs,
+ const CheckedInt<U>& rhs);
+ template<typename U>
+ CheckedInt& operator /=(U rhs);
+
+ template<typename U>
+ friend CheckedInt<U> operator %(const CheckedInt<U>& lhs,
+ const CheckedInt<U>& rhs);
+ template<typename U>
+ CheckedInt& operator %=(U rhs);
+
+ CheckedInt operator -() const
+ {
+ return detail::NegateImpl<T>::negate(*this);
+ }
+
+ /**
+ * @returns true if the left and right hand sides are valid
+ * and have the same value.
+ *
+ * Note that these semantics are the reason why we don't offer
+ * a operator!=. Indeed, we'd want to have a!=b be equivalent to !(a==b)
+ * but that would mean that whenever a or b is invalid, a!=b
+ * is always true, which would be very confusing.
+ *
+ * For similar reasons, operators <, >, <=, >= would be very tricky to
+ * specify, so we just avoid offering them.
+ *
+ * Notice that these == semantics are made more reasonable by these facts:
+ * 1. a==b implies equality at the raw data level
+ * (the converse is false, as a==b is never true among invalids)
+ * 2. This is similar to the behavior of IEEE floats, where a==b
+ * means that a and b have the same value *and* neither is NaN.
+ */
+ bool operator ==(const CheckedInt& other) const
+ {
+ return mIsValid && other.mIsValid && mValue == other.mValue;
+ }
+
+ /** prefix ++ */
+ CheckedInt& operator++()
+ {
+ *this += 1;
+ return *this;
+ }
+
+ /** postfix ++ */
+ CheckedInt operator++(int)
+ {
+ CheckedInt tmp = *this;
+ *this += 1;
+ return tmp;
+ }
+
+ /** prefix -- */
+ CheckedInt& operator--()
+ {
+ *this -= 1;
+ return *this;
+ }
+
+ /** postfix -- */
+ CheckedInt operator--(int)
+ {
+ CheckedInt tmp = *this;
+ *this -= 1;
+ return tmp;
+ }
+
+ private:
+ /**
+ * The !=, <, <=, >, >= operators are disabled:
+ * see the comment on operator==.
+ */
+ template<typename U>
+ bool operator !=(U other) const MOZ_DELETE;
+ template<typename U>
+ bool operator <(U other) const MOZ_DELETE;
+ template<typename U>
+ bool operator <=(U other) const MOZ_DELETE;
+ template<typename U>
+ bool operator >(U other) const MOZ_DELETE;
+ template<typename U>
+ bool operator >=(U other) const MOZ_DELETE;
+};
+
+#define MOZ_CHECKEDINT_BASIC_BINARY_OPERATOR(NAME, OP) \
+template<typename T> \
+inline CheckedInt<T> operator OP(const CheckedInt<T> &lhs, \
+ const CheckedInt<T> &rhs) \
+{ \
+ if (!detail::Is##NAME##Valid(lhs.mValue, rhs.mValue)) \
+ return CheckedInt<T>(0, false); \
+ \
+ return CheckedInt<T>(lhs.mValue OP rhs.mValue, \
+ lhs.mIsValid && rhs.mIsValid); \
+}
+
+MOZ_CHECKEDINT_BASIC_BINARY_OPERATOR(Add, +)
+MOZ_CHECKEDINT_BASIC_BINARY_OPERATOR(Sub, -)
+MOZ_CHECKEDINT_BASIC_BINARY_OPERATOR(Mul, *)
+MOZ_CHECKEDINT_BASIC_BINARY_OPERATOR(Div, /)
+MOZ_CHECKEDINT_BASIC_BINARY_OPERATOR(Mod, %)
+
+#undef MOZ_CHECKEDINT_BASIC_BINARY_OPERATOR
+
+// Implement castToCheckedInt<T>(x), making sure that
+// - it allows x to be either a CheckedInt<T> or any integer type
+// that can be casted to T
+// - if x is already a CheckedInt<T>, we just return a reference to it,
+// instead of copying it (optimization)
+
+namespace detail {
+
+template<typename T, typename U>
+struct CastToCheckedIntImpl
+{
+ typedef CheckedInt<T> ReturnType;
+ static CheckedInt<T> run(U u) { return u; }
+};
+
+template<typename T>
+struct CastToCheckedIntImpl<T, CheckedInt<T> >
+{
+ typedef const CheckedInt<T>& ReturnType;
+ static const CheckedInt<T>& run(const CheckedInt<T>& u) { return u; }
+};
+
+} // namespace detail
+
+template<typename T, typename U>
+inline typename detail::CastToCheckedIntImpl<T, U>::ReturnType
+castToCheckedInt(U u)
+{
+ MOZ_STATIC_ASSERT(detail::IsSupported<T>::value &&
+ detail::IsSupported<U>::value,
+ "This type is not supported by CheckedInt");
+ return detail::CastToCheckedIntImpl<T, U>::run(u);
+}
+
+#define MOZ_CHECKEDINT_CONVENIENCE_BINARY_OPERATORS(OP, COMPOUND_OP) \
+template<typename T> \
+template<typename U> \
+CheckedInt<T>& CheckedInt<T>::operator COMPOUND_OP(U rhs) \
+{ \
+ *this = *this OP castToCheckedInt<T>(rhs); \
+ return *this; \
+} \
+template<typename T, typename U> \
+inline CheckedInt<T> operator OP(const CheckedInt<T> &lhs, U rhs) \
+{ \
+ return lhs OP castToCheckedInt<T>(rhs); \
+} \
+template<typename T, typename U> \
+inline CheckedInt<T> operator OP(U lhs, const CheckedInt<T> &rhs) \
+{ \
+ return castToCheckedInt<T>(lhs) OP rhs; \
+}
+
+MOZ_CHECKEDINT_CONVENIENCE_BINARY_OPERATORS(+, +=)
+MOZ_CHECKEDINT_CONVENIENCE_BINARY_OPERATORS(*, *=)
+MOZ_CHECKEDINT_CONVENIENCE_BINARY_OPERATORS(-, -=)
+MOZ_CHECKEDINT_CONVENIENCE_BINARY_OPERATORS(/, /=)
+MOZ_CHECKEDINT_CONVENIENCE_BINARY_OPERATORS(%, %=)
+
+#undef MOZ_CHECKEDINT_CONVENIENCE_BINARY_OPERATORS
+
+template<typename T, typename U>
+inline bool
+operator ==(const CheckedInt<T> &lhs, U rhs)
+{
+ return lhs == castToCheckedInt<T>(rhs);
+}
+
+template<typename T, typename U>
+inline bool
+operator ==(U lhs, const CheckedInt<T> &rhs)
+{
+ return castToCheckedInt<T>(lhs) == rhs;
+}
+
+// Convenience typedefs.
+typedef CheckedInt<int8_t> CheckedInt8;
+typedef CheckedInt<uint8_t> CheckedUint8;
+typedef CheckedInt<int16_t> CheckedInt16;
+typedef CheckedInt<uint16_t> CheckedUint16;
+typedef CheckedInt<int32_t> CheckedInt32;
+typedef CheckedInt<uint32_t> CheckedUint32;
+typedef CheckedInt<int64_t> CheckedInt64;
+typedef CheckedInt<uint64_t> CheckedUint64;
+
+} // namespace mozilla
+
+#endif /* mozilla_CheckedInt_h_ */
diff --git a/mfbt/Compiler.h b/mfbt/Compiler.h
new file mode 100644
index 0000000..58239b0
--- /dev/null
+++ b/mfbt/Compiler.h
@@ -0,0 +1,31 @@
+/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+/* Various compiler checks. */
+
+#ifndef mozilla_Compiler_h_
+#define mozilla_Compiler_h_
+
+#if !defined(__clang__) && defined(__GNUC__)
+
+#define MOZ_IS_GCC 1
+ /*
+ * This macro should simplify gcc version checking. For example, to check
+ * for gcc 4.5.1 or later, check `#ifdef MOZ_GCC_VERSION_AT_LEAST(4, 5, 1)`.
+ */
+# define MOZ_GCC_VERSION_AT_LEAST(major, minor, patchlevel) \
+ ((__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__) \
+ >= ((major) * 10000 + (minor) * 100 + (patchlevel)))
+#if !MOZ_GCC_VERSION_AT_LEAST(4, 4, 0)
+# error "mfbt (and Gecko) require at least gcc 4.4 to build."
+#endif
+
+#else
+
+#define MOZ_IS_GCC 0
+
+#endif
+
+#endif /* mozilla_Compiler_h_ */
diff --git a/mfbt/Constants.h b/mfbt/Constants.h
new file mode 100644
index 0000000..904b301
--- /dev/null
+++ b/mfbt/Constants.h
@@ -0,0 +1,15 @@
+/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+/* mfbt math constants. */
+
+#ifndef mozilla_Constants_h_
+#define mozilla_Constants_h_
+
+#ifndef M_PI
+# define M_PI 3.14159265358979323846
+#endif
+
+#endif /* mozilla_Constants_h_ */
diff --git a/mfbt/DebugOnly.h b/mfbt/DebugOnly.h
new file mode 100644
index 0000000..1f78ed7
--- /dev/null
+++ b/mfbt/DebugOnly.h
@@ -0,0 +1,77 @@
+/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+/*
+ * Provides DebugOnly, a type for variables used only in debug builds (i.e. by
+ * assertions).
+ */
+
+#ifndef mozilla_DebugOnly_h_
+#define mozilla_DebugOnly_h_
+
+namespace mozilla {
+
+/**
+ * DebugOnly contains a value of type T, but only in debug builds. In release
+ * builds, it does not contain a value. This helper is intended to be used with
+ * MOZ_ASSERT()-style macros, allowing one to write:
+ *
+ * DebugOnly<bool> check = func();
+ * MOZ_ASSERT(check);
+ *
+ * more concisely than declaring |check| conditional on #ifdef DEBUG, but also
+ * without allocating storage space for |check| in release builds.
+ *
+ * DebugOnly instances can only be coerced to T in debug builds. In release
+ * builds they don't have a value, so type coercion is not well defined.
+ */
+template<typename T>
+class DebugOnly
+{
+ public:
+#ifdef DEBUG
+ T value;
+
+ DebugOnly() { }
+ DebugOnly(const T& other) : value(other) { }
+ DebugOnly(const DebugOnly& other) : value(other.value) { }
+ DebugOnly& operator=(const T& rhs) {
+ value = rhs;
+ return *this;
+ }
+ void operator++(int) {
+ value++;
+ }
+ void operator--(int) {
+ value--;
+ }
+
+ T* operator&() { return &value; }
+
+ operator T&() { return value; }
+ operator const T&() const { return value; }
+
+ T& operator->() { return value; }
+
+#else
+ DebugOnly() { }
+ DebugOnly(const T&) { }
+ DebugOnly(const DebugOnly&) { }
+ DebugOnly& operator=(const T&) { return *this; }
+ void operator++(int) { }
+ void operator--(int) { }
+#endif
+
+ /*
+ * DebugOnly must always have a destructor or else it will
+ * generate "unused variable" warnings, exactly what it's intended
+ * to avoid!
+ */
+ ~DebugOnly() {}
+};
+
+}
+
+#endif /* mozilla_DebugOnly_h_ */
diff --git a/mfbt/Endian.h b/mfbt/Endian.h
new file mode 100644
index 0000000..5d2f905
--- /dev/null
+++ b/mfbt/Endian.h
@@ -0,0 +1,639 @@
+/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+/* Functions for reading and writing integers in various endiannesses. */
+
+/*
+ * The classes LittleEndian and BigEndian expose static methods for
+ * reading and writing 16-, 32-, and 64-bit signed and unsigned integers
+ * in their respective endianness. The naming scheme is:
+ *
+ * {Little,Big}Endian::{read,write}{Uint,Int}<bitsize>
+ *
+ * For instance, LittleEndian::readInt32 will read a 32-bit signed
+ * integer from memory in little endian format. Similarly,
+ * BigEndian::writeUint16 will write a 16-bit unsigned integer to memory
+ * in big-endian format.
+ *
+ * The class NativeEndian exposes methods for conversion of existing
+ * data to and from the native endianness. These methods are intended
+ * for cases where data needs to be transferred, serialized, etc.
+ * swap{To,From}{Little,Big}Endian byteswap a single value if necessary.
+ * Bulk conversion functions are also provided which optimize the
+ * no-conversion-needed case:
+ *
+ * - copyAndSwap{To,From}{Little,Big}Endian;
+ * - swap{To,From}{Little,Big}EndianInPlace.
+ *
+ * The *From* variants are intended to be used for reading data and the
+ * *To* variants for writing data.
+ *
+ * Methods on NativeEndian work with integer data of any type.
+ * Floating-point data is not supported.
+ *
+ * For clarity in networking code, "Network" may be used as a synonym
+ * for "Big" in any of the above methods or class names.
+ *
+ * As an example, reading a file format header whose fields are stored
+ * in big-endian format might look like:
+ *
+ * class ExampleHeader
+ * {
+ * private:
+ * uint32_t magic;
+ * uint32_t length;
+ * uint32_t totalRecords;
+ * uint64_t checksum;
+ *
+ * public:
+ * ExampleHeader(const void* data) {
+ * const uint8_t* ptr = static_cast<const uint8_t*>(data);
+ * magic = BigEndian::readUint32(ptr); ptr += sizeof(uint32_t);
+ * length = BigEndian::readUint32(ptr); ptr += sizeof(uint32_t);
+ * totalRecords = BigEndian::readUint32(ptr); ptr += sizeof(uint32_t);
+ * checksum = BigEndian::readUint64(ptr);
+ * }
+ * ...
+ * };
+ */
+
+#ifndef mozilla_Endian_h_
+#define mozilla_Endian_h_
+
+#include "mozilla/Assertions.h"
+#include "mozilla/Attributes.h"
+#include "mozilla/Compiler.h"
+#include "mozilla/DebugOnly.h"
+#include "mozilla/StandardInteger.h"
+#include "mozilla/TypeTraits.h"
+
+#include <string.h>
+
+#if defined(_MSC_VER) && _MSC_VER >= 1300
+# include <stdlib.h>
+# pragma intrinsic(_byteswap_ushort)
+# pragma intrinsic(_byteswap_ulong)
+# pragma intrinsic(_byteswap_uint64)
+#endif
+
+#if defined(_WIN64)
+# if defined(_M_X64) || defined(_M_AMD64) || defined(_AMD64_)
+# define MOZ_LITTLE_ENDIAN 1
+# else
+# error "CPU type is unknown"
+# endif
+#elif defined(_WIN32)
+# if defined(_M_IX86)
+# define MOZ_LITTLE_ENDIAN 1
+# else
+# error "CPU type is unknown"
+# endif
+#elif defined(__APPLE__)
+# if __LITTLE_ENDIAN__
+# define MOZ_LITTLE_ENDIAN 1
+# elif __BIG_ENDIAN__
+# define MOZ_BIG_ENDIAN 1
+# endif
+#elif defined(__GNUC__) && \
+ defined(__BYTE_ORDER__) && \
+ defined(__ORDER_LITTLE_ENDIAN__) && \
+ defined(__ORDER_BIG_ENDIAN__)
+ /*
+ * Some versions of GCC provide architecture-independent macros for
+ * this. Yes, there are more than two values for __BYTE_ORDER__.
+ */
+# if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
+# define MOZ_LITTLE_ENDIAN 1
+# elif __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
+# define MOZ_BIG_ENDIAN 1
+# else
+# error "Can't handle mixed-endian architectures"
+# endif
+/*
+ * We can't include useful headers like <endian.h> or <sys/isa_defs.h>
+ * here because they're not present on all platforms. Instead we have
+ * this big conditional that ideally will catch all the interesting
+ * cases.
+ */
+#elif defined(__sparc) || defined(__sparc__) || \
+ defined(_POWER) || defined(__powerpc__) || \
+ defined(__ppc__) || defined(__hppa) || \
+ defined(_MIPSEB) || defined(__ARMEB__) || \
+ defined(__s390__) || \
+ (defined(__sh__) && defined(__LITTLE_ENDIAN__)) || \
+ (defined(__ia64) && defined(__BIG_ENDIAN__))
+# define MOZ_BIG_ENDIAN 1
+#elif defined(__i386) || defined(__i386__) || \
+ defined(__x86_64) || defined(__x86_64__) || \
+ defined(_MIPSEL) || defined(__ARMEL__) || \
+ defined(__alpha__) || \
+ (defined(__sh__) && defined(__BIG_ENDIAN__)) || \
+ (defined(__ia64) && !defined(__BIG_ENDIAN__))
+# define MOZ_LITTLE_ENDIAN 1
+#endif
+
+#if MOZ_BIG_ENDIAN
+# define MOZ_LITTLE_ENDIAN 0
+#elif MOZ_LITTLE_ENDIAN
+# define MOZ_BIG_ENDIAN 0
+#else
+# error "Cannot determine endianness"
+#endif
+
+#if defined(__clang__)
+# if __has_builtin(__builtin_bswap16)
+# define MOZ_HAVE_BUILTIN_BYTESWAP16 __builtin_bswap16
+# endif
+#elif defined(__GNUC__)
+# if MOZ_GCC_VERSION_AT_LEAST(4, 8, 0)
+# define MOZ_HAVE_BUILTIN_BYTESWAP16 __builtin_bswap16
+# endif
+#elif defined(_MSC_VER)
+# define MOZ_HAVE_BUILTIN_BYTESWAP16 _byteswap_ushort
+#endif
+
+namespace mozilla {
+
+namespace detail {
+
+/*
+ * We need wrappers here because free functions with default template
+ * arguments and/or partial specialization of function templates are not
+ * supported by all the compilers we use.
+ */
+template<typename T, size_t Size = sizeof(T)>
+struct Swapper;
+
+template<typename T>
+struct Swapper<T, 2>
+{
+ static T swap(T value)
+ {
+#if defined(MOZ_HAVE_BUILTIN_BYTESWAP16)
+ return MOZ_HAVE_BUILTIN_BYTESWAP16(value);
+#else
+ return T(((value & 0x00ff) << 8) | ((value & 0xff00) >> 8));
+#endif
+ }
+};
+
+template<typename T>
+struct Swapper<T, 4>
+{
+ static T swap(T value)
+ {
+#if defined(__clang__) || defined(__GNUC__)
+ return T(__builtin_bswap32(value));
+#elif defined(_MSC_VER)
+ return T(_byteswap_ulong(value));
+#else
+ return T(((value & 0x000000ffU) << 24) |
+ ((value & 0x0000ff00U) << 8) |
+ ((value & 0x00ff0000U) >> 8) |
+ ((value & 0xff000000U) >> 24));
+#endif
+ }
+};
+
+template<typename T>
+struct Swapper<T, 8>
+{
+ static inline T swap(T value)
+ {
+#if defined(__clang__) || defined(__GNUC__)
+ return T(__builtin_bswap64(value));
+#elif defined(_MSC_VER)
+ return T(_byteswap_uint64(value));
+#else
+ return T(((value & 0x00000000000000ffULL) << 56) |
+ ((value & 0x000000000000ff00ULL) << 40) |
+ ((value & 0x0000000000ff0000ULL) << 24) |
+ ((value & 0x00000000ff000000ULL) << 8) |
+ ((value & 0x000000ff00000000ULL) >> 8) |
+ ((value & 0x0000ff0000000000ULL) >> 24) |
+ ((value & 0x00ff000000000000ULL) >> 40) |
+ ((value & 0xff00000000000000ULL) >> 56));
+#endif
+ }
+};
+
+enum Endianness { Little, Big };
+
+#if MOZ_BIG_ENDIAN
+# define MOZ_NATIVE_ENDIANNESS detail::Big
+#else
+# define MOZ_NATIVE_ENDIANNESS detail::Little
+#endif
+
+class EndianUtils
+{
+ /**
+ * Assert that the memory regions [dest, dest+count) and [src, src+count]
+ * do not overlap. count is given in bytes.
+ */
+ static void assertNoOverlap(const void* dest, const void* src, size_t count)
+ {
+ DebugOnly<const uint8_t*> byteDestPtr = static_cast<const uint8_t*>(dest);
+ DebugOnly<const uint8_t*> byteSrcPtr = static_cast<const uint8_t*>(src);
+ MOZ_ASSERT((byteDestPtr < byteSrcPtr &&
+ byteDestPtr + count <= byteSrcPtr) ||
+ (byteSrcPtr < byteDestPtr &&
+ byteSrcPtr + count <= byteDestPtr));
+ }
+
+ template<typename T>
+ static void assertAligned(T* ptr)
+ {
+ MOZ_ASSERT((uintptr_t(ptr) % sizeof(T)) == 0, "Unaligned pointer!");
+ }
+
+ protected:
+ /**
+ * Return |value| converted from SourceEndian encoding to DestEndian
+ * encoding.
+ */
+ template<Endianness SourceEndian, Endianness DestEndian, typename T>
+ static inline T maybeSwap(T value)
+ {
+ if (SourceEndian == DestEndian)
+ return value;
+
+ return Swapper<T>::swap(value);
+ }
+
+ /**
+ * Convert |count| elements at |ptr| from SourceEndian encoding to
+ * DestEndian encoding.
+ */
+ template<Endianness SourceEndian, Endianness DestEndian, typename T>
+ static inline void maybeSwapInPlace(T* ptr, size_t count)
+ {
+ assertAligned(ptr);
+
+ if (SourceEndian == DestEndian)
+ return;
+
+ for (size_t i = 0; i < count; i++)
+ ptr[i] = Swapper<T>::swap(ptr[i]);
+ }
+
+ /**
+ * Write |count| elements to the unaligned address |dest| in DestEndian
+ * format, using elements found at |src| in SourceEndian format.
+ */
+ template<Endianness SourceEndian, Endianness DestEndian, typename T>
+ static void copyAndSwapTo(void* dest, const T* src, size_t count)
+ {
+ assertNoOverlap(dest, src, count * sizeof(T));
+ assertAligned(src);
+
+ if (SourceEndian == DestEndian) {
+ memcpy(dest, src, count * sizeof(T));
+ return;
+ }
+
+ uint8_t* byteDestPtr = static_cast<uint8_t*>(dest);
+ for (size_t i = 0; i < count; ++i) {
+ union {
+ T val;
+ uint8_t buffer[sizeof(T)];
+ } u;
+ u.val = maybeSwap<SourceEndian, DestEndian>(src[i]);
+ memcpy(byteDestPtr, u.buffer, sizeof(T));
+ byteDestPtr += sizeof(T);
+ }
+ }
+
+ /**
+ * Write |count| elements to |dest| in DestEndian format, using elements
+ * found at the unaligned address |src| in SourceEndian format.
+ */
+ template<Endianness SourceEndian, Endianness DestEndian, typename T>
+ static void copyAndSwapFrom(T* dest, const void* src, size_t count)
+ {
+ assertNoOverlap(dest, src, count * sizeof(T));
+ assertAligned(dest);
+
+ if (SourceEndian == DestEndian) {
+ memcpy(dest, src, count * sizeof(T));
+ return;
+ }
+
+ const uint8_t* byteSrcPtr = static_cast<const uint8_t*>(src);
+ for (size_t i = 0; i < count; ++i) {
+ union {
+ T val;
+ uint8_t buffer[sizeof(T)];
+ } u;
+ memcpy(u.buffer, byteSrcPtr, sizeof(T));
+ dest[i] = maybeSwap<SourceEndian, DestEndian>(u.val);
+ byteSrcPtr += sizeof(T);
+ }
+ }
+};
+
+template<Endianness ThisEndian>
+class Endian : private EndianUtils
+{
+ protected:
+ /** Read a uint16_t in ThisEndian endianness from |p| and return it. */
+ static MOZ_WARN_UNUSED_RESULT uint16_t readUint16(const void* p) {
+ return read<uint16_t>(p);
+ }
+
+ /** Read a uint32_t in ThisEndian endianness from |p| and return it. */
+ static MOZ_WARN_UNUSED_RESULT uint32_t readUint32(const void* p) {
+ return read<uint32_t>(p);
+ }
+
+ /** Read a uint64_t in ThisEndian endianness from |p| and return it. */
+ static MOZ_WARN_UNUSED_RESULT uint64_t readUint64(const void* p) {
+ return read<uint64_t>(p);
+ }
+
+ /** Read an int16_t in ThisEndian endianness from |p| and return it. */
+ static MOZ_WARN_UNUSED_RESULT int16_t readInt16(const void* p) {
+ return read<int16_t>(p);
+ }
+
+ /** Read an int32_t in ThisEndian endianness from |p| and return it. */
+ static MOZ_WARN_UNUSED_RESULT int32_t readInt32(const void* p) {
+ return read<uint32_t>(p);
+ }
+
+ /** Read an int64_t in ThisEndian endianness from |p| and return it. */
+ static MOZ_WARN_UNUSED_RESULT int64_t readInt64(const void* p) {
+ return read<int64_t>(p);
+ }
+
+ /** Write |val| to |p| using ThisEndian endianness. */
+ static void writeUint16(void* p, uint16_t val) {
+ write(p, val);
+ }
+ /** Write |val| to |p| using ThisEndian endianness. */
+ static void writeUint32(void* p, uint32_t val) {
+ write(p, val);
+ }
+ /** Write |val| to |p| using ThisEndian endianness. */
+ static void writeUint64(void* p, uint64_t val) {
+ write(p, val);
+ }
+
+ /** Write |val| to |p| using ThisEndian endianness. */
+ static void writeInt16(void* p, int16_t val) {
+ write(p, val);
+ }
+ /** Write |val| to |p| using ThisEndian endianness. */
+ static void writeInt32(void* p, int32_t val) {
+ write(p, val);
+ }
+ /** Write |val| to |p| using ThisEndian endianness. */
+ static void writeInt64(void* p, int64_t val) {
+ write(p, val);
+ }
+
+ /*
+ * Converts a value of type T to little-endian format.
+ *
+ * This function is intended for cases where you have data in your
+ * native-endian format and you need it to appear in little-endian
+ * format for transmission.
+ */
+ template<typename T>
+ MOZ_WARN_UNUSED_RESULT static T swapToLittleEndian(T value) {
+ return maybeSwap<ThisEndian, Little>(value);
+ }
+ /*
+ * Copies count values of type T starting at src to dest, converting
+ * them to little-endian format if ThisEndian is Big.
+ * As with memcpy, dest and src must not overlap.
+ */
+ template<typename T>
+ static void copyAndSwapToLittleEndian(void* dest, const T* src,
+ size_t count) {
+ copyAndSwapTo<ThisEndian, Little>(dest, src, count);
+ }
+ /*
+ * Likewise, but converts values in place.
+ */
+ template<typename T>
+ static void swapToLittleEndianInPlace(T* p, size_t count) {
+ maybeSwapInPlace<ThisEndian, Little>(p, count);
+ }
+
+ /*
+ * Converts a value of type T to big-endian format.
+ */
+ template<typename T>
+ MOZ_WARN_UNUSED_RESULT static T swapToBigEndian(T value) {
+ return maybeSwap<ThisEndian, Big>(value);
+ }
+ /*
+ * Copies count values of type T starting at src to dest, converting
+ * them to big-endian format if ThisEndian is Little.
+ * As with memcpy, dest and src must not overlap.
+ */
+ template<typename T>
+ static void copyAndSwapToBigEndian(void* dest, const T* src, size_t count) {
+ copyAndSwapTo<ThisEndian, Big>(dest, src, count);
+ }
+ /*
+ * Likewise, but converts values in place.
+ */
+ template<typename T>
+ static void swapToBigEndianInPlace(T* p, size_t count) {
+ maybeSwapInPlace<ThisEndian, Big>(p, count);
+ }
+
+ /*
+ * Synonyms for the big-endian functions, for better readability
+ * in network code.
+ */
+ template<typename T>
+ MOZ_WARN_UNUSED_RESULT static T swapToNetworkOrder(T value) {
+ return swapToBigEndian(value);
+ }
+ template<typename T>
+ static void
+ copyAndSwapToNetworkOrder(void* dest, const T* src, size_t count) {
+ copyAndSwapToBigEndian(dest, src, count);
+ }
+ template<typename T>
+ static void
+ swapToNetworkOrderInPlace(T* p, size_t count) {
+ swapToBigEndianInPlace(p, count);
+ }
+
+ /*
+ * Converts a value of type T from little-endian format.
+ */
+ template<typename T>
+ MOZ_WARN_UNUSED_RESULT static T swapFromLittleEndian(T value) {
+ return maybeSwap<Little, ThisEndian>(value);
+ }
+ /*
+ * Copies count values of type T starting at src to dest, converting
+ * them to little-endian format if ThisEndian is Big.
+ * As with memcpy, dest and src must not overlap.
+ */
+ template<typename T>
+ static void copyAndSwapFromLittleEndian(T* dest, const void* src,
+ size_t count) {
+ copyAndSwapFrom<Little, ThisEndian>(dest, src, count);
+ }
+ /*
+ * Likewise, but converts values in place.
+ */
+ template<typename T>
+ static void swapFromLittleEndianInPlace(T* p, size_t count) {
+ maybeSwapInPlace<Little, ThisEndian>(p, count);
+ }
+
+ /*
+ * Converts a value of type T from big-endian format.
+ */
+ template<typename T>
+ MOZ_WARN_UNUSED_RESULT static T swapFromBigEndian(T value) {
+ return maybeSwap<Big, ThisEndian>(value);
+ }
+ /*
+ * Copies count values of type T starting at src to dest, converting
+ * them to big-endian format if ThisEndian is Little.
+ * As with memcpy, dest and src must not overlap.
+ */
+ template<typename T>
+ static void copyAndSwapFromBigEndian(T* dest, const void* src,
+ size_t count) {
+ copyAndSwapFrom<Big, ThisEndian>(dest, src, count);
+ }
+ /*
+ * Likewise, but converts values in place.
+ */
+ template<typename T>
+ static void swapFromBigEndianInPlace(T* p, size_t count) {
+ maybeSwapInPlace<Big, ThisEndian>(p, count);
+ }
+
+ /*
+ * Synonyms for the big-endian functions, for better readability
+ * in network code.
+ */
+ template<typename T>
+ MOZ_WARN_UNUSED_RESULT static T swapFromNetworkOrder(T value) {
+ return swapFromBigEndian(value);
+ }
+ template<typename T>
+ static void copyAndSwapFromNetworkOrder(T* dest, const void* src,
+ size_t count) {
+ copyAndSwapFromBigEndian(dest, src, count);
+ }
+ template<typename T>
+ static void swapFromNetworkOrderInPlace(T* p, size_t count) {
+ swapFromBigEndianInPlace(p, count);
+ }
+
+ private:
+ /**
+ * Read a value of type T, encoded in endianness ThisEndian from |p|.
+ * Return that value encoded in native endianness.
+ */
+ template<typename T>
+ static T read(const void* p) {
+ union {
+ T val;
+ uint8_t buffer[sizeof(T)];
+ } u;
+ memcpy(u.buffer, p, sizeof(T));
+ return maybeSwap<ThisEndian, MOZ_NATIVE_ENDIANNESS>(u.val);
+ }
+
+ /**
+ * Write a value of type T, in native endianness, to |p|, in ThisEndian
+ * endianness.
+ */
+ template<typename T>
+ static void write(void* p, T value) {
+ T tmp = maybeSwap<MOZ_NATIVE_ENDIANNESS, ThisEndian>(value);
+ memcpy(p, &tmp, sizeof(T));
+ }
+
+ Endian() MOZ_DELETE;
+ Endian(const Endian& other) MOZ_DELETE;
+ void operator=(const Endian& other) MOZ_DELETE;
+};
+
+template<Endianness ThisEndian>
+class EndianReadWrite : public Endian<ThisEndian>
+{
+ private:
+ typedef Endian<ThisEndian> super;
+
+ public:
+ using super::readUint16;
+ using super::readUint32;
+ using super::readUint64;
+ using super::readInt16;
+ using super::readInt32;
+ using super::readInt64;
+ using super::writeUint16;
+ using super::writeUint32;
+ using super::writeUint64;
+ using super::writeInt16;
+ using super::writeInt32;
+ using super::writeInt64;
+};
+
+} /* namespace detail */
+
+class LittleEndian MOZ_FINAL : public detail::EndianReadWrite<detail::Little>
+{};
+
+class BigEndian MOZ_FINAL : public detail::EndianReadWrite<detail::Big>
+{};
+
+typedef BigEndian NetworkEndian;
+
+class NativeEndian MOZ_FINAL : public detail::Endian<MOZ_NATIVE_ENDIANNESS>
+{
+ private:
+ typedef detail::Endian<MOZ_NATIVE_ENDIANNESS> super;
+
+ public:
+ /*
+ * These functions are intended for cases where you have data in your
+ * native-endian format and you need the data to appear in the appropriate
+ * endianness for transmission, serialization, etc.
+ */
+ using super::swapToLittleEndian;
+ using super::copyAndSwapToLittleEndian;
+ using super::swapToLittleEndianInPlace;
+ using super::swapToBigEndian;
+ using super::copyAndSwapToBigEndian;
+ using super::swapToBigEndianInPlace;
+ using super::swapToNetworkOrder;
+ using super::copyAndSwapToNetworkOrder;
+ using super::swapToNetworkOrderInPlace;
+
+ /*
+ * These functions are intended for cases where you have data in the
+ * given endianness (e.g. reading from disk or a file-format) and you
+ * need the data to appear in native-endian format for processing.
+ */
+ using super::swapFromLittleEndian;
+ using super::copyAndSwapFromLittleEndian;
+ using super::swapFromLittleEndianInPlace;
+ using super::swapFromBigEndian;
+ using super::copyAndSwapFromBigEndian;
+ using super::swapFromBigEndianInPlace;
+ using super::swapFromNetworkOrder;
+ using super::copyAndSwapFromNetworkOrder;
+ using super::swapFromNetworkOrderInPlace;
+};
+
+#undef MOZ_NATIVE_ENDIANNESS
+
+} /* namespace mozilla */
+
+#endif /* mozilla_Endian_h_ */
diff --git a/mfbt/EnumSet.h b/mfbt/EnumSet.h
new file mode 100644
index 0000000..b18b005
--- /dev/null
+++ b/mfbt/EnumSet.h
@@ -0,0 +1,175 @@
+/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+/* A set abstraction for enumeration values. */
+
+#ifndef mozilla_EnumSet_h
+#define mozilla_EnumSet_h
+
+#include "mozilla/Assertions.h"
+#include "mozilla/StandardInteger.h"
+
+namespace mozilla {
+
+/**
+ * EnumSet<T> is a set of values defined by an enumeration. It is implemented
+ * using a 32 bit mask for each value so it will only work for enums with an int
+ * representation less than 32. It works both for enum and enum class types.
+ */
+template<typename T>
+class EnumSet
+{
+ public:
+ EnumSet()
+ : mBitField(0)
+ { }
+
+ EnumSet(T aEnum)
+ : mBitField(aEnum)
+ { }
+
+ EnumSet(T aEnum1, T aEnum2)
+ : mBitField(bitFor(aEnum1) |
+ bitFor(aEnum2))
+ { }
+
+ EnumSet(T aEnum1, T aEnum2, T aEnum3)
+ : mBitField(bitFor(aEnum1) |
+ bitFor(aEnum2) |
+ bitFor(aEnum3))
+ { }
+
+ EnumSet(T aEnum1, T aEnum2, T aEnum3, T aEnum4)
+ : mBitField(bitFor(aEnum1) |
+ bitFor(aEnum2) |
+ bitFor(aEnum3) |
+ bitFor(aEnum4))
+ { }
+
+ EnumSet(const EnumSet& aEnumSet)
+ : mBitField(aEnumSet.mBitField)
+ { }
+
+ /**
+ * Add an element
+ */
+ void operator+=(T aEnum) {
+ mBitField |= bitFor(aEnum);
+ }
+
+ /**
+ * Add an element
+ */
+ EnumSet<T> operator+(T aEnum) const {
+ EnumSet<T> result(*this);
+ result += aEnum;
+ return result;
+ }
+
+ /**
+ * Union
+ */
+ void operator+=(const EnumSet<T> aEnumSet) {
+ mBitField |= aEnumSet.mBitField;
+ }
+
+ /**
+ * Union
+ */
+ EnumSet<T> operator+(const EnumSet<T> aEnumSet) const {
+ EnumSet<T> result(*this);
+ result += aEnumSet;
+ return result;
+ }
+
+ /**
+ * Remove an element
+ */
+ void operator-=(T aEnum) {
+ mBitField &= ~(bitFor(aEnum));
+ }
+
+ /**
+ * Remove an element
+ */
+ EnumSet<T> operator-(T aEnum) const {
+ EnumSet<T> result(*this);
+ result -= aEnum;
+ return result;
+ }
+
+ /**
+ * Remove a set of elements
+ */
+ void operator-=(const EnumSet<T> aEnumSet) {
+ mBitField &= ~(aEnumSet.mBitField);
+ }
+
+ /**
+ * Remove a set of elements
+ */
+ EnumSet<T> operator-(const EnumSet<T> aEnumSet) const {
+ EnumSet<T> result(*this);
+ result -= aEnumSet;
+ return result;
+ }
+
+ /**
+ * Intersection
+ */
+ void operator&=(const EnumSet<T> aEnumSet) {
+ mBitField &= aEnumSet.mBitField;
+ }
+
+ /**
+ * Intersection
+ */
+ EnumSet<T> operator&(const EnumSet<T> aEnumSet) const {
+ EnumSet<T> result(*this);
+ result &= aEnumSet;
+ return result;
+ }
+
+ /**
+ * Equality
+ */
+
+ bool operator==(const EnumSet<T> aEnumSet) const {
+ return mBitField == aEnumSet.mBitField;
+ }
+
+ /**
+ * Test is an element is contained in the set
+ */
+ bool contains(T aEnum) const {
+ return mBitField & bitFor(aEnum);
+ }
+
+ /**
+ * Return the number of elements in the set
+ */
+
+ uint8_t size() {
+ uint8_t count = 0;
+ for (uint32_t bitField = mBitField; bitField; bitField >>= 1) {
+ if (bitField & 1)
+ count++;
+ }
+ return count;
+ }
+
+ private:
+ static uint32_t bitFor(T aEnum) {
+ uint32_t bitNumber(aEnum);
+ MOZ_ASSERT(bitNumber < 32);
+ return 1U << bitNumber;
+ }
+
+ uint32_t mBitField;
+};
+
+} // namespace mozilla
+
+#endif // mozilla_EnumSet_h_
diff --git a/mfbt/FloatingPoint.h b/mfbt/FloatingPoint.h
new file mode 100644
index 0000000..a79a321
--- /dev/null
+++ b/mfbt/FloatingPoint.h
@@ -0,0 +1,196 @@
+/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+/* Various predicates and operations on IEEE-754 floating point types. */
+
+#ifndef mozilla_FloatingPoint_h_
+#define mozilla_FloatingPoint_h_
+
+#include "mozilla/Assertions.h"
+#include "mozilla/Attributes.h"
+#include "mozilla/Casting.h"
+#include "mozilla/StandardInteger.h"
+
+namespace mozilla {
+
+/*
+ * It's reasonable to ask why we have this header at all. Don't isnan,
+ * copysign, the built-in comparison operators, and the like solve these
+ * problems? Unfortunately, they don't. We've found that various compilers
+ * (MSVC, MSVC when compiling with PGO, and GCC on OS X, at least) miscompile
+ * the standard methods in various situations, so we can't use them. Some of
+ * these compilers even have problems compiling seemingly reasonable bitwise
+ * algorithms! But with some care we've found algorithms that seem to not
+ * trigger those compiler bugs.
+ *
+ * For the aforementioned reasons, be very wary of making changes to any of
+ * these algorithms. If you must make changes, keep a careful eye out for
+ * compiler bustage, particularly PGO-specific bustage.
+ */
+
+/*
+ * These implementations all assume |double| is a 64-bit double format number
+ * type, compatible with the IEEE-754 standard. C/C++ don't require this to be
+ * the case. But we required this in implementations of these algorithms that
+ * preceded this header, so we shouldn't break anything if we continue doing so.
+ */
+MOZ_STATIC_ASSERT(sizeof(double) == sizeof(uint64_t), "double must be 64 bits");
+
+const unsigned DoubleExponentBias = 1023;
+const unsigned DoubleExponentShift = 52;
+
+const uint64_t DoubleSignBit = 0x8000000000000000ULL;
+const uint64_t DoubleExponentBits = 0x7ff0000000000000ULL;
+const uint64_t DoubleSignificandBits = 0x000fffffffffffffULL;
+
+MOZ_STATIC_ASSERT((DoubleSignBit & DoubleExponentBits) == 0,
+ "sign bit doesn't overlap exponent bits");
+MOZ_STATIC_ASSERT((DoubleSignBit & DoubleSignificandBits) == 0,
+ "sign bit doesn't overlap significand bits");
+MOZ_STATIC_ASSERT((DoubleExponentBits & DoubleSignificandBits) == 0,
+ "exponent bits don't overlap significand bits");
+
+MOZ_STATIC_ASSERT((DoubleSignBit | DoubleExponentBits | DoubleSignificandBits) ==
+ ~uint64_t(0),
+ "all bits accounted for");
+
+/** Determines whether a double is NaN. */
+static MOZ_ALWAYS_INLINE bool
+IsNaN(double d)
+{
+ /*
+ * A double is NaN if all exponent bits are 1 and the significand contains at
+ * least one non-zero bit.
+ */
+ uint64_t bits = BitwiseCast<uint64_t>(d);
+ return (bits & DoubleExponentBits) == DoubleExponentBits &&
+ (bits & DoubleSignificandBits) != 0;
+}
+
+/** Determines whether a double is +Infinity or -Infinity. */
+static MOZ_ALWAYS_INLINE bool
+IsInfinite(double d)
+{
+ /* Infinities have all exponent bits set to 1 and an all-0 significand. */
+ uint64_t bits = BitwiseCast<uint64_t>(d);
+ return (bits & ~DoubleSignBit) == DoubleExponentBits;
+}
+
+/** Determines whether a double is not NaN or infinite. */
+static MOZ_ALWAYS_INLINE bool
+IsFinite(double d)
+{
+ /*
+ * NaN and Infinities are the only non-finite doubles, and both have all
+ * exponent bits set to 1.
+ */
+ uint64_t bits = BitwiseCast<uint64_t>(d);
+ return (bits & DoubleExponentBits) != DoubleExponentBits;
+}
+
+/**
+ * Determines whether a double is negative. It is an error to call this method
+ * on a double which is NaN.
+ */
+static MOZ_ALWAYS_INLINE bool
+IsNegative(double d)
+{
+ MOZ_ASSERT(!IsNaN(d), "NaN does not have a sign");
+
+ /* The sign bit is set if the double is negative. */
+ uint64_t bits = BitwiseCast<uint64_t>(d);
+ return (bits & DoubleSignBit) != 0;
+}
+
+/** Determines whether a double represents -0. */
+static MOZ_ALWAYS_INLINE bool
+IsNegativeZero(double d)
+{
+ /* Only the sign bit is set if the double is -0. */
+ uint64_t bits = BitwiseCast<uint64_t>(d);
+ return bits == DoubleSignBit;
+}
+
+/** Returns the exponent portion of the double. */
+static MOZ_ALWAYS_INLINE int_fast16_t
+ExponentComponent(double d)
+{
+ /*
+ * The exponent component of a double is an unsigned number, biased from its
+ * actual value. Subtract the bias to retrieve the actual exponent.
+ */
+ uint64_t bits = BitwiseCast<uint64_t>(d);
+ return int_fast16_t((bits & DoubleExponentBits) >> DoubleExponentShift) -
+ int_fast16_t(DoubleExponentBias);
+}
+
+/** Returns +Infinity. */
+static MOZ_ALWAYS_INLINE double
+PositiveInfinity()
+{
+ /*
+ * Positive infinity has all exponent bits set, sign bit set to 0, and no
+ * significand.
+ */
+ return BitwiseCast<double>(DoubleExponentBits);
+}
+
+/** Returns -Infinity. */
+static MOZ_ALWAYS_INLINE double
+NegativeInfinity()
+{
+ /*
+ * Negative infinity has all exponent bits set, sign bit set to 1, and no
+ * significand.
+ */
+ return BitwiseCast<double>(DoubleSignBit | DoubleExponentBits);
+}
+
+/** Constructs a NaN value with the specified sign bit and significand bits. */
+static MOZ_ALWAYS_INLINE double
+SpecificNaN(int signbit, uint64_t significand)
+{
+ MOZ_ASSERT(signbit == 0 || signbit == 1);
+ MOZ_ASSERT((significand & ~DoubleSignificandBits) == 0);
+ MOZ_ASSERT(significand & DoubleSignificandBits);
+
+ double d = BitwiseCast<double>((signbit ? DoubleSignBit : 0) |
+ DoubleExponentBits |
+ significand);
+ MOZ_ASSERT(IsNaN(d));
+ return d;
+}
+
+/** Computes the smallest non-zero positive double value. */
+static MOZ_ALWAYS_INLINE double
+MinDoubleValue()
+{
+ return BitwiseCast<double>(uint64_t(1));
+}
+
+static MOZ_ALWAYS_INLINE bool
+DoubleIsInt32(double d, int32_t* i)
+{
+ /*
+ * XXX Casting a double that doesn't truncate to int32_t, to int32_t, induces
+ * undefined behavior. We should definitely fix this (bug 744965), but as
+ * apparently it "works" in practice, it's not a pressing concern now.
+ */
+ return !IsNegativeZero(d) && d == (*i = int32_t(d));
+}
+
+/**
+ * Computes a NaN value. Do not use this method if you depend upon a particular
+ * NaN value being returned.
+ */
+static MOZ_ALWAYS_INLINE double
+UnspecifiedNaN()
+{
+ return SpecificNaN(0, 0xfffffffffffffULL);
+}
+
+} /* namespace mozilla */
+
+#endif /* mozilla_FloatingPoint_h_ */
diff --git a/mfbt/GuardObjects.h b/mfbt/GuardObjects.h
new file mode 100644
index 0000000..6c20589
--- /dev/null
+++ b/mfbt/GuardObjects.h
@@ -0,0 +1,150 @@
+/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+/* Implementation of macros to ensure correct use of RAII Auto* objects. */
+
+#ifndef mozilla_GuardObjects_h
+#define mozilla_GuardObjects_h
+
+#include "mozilla/Assertions.h"
+#include "mozilla/Types.h"
+
+#ifdef __cplusplus
+
+#ifdef DEBUG
+
+namespace mozilla {
+namespace detail {
+
+/*
+ * The following classes are designed to cause assertions to detect
+ * inadvertent use of guard objects as temporaries. In other words,
+ * when we have a guard object whose only purpose is its constructor and
+ * destructor (and is never otherwise referenced), the intended use
+ * might be:
+ *
+ * AutoRestore savePainting(mIsPainting);
+ *
+ * but is is easy to accidentally write:
+ *
+ * AutoRestore(mIsPainting);
+ *
+ * which compiles just fine, but runs the destructor well before the
+ * intended time.
+ *
+ * They work by adding (#ifdef DEBUG) an additional parameter to the
+ * guard object's constructor, with a default value, so that users of
+ * the guard object's API do not need to do anything. The default value
+ * of this parameter is a temporary object. C++ (ISO/IEC 14882:1998),
+ * section 12.2 [class.temporary], clauses 4 and 5 seem to assume a
+ * guarantee that temporaries are destroyed in the reverse of their
+ * construction order, but I actually can't find a statement that that
+ * is true in the general case (beyond the two specific cases mentioned
+ * there). However, it seems to be true.
+ *
+ * These classes are intended to be used only via the macros immediately
+ * below them:
+ *
+ * MOZ_DECL_USE_GUARD_OBJECT_NOTIFIER declares (ifdef DEBUG) a member
+ * variable, and should be put where a declaration of a private
+ * member variable would be placed.
+ * MOZ_GUARD_OBJECT_NOTIFIER_PARAM should be placed at the end of the
+ * parameters to each constructor of the guard object; it declares
+ * (ifdef DEBUG) an additional parameter. (But use the *_ONLY_PARAM
+ * variant for constructors that take no other parameters.)
+ * MOZ_GUARD_OBJECT_NOTIFIER_PARAM_IN_IMPL should likewise be used in
+ * the implementation of such constructors when they are not inline.
+ * MOZ_GUARD_OBJECT_NOTIFIER_PARAM_TO_PARENT should be used in
+ * the implementation of such constructors to pass the parameter to
+ * a base class that also uses these macros
+ * MOZ_GUARD_OBJECT_NOTIFIER_INIT is a statement that belongs in each
+ * constructor. It uses the parameter declared by
+ * MOZ_GUARD_OBJECT_NOTIFIER_PARAM.
+ *
+ * For more details, and examples of using these macros, see
+ * https://developer.mozilla.org/en/Using_RAII_classes_in_Mozilla
+ */
+class MOZ_EXPORT GuardObjectNotifier
+{
+ private:
+ bool* statementDone;
+
+ public:
+ GuardObjectNotifier() : statementDone(NULL) { }
+
+ ~GuardObjectNotifier() {
+ *statementDone = true;
+ }
+
+ void setStatementDone(bool* statementIsDone) {
+ statementDone = statementIsDone;
+ }
+};
+
+class MOZ_EXPORT GuardObjectNotificationReceiver
+{
+ private:
+ bool statementDone;
+
+ public:
+ GuardObjectNotificationReceiver() : statementDone(false) { }
+
+ ~GuardObjectNotificationReceiver() {
+ /*
+ * Assert that the guard object was not used as a temporary. (Note that
+ * this assert might also fire if init is not called because the guard
+ * object's implementation is not using the above macros correctly.)
+ */
+ MOZ_ASSERT(statementDone);
+ }
+
+ void init(const GuardObjectNotifier& constNotifier) {
+ /*
+ * constNotifier is passed as a const reference so that we can pass a
+ * temporary, but we really intend it as non-const.
+ */
+ GuardObjectNotifier& notifier = const_cast<GuardObjectNotifier&>(constNotifier);
+ notifier.setStatementDone(&statementDone);
+ }
+};
+
+} /* namespace detail */
+} /* namespace mozilla */
+
+#endif /* DEBUG */
+
+#ifdef DEBUG
+# define MOZ_DECL_USE_GUARD_OBJECT_NOTIFIER \
+ mozilla::detail::GuardObjectNotificationReceiver _mCheckNotUsedAsTemporary;
+# define MOZ_GUARD_OBJECT_NOTIFIER_PARAM \
+ , const mozilla::detail::GuardObjectNotifier& _notifier = \
+ mozilla::detail::GuardObjectNotifier()
+# define MOZ_GUARD_OBJECT_NOTIFIER_ONLY_PARAM \
+ const mozilla::detail::GuardObjectNotifier& _notifier = \
+ mozilla::detail::GuardObjectNotifier()
+# define MOZ_GUARD_OBJECT_NOTIFIER_PARAM_IN_IMPL \
+ , const mozilla::detail::GuardObjectNotifier& _notifier
+# define MOZ_GUARD_OBJECT_NOTIFIER_ONLY_PARAM_IN_IMPL \
+ const mozilla::detail::GuardObjectNotifier& _notifier
+# define MOZ_GUARD_OBJECT_NOTIFIER_PARAM_TO_PARENT \
+ , _notifier
+# define MOZ_GUARD_OBJECT_NOTIFIER_ONLY_PARAM_TO_PARENT \
+ _notifier
+# define MOZ_GUARD_OBJECT_NOTIFIER_INIT \
+ do { _mCheckNotUsedAsTemporary.init(_notifier); } while (0)
+#else
+# define MOZ_DECL_USE_GUARD_OBJECT_NOTIFIER
+# define MOZ_GUARD_OBJECT_NOTIFIER_PARAM
+# define MOZ_GUARD_OBJECT_NOTIFIER_ONLY_PARAM
+# define MOZ_GUARD_OBJECT_NOTIFIER_PARAM_IN_IMPL
+# define MOZ_GUARD_OBJECT_NOTIFIER_ONLY_PARAM_IN_IMPL
+# define MOZ_GUARD_OBJECT_NOTIFIER_ONLY_PARAM_TO_PARENT
+# define MOZ_GUARD_OBJECT_NOTIFIER_PARAM_TO_PARENT
+# define MOZ_GUARD_OBJECT_NOTIFIER_INIT do { } while (0)
+#endif
+
+#endif /* __cplusplus */
+
+#endif /* mozilla_GuardObjects_h */
diff --git a/mfbt/HashFunctions.cpp b/mfbt/HashFunctions.cpp
new file mode 100644
index 0000000..ddbd352
--- /dev/null
+++ b/mfbt/HashFunctions.cpp
@@ -0,0 +1,38 @@
+/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+/* Implementations of hash functions. */
+
+#include "mozilla/HashFunctions.h"
+#include "mozilla/Types.h"
+
+#include <string.h>
+
+namespace mozilla {
+
+uint32_t
+HashBytes(const void* bytes, size_t length)
+{
+ uint32_t hash = 0;
+ const char* b = reinterpret_cast<const char*>(bytes);
+
+ /* Walk word by word. */
+ size_t i = 0;
+ for (; i < length - (length % sizeof(size_t)); i += sizeof(size_t)) {
+ /* Do an explicitly unaligned load of the data. */
+ size_t data;
+ memcpy(&data, b + i, sizeof(size_t));
+
+ hash = AddToHash(hash, data, sizeof(data));
+ }
+
+ /* Get the remaining bytes. */
+ for (; i < length; i++)
+ hash = AddToHash(hash, b[i]);
+
+ return hash;
+}
+
+} /* namespace mozilla */
diff --git a/mfbt/HashFunctions.h b/mfbt/HashFunctions.h
new file mode 100644
index 0000000..e5f971b
--- /dev/null
+++ b/mfbt/HashFunctions.h
@@ -0,0 +1,359 @@
+/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+/* Utilities for hashing. */
+
+/*
+ * This file exports functions for hashing data down to a 32-bit value,
+ * including:
+ *
+ * - HashString Hash a char* or uint16_t/wchar_t* of known or unknown
+ * length.
+ *
+ * - HashBytes Hash a byte array of known length.
+ *
+ * - HashGeneric Hash one or more values. Currently, we support uint32_t,
+ * types which can be implicitly cast to uint32_t, data
+ * pointers, and function pointers.
+ *
+ * - AddToHash Add one or more values to the given hash. This supports the
+ * same list of types as HashGeneric.
+ *
+ *
+ * You can chain these functions together to hash complex objects. For example:
+ *
+ * class ComplexObject
+ * {
+ * char* str;
+ * uint32_t uint1, uint2;
+ * void (*callbackFn)();
+ *
+ * public:
+ * uint32_t hash() {
+ * uint32_t hash = HashString(str);
+ * hash = AddToHash(hash, uint1, uint2);
+ * return AddToHash(hash, callbackFn);
+ * }
+ * };
+ *
+ * If you want to hash an nsAString or nsACString, use the HashString functions
+ * in nsHashKeys.h.
+ */
+
+#ifndef mozilla_HashFunctions_h_
+#define mozilla_HashFunctions_h_
+
+#include "mozilla/Assertions.h"
+#include "mozilla/Attributes.h"
+#include "mozilla/StandardInteger.h"
+#include "mozilla/Types.h"
+
+#ifdef __cplusplus
+namespace mozilla {
+
+/**
+ * The golden ratio as a 32-bit fixed-point value.
+ */
+static const uint32_t GoldenRatioU32 = 0x9E3779B9U;
+
+inline uint32_t
+RotateBitsLeft32(uint32_t value, uint8_t bits)
+{
+ MOZ_ASSERT(bits < 32);
+ return (value << bits) | (value >> (32 - bits));
+}
+
+namespace detail {
+
+inline uint32_t
+AddU32ToHash(uint32_t hash, uint32_t value)
+{
+ /*
+ * This is the meat of all our hash routines. This hash function is not
+ * particularly sophisticated, but it seems to work well for our mostly
+ * plain-text inputs. Implementation notes follow.
+ *
+ * Our use of the golden ratio here is arbitrary; we could pick almost any
+ * number which:
+ *
+ * * is odd (because otherwise, all our hash values will be even)
+ *
+ * * has a reasonably-even mix of 1's and 0's (consider the extreme case
+ * where we multiply by 0x3 or 0xeffffff -- this will not produce good
+ * mixing across all bits of the hash).
+ *
+ * The rotation length of 5 is also arbitrary, although an odd number is again
+ * preferable so our hash explores the whole universe of possible rotations.
+ *
+ * Finally, we multiply by the golden ratio *after* xor'ing, not before.
+ * Otherwise, if |hash| is 0 (as it often is for the beginning of a message),
+ * the expression
+ *
+ * (GoldenRatioU32 * RotateBitsLeft(hash, 5)) |xor| value
+ *
+ * evaluates to |value|.
+ *
+ * (Number-theoretic aside: Because any odd number |m| is relatively prime to
+ * our modulus (2^32), the list
+ *
+ * [x * m (mod 2^32) for 0 <= x < 2^32]
+ *
+ * has no duplicate elements. This means that multiplying by |m| does not
+ * cause us to skip any possible hash values.
+ *
+ * It's also nice if |m| has large-ish order mod 2^32 -- that is, if the
+ * smallest k such that m^k == 1 (mod 2^32) is large -- so we can safely
+ * multiply our hash value by |m| a few times without negating the
+ * multiplicative effect. Our golden ratio constant has order 2^29, which is
+ * more than enough for our purposes.)
+ */
+ return GoldenRatioU32 * (RotateBitsLeft32(hash, 5) ^ value);
+}
+
+/**
+ * AddUintptrToHash takes sizeof(uintptr_t) as a template parameter.
+ */
+template<size_t PtrSize>
+inline uint32_t
+AddUintptrToHash(uint32_t hash, uintptr_t value);
+
+template<>
+inline uint32_t
+AddUintptrToHash<4>(uint32_t hash, uintptr_t value)
+{
+ return AddU32ToHash(hash, static_cast<uint32_t>(value));
+}
+
+template<>
+inline uint32_t
+AddUintptrToHash<8>(uint32_t hash, uintptr_t value)
+{
+ /*
+ * The static cast to uint64_t below is necessary because this function
+ * sometimes gets compiled on 32-bit platforms (yes, even though it's a
+ * template and we never call this particular override in a 32-bit build). If
+ * we do value >> 32 on a 32-bit machine, we're shifting a 32-bit uintptr_t
+ * right 32 bits, and the compiler throws an error.
+ */
+ uint32_t v1 = static_cast<uint32_t>(value);
+ uint32_t v2 = static_cast<uint32_t>(static_cast<uint64_t>(value) >> 32);
+ return AddU32ToHash(AddU32ToHash(hash, v1), v2);
+}
+
+} /* namespace detail */
+
+/**
+ * AddToHash takes a hash and some values and returns a new hash based on the
+ * inputs.
+ *
+ * Currently, we support hashing uint32_t's, values which we can implicitly
+ * convert to uint32_t, data pointers, and function pointers.
+ */
+template<typename A>
+MOZ_WARN_UNUSED_RESULT
+inline uint32_t
+AddToHash(uint32_t hash, A a)
+{
+ /*
+ * Try to convert |A| to uint32_t implicitly. If this works, great. If not,
+ * we'll error out.
+ */
+ return detail::AddU32ToHash(hash, a);
+}
+
+template<typename A>
+MOZ_WARN_UNUSED_RESULT
+inline uint32_t
+AddToHash(uint32_t hash, A* a)
+{
+ /*
+ * You might think this function should just take a void*. But then we'd only
+ * catch data pointers and couldn't handle function pointers.
+ */
+
+ MOZ_STATIC_ASSERT(sizeof(a) == sizeof(uintptr_t),
+ "Strange pointer!");
+
+ return detail::AddUintptrToHash<sizeof(uintptr_t)>(hash, uintptr_t(a));
+}
+
+template<>
+MOZ_WARN_UNUSED_RESULT
+inline uint32_t
+AddToHash(uint32_t hash, uintptr_t a)
+{
+ return detail::AddUintptrToHash<sizeof(uintptr_t)>(hash, a);
+}
+
+template<typename A, typename B>
+MOZ_WARN_UNUSED_RESULT
+uint32_t
+AddToHash(uint32_t hash, A a, B b)
+{
+ return AddToHash(AddToHash(hash, a), b);
+}
+
+template<typename A, typename B, typename C>
+MOZ_WARN_UNUSED_RESULT
+uint32_t
+AddToHash(uint32_t hash, A a, B b, C c)
+{
+ return AddToHash(AddToHash(hash, a, b), c);
+}
+
+template<typename A, typename B, typename C, typename D>
+MOZ_WARN_UNUSED_RESULT
+uint32_t
+AddToHash(uint32_t hash, A a, B b, C c, D d)
+{
+ return AddToHash(AddToHash(hash, a, b, c), d);
+}
+
+template<typename A, typename B, typename C, typename D, typename E>
+MOZ_WARN_UNUSED_RESULT
+uint32_t
+AddToHash(uint32_t hash, A a, B b, C c, D d, E e)
+{
+ return AddToHash(AddToHash(hash, a, b, c, d), e);
+}
+
+/**
+ * The HashGeneric class of functions let you hash one or more values.
+ *
+ * If you want to hash together two values x and y, calling HashGeneric(x, y) is
+ * much better than calling AddToHash(x, y), because AddToHash(x, y) assumes
+ * that x has already been hashed.
+ */
+template<typename A>
+MOZ_WARN_UNUSED_RESULT
+inline uint32_t
+HashGeneric(A a)
+{
+ return AddToHash(0, a);
+}
+
+template<typename A, typename B>
+MOZ_WARN_UNUSED_RESULT
+inline uint32_t
+HashGeneric(A a, B b)
+{
+ return AddToHash(0, a, b);
+}
+
+template<typename A, typename B, typename C>
+MOZ_WARN_UNUSED_RESULT
+inline uint32_t
+HashGeneric(A a, B b, C c)
+{
+ return AddToHash(0, a, b, c);
+}
+
+template<typename A, typename B, typename C, typename D>
+MOZ_WARN_UNUSED_RESULT
+inline uint32_t
+HashGeneric(A a, B b, C c, D d)
+{
+ return AddToHash(0, a, b, c, d);
+}
+
+template<typename A, typename B, typename C, typename D, typename E>
+MOZ_WARN_UNUSED_RESULT
+inline uint32_t
+HashGeneric(A a, B b, C c, D d, E e)
+{
+ return AddToHash(0, a, b, c, d, e);
+}
+
+namespace detail {
+
+template<typename T>
+uint32_t
+HashUntilZero(const T* str)
+{
+ uint32_t hash = 0;
+ for (T c; (c = *str); str++)
+ hash = AddToHash(hash, c);
+ return hash;
+}
+
+template<typename T>
+uint32_t
+HashKnownLength(const T* str, size_t length)
+{
+ uint32_t hash = 0;
+ for (size_t i = 0; i < length; i++)
+ hash = AddToHash(hash, str[i]);
+ return hash;
+}
+
+} /* namespace detail */
+
+/**
+ * The HashString overloads below do just what you'd expect.
+ *
+ * If you have the string's length, you might as well call the overload which
+ * includes the length. It may be marginally faster.
+ */
+MOZ_WARN_UNUSED_RESULT
+inline uint32_t
+HashString(const char* str)
+{
+ return detail::HashUntilZero(str);
+}
+
+MOZ_WARN_UNUSED_RESULT
+inline uint32_t
+HashString(const char* str, size_t length)
+{
+ return detail::HashKnownLength(str, length);
+}
+
+MOZ_WARN_UNUSED_RESULT
+inline uint32_t
+HashString(const uint16_t* str)
+{
+ return detail::HashUntilZero(str);
+}
+
+MOZ_WARN_UNUSED_RESULT
+inline uint32_t
+HashString(const uint16_t* str, size_t length)
+{
+ return detail::HashKnownLength(str, length);
+}
+
+/*
+ * On Windows, wchar_t (PRUnichar) is not the same as uint16_t, even though it's
+ * the same width!
+ */
+#ifdef WIN32
+MOZ_WARN_UNUSED_RESULT
+inline uint32_t
+HashString(const wchar_t* str)
+{
+ return detail::HashUntilZero(str);
+}
+
+MOZ_WARN_UNUSED_RESULT
+inline uint32_t
+HashString(const wchar_t* str, size_t length)
+{
+ return detail::HashKnownLength(str, length);
+}
+#endif
+
+/**
+ * Hash some number of bytes.
+ *
+ * This hash walks word-by-word, rather than byte-by-byte, so you won't get the
+ * same result out of HashBytes as you would out of HashString.
+ */
+MOZ_WARN_UNUSED_RESULT
+extern MFBT_API uint32_t
+HashBytes(const void* bytes, size_t length);
+
+} /* namespace mozilla */
+#endif /* __cplusplus */
+#endif /* mozilla_HashFunctions_h_ */
diff --git a/mfbt/Likely.h b/mfbt/Likely.h
new file mode 100644
index 0000000..6412b49
--- /dev/null
+++ b/mfbt/Likely.h
@@ -0,0 +1,22 @@
+/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+/*
+ * MOZ_LIKELY and MOZ_UNLIKELY macros to hint to the compiler how a
+ * boolean predicate should be branch-predicted.
+ */
+
+#ifndef mozilla_Likely_h_
+#define mozilla_Likely_h_
+
+#if defined(__clang__) || defined(__GNUC__)
+# define MOZ_LIKELY(x) (__builtin_expect(!!(x), 1))
+# define MOZ_UNLIKELY(x) (__builtin_expect(!!(x), 0))
+#else
+# define MOZ_LIKELY(x) (!!(x))
+# define MOZ_UNLIKELY(x) (!!(x))
+#endif
+
+#endif /* mozilla_Likely_h_ */
diff --git a/mfbt/LinkedList.h b/mfbt/LinkedList.h
new file mode 100644
index 0000000..5cfd60e
--- /dev/null
+++ b/mfbt/LinkedList.h
@@ -0,0 +1,429 @@
+/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+/* A type-safe doubly-linked list class. */
+
+/*
+ * The classes LinkedList<T> and LinkedListElement<T> together form a
+ * convenient, type-safe doubly-linked list implementation.
+ *
+ * The class T which will be inserted into the linked list must inherit from
+ * LinkedListElement<T>. A given object may be in only one linked list at a
+ * time.
+ *
+ * A LinkedListElement automatically removes itself from the list upon
+ * destruction, and a LinkedList will fatally assert in debug builds if it's
+ * non-empty when it's destructed.
+ *
+ * For example, you might use LinkedList in a simple observer list class as
+ * follows.
+ *
+ * class Observer : public LinkedListElement<Observer>
+ * {
+ * public:
+ * void observe(char* topic) { ... }
+ * };
+ *
+ * class ObserverContainer
+ * {
+ * private:
+ * LinkedList<Observer> list;
+ *
+ * public:
+ * void addObserver(Observer* observer) {
+ * // Will assert if |observer| is part of another list.
+ * list.insertBack(observer);
+ * }
+ *
+ * void removeObserver(Observer* observer) {
+ * // Will assert if |observer| is not part of some list.
+ * observer.remove();
+ * // Or, will assert if |observer| is not part of |list| specifically.
+ * // observer.removeFrom(list);
+ * }
+ *
+ * void notifyObservers(char* topic) {
+ * for (Observer* o = list.getFirst(); o != NULL; o = o->getNext())
+ * o->Observe(topic);
+ * }
+ * };
+ *
+ */
+
+#ifndef mozilla_LinkedList_h_
+#define mozilla_LinkedList_h_
+
+#include "mozilla/Assertions.h"
+#include "mozilla/Attributes.h"
+
+#ifdef __cplusplus
+
+namespace mozilla {
+
+template<typename T>
+class LinkedList;
+
+template<typename T>
+class LinkedListElement
+{
+ /*
+ * It's convenient that we return NULL when getNext() or getPrevious() hits
+ * the end of the list, but doing so costs an extra word of storage in each
+ * linked list node (to keep track of whether |this| is the sentinel node)
+ * and a branch on this value in getNext/getPrevious.
+ *
+ * We could get rid of the extra word of storage by shoving the "is
+ * sentinel" bit into one of the pointers, although this would, of course,
+ * have performance implications of its own.
+ *
+ * But the goal here isn't to win an award for the fastest or slimmest
+ * linked list; rather, we want a *convenient* linked list. So we won't
+ * waste time guessing which micro-optimization strategy is best.
+ *
+ *
+ * Speaking of unnecessary work, it's worth addressing here why we wrote
+ * mozilla::LinkedList in the first place, instead of using stl::list.
+ *
+ * The key difference between mozilla::LinkedList and stl::list is that
+ * mozilla::LinkedList stores the prev/next pointers in the object itself,
+ * while stl::list stores the prev/next pointers in a list element which
+ * itself points to the object being stored.
+ *
+ * mozilla::LinkedList's approach makes it harder to store an object in more
+ * than one list. But the upside is that you can call next() / prev() /
+ * remove() directly on the object. With stl::list, you'd need to store a
+ * pointer to its iterator in the object in order to accomplish this. Not
+ * only would this waste space, but you'd have to remember to update that
+ * pointer every time you added or removed the object from a list.
+ *
+ * In-place, constant-time removal is a killer feature of doubly-linked
+ * lists, and supporting this painlessly was a key design criterion.
+ */
+
+ private:
+ LinkedListElement* next;
+ LinkedListElement* prev;
+ const bool isSentinel;
+
+ LinkedListElement* thisDuringConstruction() { return this; }
+
+ public:
+ LinkedListElement()
+ : next(thisDuringConstruction()),
+ prev(thisDuringConstruction()),
+ isSentinel(false)
+ { }
+
+ ~LinkedListElement() {
+ if (!isSentinel && isInList())
+ remove();
+ }
+
+ /*
+ * Get the next element in the list, or NULL if this is the last element in
+ * the list.
+ */
+ T* getNext() {
+ return next->asT();
+ }
+ const T* getNext() const {
+ return next->asT();
+ }
+
+ /*
+ * Get the previous element in the list, or NULL if this is the first element
+ * in the list.
+ */
+ T* getPrevious() {
+ return prev->asT();
+ }
+ const T* getPrevious() const {
+ return prev->asT();
+ }
+
+ /*
+ * Insert elem after this element in the list. |this| must be part of a
+ * linked list when you call setNext(); otherwise, this method will assert.
+ */
+ void setNext(T* elem) {
+ MOZ_ASSERT(isInList());
+ setNextUnsafe(elem);
+ }
+
+ /*
+ * Insert elem before this element in the list. |this| must be part of a
+ * linked list when you call setPrevious(); otherwise, this method will
+ * assert.
+ */
+ void setPrevious(T* elem) {
+ MOZ_ASSERT(isInList());
+ setPreviousUnsafe(elem);
+ }
+
+ /*
+ * Remove this element from the list which contains it. If this element is
+ * not currently part of a linked list, this method asserts.
+ */
+ void remove() {
+ MOZ_ASSERT(isInList());
+
+ prev->next = next;
+ next->prev = prev;
+ next = this;
+ prev = this;
+ }
+
+ /*
+ * Identical to remove(), but also asserts in debug builds that this element
+ * is in list.
+ */
+ void removeFrom(const LinkedList<T>& list) {
+ list.assertContains(asT());
+ remove();
+ }
+
+ /*
+ * Return true if |this| part is of a linked list, and false otherwise.
+ */
+ bool isInList() const {
+ MOZ_ASSERT((next == this) == (prev == this));
+ return next != this;
+ }
+
+ private:
+ friend class LinkedList<T>;
+
+ enum NodeKind {
+ NODE_KIND_NORMAL,
+ NODE_KIND_SENTINEL
+ };
+
+ LinkedListElement(NodeKind nodeKind)
+ : next(thisDuringConstruction()),
+ prev(thisDuringConstruction()),
+ isSentinel(nodeKind == NODE_KIND_SENTINEL)
+ { }
+
+ /*
+ * Return |this| cast to T* if we're a normal node, or return NULL if we're
+ * a sentinel node.
+ */
+ T* asT() {
+ if (isSentinel)
+ return NULL;
+
+ return static_cast<T*>(this);
+ }
+ const T* asT() const {
+ if (isSentinel)
+ return NULL;
+
+ return static_cast<const T*>(this);
+ }
+
+ /*
+ * Insert elem after this element, but don't check that this element is in
+ * the list. This is called by LinkedList::insertFront().
+ */
+ void setNextUnsafe(T* elem) {
+ LinkedListElement *listElem = static_cast<LinkedListElement*>(elem);
+ MOZ_ASSERT(!listElem->isInList());
+
+ listElem->next = this->next;
+ listElem->prev = this;
+ this->next->prev = listElem;
+ this->next = listElem;
+ }
+
+ /*
+ * Insert elem before this element, but don't check that this element is in
+ * the list. This is called by LinkedList::insertBack().
+ */
+ void setPreviousUnsafe(T* elem) {
+ LinkedListElement<T>* listElem = static_cast<LinkedListElement<T>*>(elem);
+ MOZ_ASSERT(!listElem->isInList());
+
+ listElem->next = this;
+ listElem->prev = this->prev;
+ this->prev->next = listElem;
+ this->prev = listElem;
+ }
+
+ private:
+ LinkedListElement& operator=(const LinkedList<T>& other) MOZ_DELETE;
+ LinkedListElement(const LinkedList<T>& other) MOZ_DELETE;
+};
+
+template<typename T>
+class LinkedList
+{
+ private:
+ LinkedListElement<T> sentinel;
+
+ public:
+ LinkedList() : sentinel(LinkedListElement<T>::NODE_KIND_SENTINEL) { }
+
+ ~LinkedList() {
+ MOZ_ASSERT(isEmpty());
+ }
+
+ /*
+ * Add elem to the front of the list.
+ */
+ void insertFront(T* elem) {
+ /* Bypass setNext()'s this->isInList() assertion. */
+ sentinel.setNextUnsafe(elem);
+ }
+
+ /*
+ * Add elem to the back of the list.
+ */
+ void insertBack(T* elem) {
+ sentinel.setPreviousUnsafe(elem);
+ }
+
+ /*
+ * Get the first element of the list, or NULL if the list is empty.
+ */
+ T* getFirst() {
+ return sentinel.getNext();
+ }
+ const T* getFirst() const {
+ return sentinel.getNext();
+ }
+
+ /*
+ * Get the last element of the list, or NULL if the list is empty.
+ */
+ T* getLast() {
+ return sentinel.getPrevious();
+ }
+ const T* getLast() const {
+ return sentinel.getPrevious();
+ }
+
+ /*
+ * Get and remove the first element of the list. If the list is empty,
+ * return NULL.
+ */
+ T* popFirst() {
+ T* ret = sentinel.getNext();
+ if (ret)
+ static_cast<LinkedListElement<T>*>(ret)->remove();
+ return ret;
+ }
+
+ /*
+ * Get and remove the last element of the list. If the list is empty,
+ * return NULL.
+ */
+ T* popLast() {
+ T* ret = sentinel.getPrevious();
+ if (ret)
+ static_cast<LinkedListElement<T>*>(ret)->remove();
+ return ret;
+ }
+
+ /*
+ * Return true if the list is empty, or false otherwise.
+ */
+ bool isEmpty() const {
+ return !sentinel.isInList();
+ }
+
+ /*
+ * Remove all the elements from the list.
+ *
+ * This runs in time linear to the list's length, because we have to mark
+ * each element as not in the list.
+ */
+ void clear() {
+ while (popFirst())
+ continue;
+ }
+
+ /*
+ * In a debug build, make sure that the list is sane (no cycles, consistent
+ * next/prev pointers, only one sentinel). Has no effect in release builds.
+ */
+ void debugAssertIsSane() const {
+#ifdef DEBUG
+ const LinkedListElement<T>* slow;
+ const LinkedListElement<T>* fast1;
+ const LinkedListElement<T>* fast2;
+
+ /*
+ * Check for cycles in the forward singly-linked list using the
+ * tortoise/hare algorithm.
+ */
+ for (slow = sentinel.next,
+ fast1 = sentinel.next->next,
+ fast2 = sentinel.next->next->next;
+ slow != sentinel && fast1 != sentinel && fast2 != sentinel;
+ slow = slow->next, fast1 = fast2->next, fast2 = fast1->next)
+ {
+ MOZ_ASSERT(slow != fast1);
+ MOZ_ASSERT(slow != fast2);
+ }
+
+ /* Check for cycles in the backward singly-linked list. */
+ for (slow = sentinel.prev,
+ fast1 = sentinel.prev->prev,
+ fast2 = sentinel.prev->prev->prev;
+ slow != sentinel && fast1 != sentinel && fast2 != sentinel;
+ slow = slow->prev, fast1 = fast2->prev, fast2 = fast1->prev)
+ {
+ MOZ_ASSERT(slow != fast1);
+ MOZ_ASSERT(slow != fast2);
+ }
+
+ /*
+ * Check that |sentinel| is the only node in the list with
+ * isSentinel == true.
+ */
+ for (const LinkedListElement<T>* elem = sentinel.next;
+ elem != sentinel;
+ elem = elem->next)
+ {
+ MOZ_ASSERT(!elem->isSentinel);
+ }
+
+ /* Check that the next/prev pointers match up. */
+ const LinkedListElement<T>* prev = sentinel;
+ const LinkedListElement<T>* cur = sentinel.next;
+ do {
+ MOZ_ASSERT(cur->prev == prev);
+ MOZ_ASSERT(prev->next == cur);
+
+ prev = cur;
+ cur = cur->next;
+ } while (cur != sentinel);
+#endif /* ifdef DEBUG */
+ }
+
+ private:
+ friend class LinkedListElement<T>;
+
+ void assertContains(const T* t) const {
+#ifdef DEBUG
+ for (const T* elem = getFirst();
+ elem;
+ elem = elem->getNext())
+ {
+ if (elem == t)
+ return;
+ }
+ MOZ_NOT_REACHED("element wasn't found in this list!");
+#endif
+ }
+
+ LinkedList& operator=(const LinkedList<T>& other) MOZ_DELETE;
+ LinkedList(const LinkedList<T>& other) MOZ_DELETE;
+};
+
+} /* namespace mozilla */
+
+#endif /* ifdef __cplusplus */
+#endif /* ifdef mozilla_LinkedList_h_ */
diff --git a/mfbt/MSStdInt.h b/mfbt/MSStdInt.h
new file mode 100644
index 0000000..0447f2f
--- /dev/null
+++ b/mfbt/MSStdInt.h
@@ -0,0 +1,247 @@
+// ISO C9x compliant stdint.h for Microsoft Visual Studio
+// Based on ISO/IEC 9899:TC2 Committee draft (May 6, 2005) WG14/N1124
+//
+// Copyright (c) 2006-2008 Alexander Chemeris
+//
+// 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.
+//
+// 3. The name of the author may be used to endorse or promote products
+// derived from this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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.
+//
+///////////////////////////////////////////////////////////////////////////////
+
+#ifndef _MSC_VER // [
+#error "Use this header only with Microsoft Visual C++ compilers!"
+#endif // _MSC_VER ]
+
+#ifndef _MSC_STDINT_H_ // [
+#define _MSC_STDINT_H_
+
+#if _MSC_VER > 1000
+#pragma once
+#endif
+
+#include <limits.h>
+
+// For Visual Studio 6 in C++ mode and for many Visual Studio versions when
+// compiling for ARM we should wrap <wchar.h> include with 'extern "C++" {}'
+// or compiler give many errors like this:
+// error C2733: second C linkage of overloaded function 'wmemchr' not allowed
+#ifdef __cplusplus
+extern "C" {
+#endif
+# include <wchar.h>
+#ifdef __cplusplus
+}
+#endif
+
+// Define _W64 macros to mark types changing their size, like intptr_t.
+#ifndef _W64
+# if !defined(__midl) && (defined(_X86_) || defined(_M_IX86)) && _MSC_VER >= 1300
+# define _W64 __w64
+# else
+# define _W64
+# endif
+#endif
+
+
+// 7.18.1 Integer types
+
+// 7.18.1.1 Exact-width integer types
+
+// Visual Studio 6 and Embedded Visual C++ 4 doesn't
+// realize that, e.g. char has the same size as __int8
+// so we give up on __intX for them.
+#if (_MSC_VER < 1300)
+ typedef signed char int8_t;
+ typedef signed short int16_t;
+ typedef signed int int32_t;
+ typedef unsigned char uint8_t;
+ typedef unsigned short uint16_t;
+ typedef unsigned int uint32_t;
+#else
+ typedef signed __int8 int8_t;
+ typedef signed __int16 int16_t;
+ typedef signed __int32 int32_t;
+ typedef unsigned __int8 uint8_t;
+ typedef unsigned __int16 uint16_t;
+ typedef unsigned __int32 uint32_t;
+#endif
+typedef signed __int64 int64_t;
+typedef unsigned __int64 uint64_t;
+
+
+// 7.18.1.2 Minimum-width integer types
+typedef int8_t int_least8_t;
+typedef int16_t int_least16_t;
+typedef int32_t int_least32_t;
+typedef int64_t int_least64_t;
+typedef uint8_t uint_least8_t;
+typedef uint16_t uint_least16_t;
+typedef uint32_t uint_least32_t;
+typedef uint64_t uint_least64_t;
+
+// 7.18.1.3 Fastest minimum-width integer types
+typedef int8_t int_fast8_t;
+typedef int32_t int_fast16_t;
+typedef int32_t int_fast32_t;
+typedef int64_t int_fast64_t;
+typedef uint8_t uint_fast8_t;
+typedef uint32_t uint_fast16_t;
+typedef uint32_t uint_fast32_t;
+typedef uint64_t uint_fast64_t;
+
+// 7.18.1.4 Integer types capable of holding object pointers
+#ifdef _WIN64 // [
+ typedef signed __int64 intptr_t;
+ typedef unsigned __int64 uintptr_t;
+#else // _WIN64 ][
+ typedef _W64 signed int intptr_t;
+ typedef _W64 unsigned int uintptr_t;
+#endif // _WIN64 ]
+
+// 7.18.1.5 Greatest-width integer types
+typedef int64_t intmax_t;
+typedef uint64_t uintmax_t;
+
+
+// 7.18.2 Limits of specified-width integer types
+
+#if !defined(__cplusplus) || defined(__STDC_LIMIT_MACROS) // [ See footnote 220 at page 257 and footnote 221 at page 259
+
+// 7.18.2.1 Limits of exact-width integer types
+#define INT8_MIN ((int8_t)_I8_MIN)
+#define INT8_MAX _I8_MAX
+#define INT16_MIN ((int16_t)_I16_MIN)
+#define INT16_MAX _I16_MAX
+#define INT32_MIN ((int32_t)_I32_MIN)
+#define INT32_MAX _I32_MAX
+#define INT64_MIN ((int64_t)_I64_MIN)
+#define INT64_MAX _I64_MAX
+#define UINT8_MAX _UI8_MAX
+#define UINT16_MAX _UI16_MAX
+#define UINT32_MAX _UI32_MAX
+#define UINT64_MAX _UI64_MAX
+
+// 7.18.2.2 Limits of minimum-width integer types
+#define INT_LEAST8_MIN INT8_MIN
+#define INT_LEAST8_MAX INT8_MAX
+#define INT_LEAST16_MIN INT16_MIN
+#define INT_LEAST16_MAX INT16_MAX
+#define INT_LEAST32_MIN INT32_MIN
+#define INT_LEAST32_MAX INT32_MAX
+#define INT_LEAST64_MIN INT64_MIN
+#define INT_LEAST64_MAX INT64_MAX
+#define UINT_LEAST8_MAX UINT8_MAX
+#define UINT_LEAST16_MAX UINT16_MAX
+#define UINT_LEAST32_MAX UINT32_MAX
+#define UINT_LEAST64_MAX UINT64_MAX
+
+// 7.18.2.3 Limits of fastest minimum-width integer types
+#define INT_FAST8_MIN INT8_MIN
+#define INT_FAST8_MAX INT8_MAX
+#define INT_FAST16_MIN INT16_MIN
+#define INT_FAST16_MAX INT16_MAX
+#define INT_FAST32_MIN INT32_MIN
+#define INT_FAST32_MAX INT32_MAX
+#define INT_FAST64_MIN INT64_MIN
+#define INT_FAST64_MAX INT64_MAX
+#define UINT_FAST8_MAX UINT8_MAX
+#define UINT_FAST16_MAX UINT16_MAX
+#define UINT_FAST32_MAX UINT32_MAX
+#define UINT_FAST64_MAX UINT64_MAX
+
+// 7.18.2.4 Limits of integer types capable of holding object pointers
+#ifdef _WIN64 // [
+# define INTPTR_MIN INT64_MIN
+# define INTPTR_MAX INT64_MAX
+# define UINTPTR_MAX UINT64_MAX
+#else // _WIN64 ][
+# define INTPTR_MIN INT32_MIN
+# define INTPTR_MAX INT32_MAX
+# define UINTPTR_MAX UINT32_MAX
+#endif // _WIN64 ]
+
+// 7.18.2.5 Limits of greatest-width integer types
+#define INTMAX_MIN INT64_MIN
+#define INTMAX_MAX INT64_MAX
+#define UINTMAX_MAX UINT64_MAX
+
+// 7.18.3 Limits of other integer types
+
+#ifdef _WIN64 // [
+# define PTRDIFF_MIN _I64_MIN
+# define PTRDIFF_MAX _I64_MAX
+#else // _WIN64 ][
+# define PTRDIFF_MIN _I32_MIN
+# define PTRDIFF_MAX _I32_MAX
+#endif // _WIN64 ]
+
+#define SIG_ATOMIC_MIN INT_MIN
+#define SIG_ATOMIC_MAX INT_MAX
+
+#ifndef SIZE_MAX // [
+# ifdef _WIN64 // [
+# define SIZE_MAX _UI64_MAX
+# else // _WIN64 ][
+# define SIZE_MAX _UI32_MAX
+# endif // _WIN64 ]
+#endif // SIZE_MAX ]
+
+// WCHAR_MIN and WCHAR_MAX are also defined in <wchar.h>
+#ifndef WCHAR_MIN // [
+# define WCHAR_MIN 0
+#endif // WCHAR_MIN ]
+#ifndef WCHAR_MAX // [
+# define WCHAR_MAX _UI16_MAX
+#endif // WCHAR_MAX ]
+
+#define WINT_MIN 0
+#define WINT_MAX _UI16_MAX
+
+#endif // __STDC_LIMIT_MACROS ]
+
+
+// 7.18.4 Limits of other integer types
+
+#if !defined(__cplusplus) || defined(__STDC_CONSTANT_MACROS) // [ See footnote 224 at page 260
+
+// 7.18.4.1 Macros for minimum-width integer constants
+
+#define INT8_C(val) val##i8
+#define INT16_C(val) val##i16
+#define INT32_C(val) val##i32
+#define INT64_C(val) val##i64
+
+#define UINT8_C(val) val##ui8
+#define UINT16_C(val) val##ui16
+#define UINT32_C(val) val##ui32
+#define UINT64_C(val) val##ui64
+
+// 7.18.4.2 Macros for greatest-width integer constants
+#define INTMAX_C INT64_C
+#define UINTMAX_C UINT64_C
+
+#endif // __STDC_CONSTANT_MACROS ]
+
+
+#endif // _MSC_STDINT_H_ ]
diff --git a/mfbt/Makefile.in b/mfbt/Makefile.in
new file mode 100644
index 0000000..c74f8d2
--- /dev/null
+++ b/mfbt/Makefile.in
@@ -0,0 +1,28 @@
+# This Source Code Form is subject to the terms of the Mozilla Public
+# License, v. 2.0. If a copy of the MPL was not distributed with this
+# file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+DEPTH = @DEPTH@
+topsrcdir = @top_srcdir@
+srcdir = @srcdir@
+VPATH = @srcdir@
+
+include $(DEPTH)/config/autoconf.mk
+
+FORCE_STATIC_LIB = 1
+STL_FLAGS =
+
+# exported_headers.mk defines the headers exported by mfbt. It is included by
+# mfbt itself and by the JS engine, which, when built standalone, must do the
+# work to install mfbt's exported headers itself.
+include $(srcdir)/exported_headers.mk
+
+# sources.mk defines the source files built for mfbt. It is included by mfbt
+# itself and by the JS engine, which, when built standalone, must do the work
+# to build mfbt sources itself.
+MFBT_ROOT = $(srcdir)
+include $(MFBT_ROOT)/sources.mk
+
+DEFINES += -DIMPL_MFBT
+
+include $(topsrcdir)/config/rules.mk
diff --git a/mfbt/MathAlgorithms.h b/mfbt/MathAlgorithms.h
new file mode 100644
index 0000000..0a47810
--- /dev/null
+++ b/mfbt/MathAlgorithms.h
@@ -0,0 +1,147 @@
+/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+/* mfbt maths algorithms. */
+
+#ifndef mozilla_MathAlgorithms_h_
+#define mozilla_MathAlgorithms_h_
+
+#include "mozilla/Assertions.h"
+#include "mozilla/StandardInteger.h"
+#include "mozilla/TypeTraits.h"
+
+#include <cmath>
+#include <limits.h>
+
+namespace mozilla {
+
+// Greatest Common Divisor
+template<typename IntegerType>
+MOZ_ALWAYS_INLINE IntegerType
+EuclidGCD(IntegerType a, IntegerType b)
+{
+ // Euclid's algorithm; O(N) in the worst case. (There are better
+ // ways, but we don't need them for the current use of this algo.)
+ MOZ_ASSERT(a > 0);
+ MOZ_ASSERT(b > 0);
+
+ while (a != b) {
+ if (a > b) {
+ a = a - b;
+ } else {
+ b = b - a;
+ }
+ }
+
+ return a;
+}
+
+// Least Common Multiple
+template<typename IntegerType>
+MOZ_ALWAYS_INLINE IntegerType
+EuclidLCM(IntegerType a, IntegerType b)
+{
+ // Divide first to reduce overflow risk.
+ return (a / EuclidGCD(a, b)) * b;
+}
+
+namespace detail {
+
+template<typename T>
+struct AllowDeprecatedAbsFixed : FalseType {};
+
+template<> struct AllowDeprecatedAbsFixed<int32_t> : TrueType {};
+template<> struct AllowDeprecatedAbsFixed<int64_t> : TrueType {};
+
+template<typename T>
+struct AllowDeprecatedAbs : AllowDeprecatedAbsFixed<T> {};
+
+template<> struct AllowDeprecatedAbs<int> : TrueType {};
+template<> struct AllowDeprecatedAbs<long> : TrueType {};
+
+} // namespace detail
+
+// DO NOT USE DeprecatedAbs. It exists only until its callers can be converted
+// to Abs below, and it will be removed when all callers have been changed.
+template<typename T>
+inline typename mozilla::EnableIf<detail::AllowDeprecatedAbs<T>::value, T>::Type
+DeprecatedAbs(const T t)
+{
+ // The absolute value of the smallest possible value of a signed-integer type
+ // won't fit in that type (on twos-complement systems -- and we're blithely
+ // assuming we're on such systems, for the non-<stdint.h> types listed above),
+ // so assert that the input isn't that value.
+ //
+ // This is the case if: the value is non-negative; or if adding one (giving a
+ // value in the range [-maxvalue, 0]), then negating (giving a value in the
+ // range [0, maxvalue]), doesn't produce maxvalue (because in twos-complement,
+ // (minvalue + 1) == -maxvalue).
+ MOZ_ASSERT(t >= 0 ||
+ -(t + 1) != T((1ULL << (CHAR_BIT * sizeof(T) - 1)) - 1),
+ "You can't negate the smallest possible negative integer!");
+ return t >= 0 ? t : -t;
+}
+
+namespace detail {
+
+// For now mozilla::Abs only takes intN_T, the signed natural types, and
+// float/double/long double. Feel free to add overloads for other standard,
+// signed types if you need them.
+
+template<typename T>
+struct AbsReturnTypeFixed;
+
+template<> struct AbsReturnTypeFixed<int8_t> { typedef uint8_t Type; };
+template<> struct AbsReturnTypeFixed<int16_t> { typedef uint16_t Type; };
+template<> struct AbsReturnTypeFixed<int32_t> { typedef uint32_t Type; };
+template<> struct AbsReturnTypeFixed<int64_t> { typedef uint64_t Type; };
+
+template<typename T>
+struct AbsReturnType : AbsReturnTypeFixed<T> {};
+
+template<> struct AbsReturnType<char> : EnableIf<char(-1) < char(0), unsigned char> {};
+template<> struct AbsReturnType<signed char> { typedef unsigned char Type; };
+template<> struct AbsReturnType<short> { typedef unsigned short Type; };
+template<> struct AbsReturnType<int> { typedef unsigned int Type; };
+template<> struct AbsReturnType<long> { typedef unsigned long Type; };
+template<> struct AbsReturnType<long long> { typedef unsigned long long Type; };
+template<> struct AbsReturnType<float> { typedef float Type; };
+template<> struct AbsReturnType<double> { typedef double Type; };
+template<> struct AbsReturnType<long double> { typedef long double Type; };
+
+} // namespace detail
+
+template<typename T>
+inline typename detail::AbsReturnType<T>::Type
+Abs(const T t)
+{
+ typedef typename detail::AbsReturnType<T>::Type ReturnType;
+ return t >= 0 ? ReturnType(t) : ~ReturnType(t) + 1;
+}
+
+template<>
+inline float
+Abs<float>(const float f)
+{
+ return std::fabs(f);
+}
+
+template<>
+inline double
+Abs<double>(const double d)
+{
+ return std::fabs(d);
+}
+
+template<>
+inline long double
+Abs<long double>(const long double d)
+{
+ return std::fabs(d);
+}
+
+} /* namespace mozilla */
+
+#endif /* mozilla_MathAlgorithms_h_ */
diff --git a/mfbt/MemoryChecking.h b/mfbt/MemoryChecking.h
new file mode 100644
index 0000000..3287e57
--- /dev/null
+++ b/mfbt/MemoryChecking.h
@@ -0,0 +1,71 @@
+/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+/*
+ * Provides a common interface to the ASan (AddressSanitizer) and Valgrind
+ * functions used to mark memory in certain ways. In detail, the following
+ * three macros are provided:
+ *
+ * MOZ_MAKE_MEM_NOACCESS - Mark memory as unsafe to access (e.g. freed)
+ * MOZ_MAKE_MEM_UNDEFINED - Mark memory as accessible, with content undefined
+ * MOZ_MAKE_MEM_DEFINED - Mark memory as accessible, with content defined
+ *
+ * With Valgrind in use, these directly map to the three respective Valgrind
+ * macros. With ASan in use, the NOACCESS macro maps to poisoning the memory,
+ * while the UNDEFINED/DEFINED macros unpoison memory.
+ *
+ * With no memory checker available, all macros expand to the empty statement.
+ */
+
+#ifndef mozilla_MemoryChecking_h_
+#define mozilla_MemoryChecking_h_
+
+#if defined(MOZ_VALGRIND)
+#include "valgrind/memcheck.h"
+#endif
+
+#if defined(MOZ_ASAN) || defined(MOZ_VALGRIND)
+#define MOZ_HAVE_MEM_CHECKS 1
+#endif
+
+#if defined(MOZ_ASAN)
+#include <stddef.h>
+
+extern "C" {
+ /* These definitions are usually provided through the
+ * sanitizer/asan_interface.h header installed by ASan.
+ */
+ void __asan_poison_memory_region(void const volatile *addr, size_t size)
+ __attribute__((visibility("default")));
+ void __asan_unpoison_memory_region(void const volatile *addr, size_t size)
+ __attribute__((visibility("default")));
+
+#define MOZ_MAKE_MEM_NOACCESS(addr, size) \
+ __asan_poison_memory_region((addr), (size))
+
+#define MOZ_MAKE_MEM_UNDEFINED(addr, size) \
+ __asan_unpoison_memory_region((addr), (size))
+
+#define MOZ_MAKE_MEM_DEFINED(addr, size) \
+ __asan_unpoison_memory_region((addr), (size))
+}
+#elif defined(MOZ_VALGRIND)
+#define MOZ_MAKE_MEM_NOACCESS(addr, size) \
+ VALGRIND_MAKE_MEM_NOACCESS((addr), (size))
+
+#define MOZ_MAKE_MEM_UNDEFINED(addr, size) \
+ VALGRIND_MAKE_MEM_UNDEFINED((addr), (size))
+
+#define MOZ_MAKE_MEM_DEFINED(addr, size) \
+ VALGRIND_MAKE_MEM_DEFINED((addr), (size))
+#else
+
+#define MOZ_MAKE_MEM_NOACCESS(addr, size) do {} while(0)
+#define MOZ_MAKE_MEM_UNDEFINED(addr, size) do {} while(0)
+#define MOZ_MAKE_MEM_DEFINED(addr, size) do {} while(0)
+
+#endif
+
+#endif /* mozilla_MemoryChecking_h_ */
diff --git a/mfbt/NullPtr.h b/mfbt/NullPtr.h
new file mode 100644
index 0000000..7dcb03d
--- /dev/null
+++ b/mfbt/NullPtr.h
@@ -0,0 +1,48 @@
+/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+/*
+ * Implements a workaround for compilers which do not support the C++11 nullptr
+ * constant.
+ */
+
+#ifndef mozilla_NullPtr_h_
+#define mozilla_NullPtr_h_
+
+#include "mozilla/Compiler.h"
+
+#if defined(__clang__)
+# ifndef __has_extension
+# define __has_extension __has_feature
+# endif
+# if __has_extension(cxx_nullptr)
+# define MOZ_HAVE_CXX11_NULLPTR
+# endif
+#elif defined(__GNUC__)
+# if defined(__GXX_EXPERIMENTAL_CXX0X__) || __cplusplus >= 201103L
+# if MOZ_GCC_VERSION_AT_LEAST(4, 6, 0)
+# define MOZ_HAVE_CXX11_NULLPTR
+# endif
+# endif
+#elif _MSC_VER >= 1600
+# define MOZ_HAVE_CXX11_NULLPTR
+#endif
+
+/**
+ * Use C++11 nullptr if available; otherwise use __null for gcc, or a 0 literal
+ * with the correct size to match the size of a pointer on a given platform.
+ */
+
+#ifndef MOZ_HAVE_CXX11_NULLPTR
+# if defined(__GNUC__)
+# define nullptr __null
+# elif defined(_WIN64)
+# define nullptr 0LL
+# else
+# define nullptr 0L
+# endif
+#endif
+
+#endif /* mozilla_NullPtr_h_ */
diff --git a/mfbt/PodOperations.h b/mfbt/PodOperations.h
new file mode 100644
index 0000000..6c6af27
--- /dev/null
+++ b/mfbt/PodOperations.h
@@ -0,0 +1,159 @@
+/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+/*
+ * Operations for zeroing POD types, arrays, and so on.
+ *
+ * These operations are preferable to memset, memcmp, and the like because they
+ * don't require remembering to multiply by sizeof(T), array lengths, and so on
+ * everywhere.
+ */
+
+#ifndef mozilla_PodOperations_h
+#define mozilla_PodOperations_h
+
+#include "mozilla/Attributes.h"
+#include "mozilla/Util.h"
+
+#include <string.h>
+
+namespace mozilla {
+
+/** Set the contents of |t| to 0. */
+template<typename T>
+static void
+PodZero(T* t)
+{
+ memset(t, 0, sizeof(T));
+}
+
+/** Set the contents of |nelem| elements starting at |t| to 0. */
+template<typename T>
+static void
+PodZero(T* t, size_t nelem)
+{
+ /*
+ * This function is often called with 'nelem' small; we use an inline loop
+ * instead of calling 'memset' with a non-constant length. The compiler
+ * should inline the memset call with constant size, though.
+ */
+ for (T* end = t + nelem; t < end; t++)
+ memset(t, 0, sizeof(T));
+}
+
+/*
+ * Arrays implicitly convert to pointers to their first element, which is
+ * dangerous when combined with the above PodZero definitions. Adding an
+ * overload for arrays is ambiguous, so we need another identifier. The
+ * ambiguous overload is left to catch mistaken uses of PodZero; if you get a
+ * compile error involving PodZero and array types, use PodArrayZero instead.
+ */
+template<typename T, size_t N>
+static void PodZero(T (&t)[N]) MOZ_DELETE;
+template<typename T, size_t N>
+static void PodZero(T (&t)[N], size_t nelem) MOZ_DELETE;
+
+/** Set the contents of the array |t| to zero. */
+template <class T, size_t N>
+static void
+PodArrayZero(T (&t)[N])
+{
+ memset(t, 0, N * sizeof(T));
+}
+
+/**
+ * Assign |*src| to |*dst|. The locations must not be the same and must not
+ * overlap.
+ */
+template<typename T>
+static void
+PodAssign(T* dst, const T* src)
+{
+ MOZ_ASSERT(dst != src);
+ MOZ_ASSERT_IF(src < dst, PointerRangeSize(src, static_cast<const T*>(dst)) >= 1);
+ MOZ_ASSERT_IF(dst < src, PointerRangeSize(static_cast<const T*>(dst), src) >= 1);
+ memcpy(reinterpret_cast<char*>(dst), reinterpret_cast<const char*>(src), sizeof(T));
+}
+
+/**
+ * Copy |nelem| T elements from |src| to |dst|. The two memory ranges must not
+ * overlap!
+ */
+template<typename T>
+MOZ_ALWAYS_INLINE static void
+PodCopy(T* dst, const T* src, size_t nelem)
+{
+ MOZ_ASSERT(dst != src);
+ MOZ_ASSERT_IF(src < dst, PointerRangeSize(src, static_cast<const T*>(dst)) >= nelem);
+ MOZ_ASSERT_IF(dst < src, PointerRangeSize(static_cast<const T*>(dst), src) >= nelem);
+
+ if (nelem < 128) {
+ /*
+ * Avoid using operator= in this loop, as it may have been
+ * intentionally deleted by the POD type.
+ */
+ for (const T* srcend = src + nelem; src < srcend; src++, dst++)
+ PodAssign(dst, src);
+ } else {
+ memcpy(dst, src, nelem * sizeof(T));
+ }
+}
+
+template<typename T>
+MOZ_ALWAYS_INLINE static void
+PodCopy(volatile T* dst, const volatile T* src, size_t nelem)
+{
+ MOZ_ASSERT(dst != src);
+ MOZ_ASSERT_IF(src < dst,
+ PointerRangeSize(src, static_cast<const volatile T*>(dst)) >= nelem);
+ MOZ_ASSERT_IF(dst < src,
+ PointerRangeSize(static_cast<const volatile T*>(dst), src) >= nelem);
+
+ /*
+ * Volatile |dst| requires extra work, because it's undefined behavior to
+ * modify volatile objects using the mem* functions. Just write out the
+ * loops manually, using operator= rather than memcpy for the same reason,
+ * and let the compiler optimize to the extent it can.
+ */
+ for (const volatile T* srcend = src + nelem; src < srcend; src++, dst++)
+ *dst = *src;
+}
+
+/*
+ * Copy the contents of the array |src| into the array |dst|, both of size N.
+ * The arrays must not overlap!
+ */
+template <class T, size_t N>
+static void
+PodArrayCopy(T (&dst)[N], const T (&src)[N])
+{
+ PodCopy(dst, src, N);
+}
+
+/**
+ * Determine whether the |len| elements at |one| are memory-identical to the
+ * |len| elements at |two|.
+ */
+template<typename T>
+MOZ_ALWAYS_INLINE static bool
+PodEqual(const T* one, const T* two, size_t len)
+{
+ if (len < 128) {
+ const T* p1end = one + len;
+ const T* p1 = one;
+ const T* p2 = two;
+ for (; p1 < p1end; p1++, p2++) {
+ if (*p1 != *p2)
+ return false;
+ }
+ return true;
+ }
+
+ return !memcmp(one, two, len * sizeof(T));
+}
+
+} // namespace mozilla
+
+#endif // mozilla_PodOperations_h_
diff --git a/mfbt/Poison.cpp b/mfbt/Poison.cpp
new file mode 100644
index 0000000..ade9a22
--- /dev/null
+++ b/mfbt/Poison.cpp
@@ -0,0 +1,206 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+/*
+ * A poison value that can be used to fill a memory space with
+ * an address that leads to a safe crash when dereferenced.
+ */
+
+#include "mozilla/Poison.h"
+
+#include "mozilla/Assertions.h"
+#ifdef _WIN32
+# include <windows.h>
+#elif !defined(__OS2__)
+# include <unistd.h>
+# include <sys/mman.h>
+# ifndef MAP_ANON
+# ifdef MAP_ANONYMOUS
+# define MAP_ANON MAP_ANONYMOUS
+# else
+# error "Don't know how to get anonymous memory"
+# endif
+# endif
+#endif
+
+extern "C" {
+uintptr_t gMozillaPoisonValue;
+uintptr_t gMozillaPoisonBase;
+uintptr_t gMozillaPoisonSize;
+}
+
+// Freed memory is filled with a poison value, which we arrange to
+// form a pointer either to an always-unmapped region of the address
+// space, or to a page that has been reserved and rendered
+// inaccessible via OS primitives. See tests/TestPoisonArea.cpp for
+// extensive discussion of the requirements for this page. The code
+// from here to 'class FreeList' needs to be kept in sync with that
+// file.
+
+#ifdef _WIN32
+static void *
+ReserveRegion(uintptr_t region, uintptr_t size)
+{
+ return VirtualAlloc((void *)region, size, MEM_RESERVE, PAGE_NOACCESS);
+}
+
+static void
+ReleaseRegion(void *region, uintptr_t size)
+{
+ VirtualFree(region, size, MEM_RELEASE);
+}
+
+static bool
+ProbeRegion(uintptr_t region, uintptr_t size)
+{
+ SYSTEM_INFO sinfo;
+ GetSystemInfo(&sinfo);
+ if (region >= (uintptr_t)sinfo.lpMaximumApplicationAddress &&
+ region + size >= (uintptr_t)sinfo.lpMaximumApplicationAddress) {
+ return true;
+ } else {
+ return false;
+ }
+}
+
+static uintptr_t
+GetDesiredRegionSize()
+{
+ SYSTEM_INFO sinfo;
+ GetSystemInfo(&sinfo);
+ return sinfo.dwAllocationGranularity;
+}
+
+#define RESERVE_FAILED 0
+
+#elif defined(__OS2__)
+static void *
+ReserveRegion(uintptr_t region, uintptr_t size)
+{
+ // OS/2 doesn't support allocation at an arbitrary address,
+ // so return an address that is known to be invalid.
+ return (void*)0xFFFD0000;
+}
+
+static void
+ReleaseRegion(void *region, uintptr_t size)
+{
+ return;
+}
+
+static bool
+ProbeRegion(uintptr_t region, uintptr_t size)
+{
+ // There's no reliable way to probe an address in the system
+ // arena other than by touching it and seeing if a trap occurs.
+ return false;
+}
+
+static uintptr_t
+GetDesiredRegionSize()
+{
+ // Page size is fixed at 4k.
+ return 0x1000;
+}
+
+#define RESERVE_FAILED 0
+
+#else // Unix
+
+static void *
+ReserveRegion(uintptr_t region, uintptr_t size)
+{
+ return mmap(reinterpret_cast<void*>(region), size, PROT_NONE, MAP_PRIVATE|MAP_ANON, -1, 0);
+}
+
+static void
+ReleaseRegion(void *region, uintptr_t size)
+{
+ munmap(region, size);
+}
+
+static bool
+ProbeRegion(uintptr_t region, uintptr_t size)
+{
+ if (madvise(reinterpret_cast<void*>(region), size, MADV_NORMAL)) {
+ return true;
+ } else {
+ return false;
+ }
+}
+
+static uintptr_t
+GetDesiredRegionSize()
+{
+ return sysconf(_SC_PAGESIZE);
+}
+
+#define RESERVE_FAILED MAP_FAILED
+
+#endif // system dependencies
+
+MOZ_STATIC_ASSERT(sizeof(uintptr_t) == 4 || sizeof(uintptr_t) == 8, "");
+MOZ_STATIC_ASSERT(sizeof(uintptr_t) == sizeof(void *), "");
+
+static uintptr_t
+ReservePoisonArea(uintptr_t rgnsize)
+{
+ if (sizeof(uintptr_t) == 8) {
+ // Use the hardware-inaccessible region.
+ // We have to avoid 64-bit constants and shifts by 32 bits, since this
+ // code is compiled in 32-bit mode, although it is never executed there.
+ return
+ (((uintptr_t(0x7FFFFFFFu) << 31) << 1 | uintptr_t(0xF0DEAFFFu))
+ & ~(rgnsize-1));
+
+ } else {
+ // First see if we can allocate the preferred poison address from the OS.
+ uintptr_t candidate = (0xF0DEAFFF & ~(rgnsize-1));
+ void *result = ReserveRegion(candidate, rgnsize);
+ if (result == (void *)candidate) {
+ // success - inaccessible page allocated
+ return candidate;
+ }
+
+ // That didn't work, so see if the preferred address is within a range
+ // of permanently inacessible memory.
+ if (ProbeRegion(candidate, rgnsize)) {
+ // success - selected page cannot be usable memory
+ if (result != RESERVE_FAILED)
+ ReleaseRegion(result, rgnsize);
+ return candidate;
+ }
+
+ // The preferred address is already in use. Did the OS give us a
+ // consolation prize?
+ if (result != RESERVE_FAILED) {
+ return uintptr_t(result);
+ }
+
+ // It didn't, so try to allocate again, without any constraint on
+ // the address.
+ result = ReserveRegion(0, rgnsize);
+ if (result != RESERVE_FAILED) {
+ return uintptr_t(result);
+ }
+
+ // no usable poison region identified
+ MOZ_CRASH();
+ return 0;
+ }
+}
+
+void
+mozPoisonValueInit()
+{
+ gMozillaPoisonSize = GetDesiredRegionSize();
+ gMozillaPoisonBase = ReservePoisonArea(gMozillaPoisonSize);
+
+ if (gMozillaPoisonSize == 0) // can't happen
+ return;
+
+ gMozillaPoisonValue = gMozillaPoisonBase + gMozillaPoisonSize/2 - 1;
+}
diff --git a/mfbt/Poison.h b/mfbt/Poison.h
new file mode 100644
index 0000000..42d373b
--- /dev/null
+++ b/mfbt/Poison.h
@@ -0,0 +1,61 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+/*
+ * A poison value that can be used to fill a memory space with
+ * an address that leads to a safe crash when dereferenced.
+ */
+
+#ifndef mozilla_Poison_h_
+#define mozilla_Poison_h_
+
+#include "mozilla/Assertions.h"
+#include "mozilla/StandardInteger.h"
+#include "mozilla/Types.h"
+
+MOZ_BEGIN_EXTERN_C
+
+extern MFBT_DATA uintptr_t gMozillaPoisonValue;
+
+/**
+ * @return the poison value.
+ */
+inline uintptr_t mozPoisonValue()
+{
+ return gMozillaPoisonValue;
+}
+
+/**
+ * Overwrite the memory block of aSize bytes at aPtr with the poison value.
+ * aPtr MUST be aligned at a sizeof(uintptr_t) boundary.
+ * Only an even number of sizeof(uintptr_t) bytes are overwritten, the last
+ * few bytes (if any) is not overwritten.
+ */
+inline void mozWritePoison(void* aPtr, size_t aSize)
+{
+ const uintptr_t POISON = mozPoisonValue();
+ char* p = (char*)aPtr;
+ char* limit = p + aSize;
+ MOZ_ASSERT((uintptr_t)aPtr % sizeof(uintptr_t) == 0, "bad alignment");
+ MOZ_ASSERT(aSize >= sizeof(uintptr_t), "poisoning this object has no effect");
+ for (; p < limit; p += sizeof(uintptr_t)) {
+ *((uintptr_t*)p) = POISON;
+ }
+}
+
+/**
+ * Initialize the poison value.
+ * This should only be called once.
+ */
+extern MFBT_API void mozPoisonValueInit();
+
+/* Values annotated by CrashReporter */
+extern MFBT_DATA uintptr_t gMozillaPoisonBase;
+extern MFBT_DATA uintptr_t gMozillaPoisonSize;
+
+MOZ_END_EXTERN_C
+
+#endif /* mozilla_Poison_h_ */
diff --git a/mfbt/Range.h b/mfbt/Range.h
new file mode 100644
index 0000000..e14594d
--- /dev/null
+++ b/mfbt/Range.h
@@ -0,0 +1,49 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*-
+ * vim: set ts=8 sw=4 et tw=78:
+ *
+ * This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#ifndef mozilla_Range_h_
+#define mozilla_Range_h_
+
+#include "mozilla/NullPtr.h"
+#include "mozilla/RangedPtr.h"
+
+#include <stddef.h>
+
+namespace mozilla {
+
+// Range<T> is a tuple containing a pointer and a length.
+template <typename T>
+class Range
+{
+ RangedPtr<T> mStart;
+ RangedPtr<T> mEnd;
+
+ typedef void (Range::* ConvertibleToBool)();
+ void nonNull() {}
+
+ public:
+ Range() : mStart(nullptr, 0), mEnd(nullptr, 0) {}
+ Range(T* p, size_t len)
+ : mStart(p, p, p + len),
+ mEnd(p + len, p, p + len)
+ {}
+
+ RangedPtr<T> start() const { return mStart; }
+ RangedPtr<T> end() const { return mEnd; }
+ size_t length() const { return mEnd - mStart; }
+
+ T& operator[](size_t offset) {
+ return mStart[offset];
+ }
+
+ operator ConvertibleToBool() const { return mStart ? &Range::nonNull : 0; }
+};
+
+} // namespace mozilla
+
+#endif // mozilla_Range_h_
+
diff --git a/mfbt/RangedPtr.h b/mfbt/RangedPtr.h
new file mode 100644
index 0000000..7ce19d0
--- /dev/null
+++ b/mfbt/RangedPtr.h
@@ -0,0 +1,254 @@
+/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+/*
+ * Implements a smart pointer asserted to remain within a range specified at
+ * construction.
+ */
+
+#ifndef mozilla_RangedPtr_h_
+#define mozilla_RangedPtr_h_
+
+#include "mozilla/Assertions.h"
+#include "mozilla/Attributes.h"
+#include "mozilla/Util.h"
+
+namespace mozilla {
+
+/*
+ * RangedPtr is a smart pointer restricted to an address range specified at
+ * creation. The pointer (and any smart pointers derived from it) must remain
+ * within the range [start, end] (inclusive of end to facilitate use as
+ * sentinels). Dereferencing or indexing into the pointer (or pointers derived
+ * from it) must remain within the range [start, end). All the standard pointer
+ * operators are defined on it; in debug builds these operations assert that the
+ * range specified at construction is respected.
+ *
+ * In theory passing a smart pointer instance as an argument can be slightly
+ * slower than passing a T* (due to ABI requirements for passing structs versus
+ * passing pointers), if the method being called isn't inlined. If you are in
+ * extremely performance-critical code, you may want to be careful using this
+ * smart pointer as an argument type.
+ *
+ * RangedPtr<T> intentionally does not implicitly convert to T*. Use get() to
+ * explicitly convert to T*. Keep in mind that the raw pointer of course won't
+ * implement bounds checking in debug builds.
+ */
+template<typename T>
+class RangedPtr
+{
+ T* ptr;
+
+#ifdef DEBUG
+ T* const rangeStart;
+ T* const rangeEnd;
+#endif
+
+ typedef void (RangedPtr::* ConvertibleToBool)();
+ void nonNull() {}
+
+ void checkSanity() {
+ MOZ_ASSERT(rangeStart <= ptr);
+ MOZ_ASSERT(ptr <= rangeEnd);
+ }
+
+ /* Creates a new pointer for |p|, restricted to this pointer's range. */
+ RangedPtr<T> create(T *p) const {
+#ifdef DEBUG
+ return RangedPtr<T>(p, rangeStart, rangeEnd);
+#else
+ return RangedPtr<T>(p, NULL, size_t(0));
+#endif
+ }
+
+ uintptr_t asUintptr() const { return uintptr_t(ptr); }
+
+ public:
+ RangedPtr(T* p, T* start, T* end)
+ : ptr(p)
+#ifdef DEBUG
+ , rangeStart(start), rangeEnd(end)
+#endif
+ {
+ MOZ_ASSERT(rangeStart <= rangeEnd);
+ checkSanity();
+ }
+ RangedPtr(T* p, T* start, size_t length)
+ : ptr(p)
+#ifdef DEBUG
+ , rangeStart(start), rangeEnd(start + length)
+#endif
+ {
+ MOZ_ASSERT(length <= size_t(-1) / sizeof(T));
+ MOZ_ASSERT(uintptr_t(rangeStart) + length * sizeof(T) >= uintptr_t(rangeStart));
+ checkSanity();
+ }
+
+ /* Equivalent to RangedPtr(p, p, length). */
+ RangedPtr(T* p, size_t length)
+ : ptr(p)
+#ifdef DEBUG
+ , rangeStart(p), rangeEnd(p + length)
+#endif
+ {
+ MOZ_ASSERT(length <= size_t(-1) / sizeof(T));
+ MOZ_ASSERT(uintptr_t(rangeStart) + length * sizeof(T) >= uintptr_t(rangeStart));
+ checkSanity();
+ }
+
+ /* Equivalent to RangedPtr(arr, arr, N). */
+ template<size_t N>
+ RangedPtr(T (&arr)[N])
+ : ptr(arr)
+#ifdef DEBUG
+ , rangeStart(arr), rangeEnd(arr + N)
+#endif
+ {
+ checkSanity();
+ }
+
+ T* get() const {
+ return ptr;
+ }
+
+ operator ConvertibleToBool() const { return ptr ? &RangedPtr::nonNull : 0; }
+
+ /*
+ * You can only assign one RangedPtr into another if the two pointers have
+ * the same valid range:
+ *
+ * char arr1[] = "hi";
+ * char arr2[] = "bye";
+ * RangedPtr<char> p1(arr1, 2);
+ * p1 = RangedPtr<char>(arr1 + 1, arr1, arr1 + 2); // works
+ * p1 = RangedPtr<char>(arr2, 3); // asserts
+ */
+ RangedPtr<T>& operator=(const RangedPtr<T>& other) {
+ MOZ_ASSERT(rangeStart == other.rangeStart);
+ MOZ_ASSERT(rangeEnd == other.rangeEnd);
+ ptr = other.ptr;
+ checkSanity();
+ return *this;
+ }
+
+ RangedPtr<T> operator+(size_t inc) {
+ MOZ_ASSERT(inc <= size_t(-1) / sizeof(T));
+ MOZ_ASSERT(asUintptr() + inc * sizeof(T) >= asUintptr());
+ return create(ptr + inc);
+ }
+
+ RangedPtr<T> operator-(size_t dec) {
+ MOZ_ASSERT(dec <= size_t(-1) / sizeof(T));
+ MOZ_ASSERT(asUintptr() - dec * sizeof(T) <= asUintptr());
+ return create(ptr - dec);
+ }
+
+ /*
+ * You can assign a raw pointer into a RangedPtr if the raw pointer is
+ * within the range specified at creation.
+ */
+ template <typename U>
+ RangedPtr<T>& operator=(U* p) {
+ *this = create(p);
+ return *this;
+ }
+
+ template <typename U>
+ RangedPtr<T>& operator=(const RangedPtr<U>& p) {
+ MOZ_ASSERT(rangeStart <= p.ptr);
+ MOZ_ASSERT(p.ptr <= rangeEnd);
+ ptr = p.ptr;
+ checkSanity();
+ return *this;
+ }
+
+ RangedPtr<T>& operator++() {
+ return (*this += 1);
+ }
+
+ RangedPtr<T> operator++(int) {
+ RangedPtr<T> rcp = *this;
+ ++*this;
+ return rcp;
+ }
+
+ RangedPtr<T>& operator--() {
+ return (*this -= 1);
+ }
+
+ RangedPtr<T> operator--(int) {
+ RangedPtr<T> rcp = *this;
+ --*this;
+ return rcp;
+ }
+
+ RangedPtr<T>& operator+=(size_t inc) {
+ *this = *this + inc;
+ return *this;
+ }
+
+ RangedPtr<T>& operator-=(size_t dec) {
+ *this = *this - dec;
+ return *this;
+ }
+
+ T& operator[](int index) const {
+ MOZ_ASSERT(size_t(index > 0 ? index : -index) <= size_t(-1) / sizeof(T));
+ return *create(ptr + index);
+ }
+
+ T& operator*() const {
+ return *ptr;
+ }
+
+ template <typename U>
+ bool operator==(const RangedPtr<U>& other) const {
+ return ptr == other.ptr;
+ }
+ template <typename U>
+ bool operator!=(const RangedPtr<U>& other) const {
+ return !(*this == other);
+ }
+
+ template<typename U>
+ bool operator==(const U* u) const {
+ return ptr == u;
+ }
+ template<typename U>
+ bool operator!=(const U* u) const {
+ return !(*this == u);
+ }
+
+ template <typename U>
+ bool operator<(const RangedPtr<U>& other) const {
+ return ptr < other.ptr;
+ }
+ template <typename U>
+ bool operator<=(const RangedPtr<U>& other) const {
+ return ptr <= other.ptr;
+ }
+
+ template <typename U>
+ bool operator>(const RangedPtr<U>& other) const {
+ return ptr > other.ptr;
+ }
+ template <typename U>
+ bool operator>=(const RangedPtr<U>& other) const {
+ return ptr >= other.ptr;
+ }
+
+ size_t operator-(const RangedPtr<T>& other) const {
+ MOZ_ASSERT(ptr >= other.ptr);
+ return PointerRangeSize(other.ptr, ptr);
+ }
+
+ private:
+ RangedPtr() MOZ_DELETE;
+ T* operator&() MOZ_DELETE;
+};
+
+} /* namespace mozilla */
+
+#endif /* mozilla_RangedPtr_h_ */
diff --git a/mfbt/RefPtr.h b/mfbt/RefPtr.h
new file mode 100644
index 0000000..3367e3a
--- /dev/null
+++ b/mfbt/RefPtr.h
@@ -0,0 +1,449 @@
+/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+/* Helpers for defining and using refcounted objects. */
+
+#ifndef mozilla_RefPtr_h_
+#define mozilla_RefPtr_h_
+
+#include "mozilla/Assertions.h"
+#include "mozilla/Atomics.h"
+#include "mozilla/Attributes.h"
+#include "mozilla/TypeTraits.h"
+
+namespace mozilla {
+
+template<typename T> class RefCounted;
+template<typename T> class RefPtr;
+template<typename T> class TemporaryRef;
+template<typename T> class OutParamRef;
+template<typename T> OutParamRef<T> byRef(RefPtr<T>&);
+
+/**
+ * RefCounted<T> is a sort of a "mixin" for a class T. RefCounted
+ * manages, well, refcounting for T, and because RefCounted is
+ * parameterized on T, RefCounted<T> can call T's destructor directly.
+ * This means T doesn't need to have a virtual dtor and so doesn't
+ * need a vtable.
+ *
+ * RefCounted<T> is created with refcount == 0. Newly-allocated
+ * RefCounted<T> must immediately be assigned to a RefPtr to make the
+ * refcount > 0. It's an error to allocate and free a bare
+ * RefCounted<T>, i.e. outside of the RefPtr machinery. Attempts to
+ * do so will abort DEBUG builds.
+ *
+ * Live RefCounted<T> have refcount > 0. The lifetime (refcounts) of
+ * live RefCounted<T> are controlled by RefPtr<T> and
+ * RefPtr<super/subclass of T>. Upon a transition from refcounted==1
+ * to 0, the RefCounted<T> "dies" and is destroyed. The "destroyed"
+ * state is represented in DEBUG builds by refcount==0xffffdead. This
+ * state distinguishes use-before-ref (refcount==0) from
+ * use-after-destroy (refcount==0xffffdead).
+ */
+namespace detail {
+#ifdef DEBUG
+static const int DEAD = 0xffffdead;
+#endif
+
+// This is used WeakPtr.h as well as this file.
+enum RefCountAtomicity
+{
+ AtomicRefCount,
+ NonAtomicRefCount
+};
+
+template<typename T, RefCountAtomicity Atomicity>
+class RefCounted
+{
+ friend class RefPtr<T>;
+
+ protected:
+ RefCounted() : refCnt(0) { }
+ ~RefCounted() {
+ MOZ_ASSERT(refCnt == detail::DEAD);
+ }
+
+ public:
+ // Compatibility with nsRefPtr.
+ void AddRef() {
+ MOZ_ASSERT(refCnt >= 0);
+ ++refCnt;
+ }
+
+ void Release() {
+ MOZ_ASSERT(refCnt > 0);
+ if (0 == --refCnt) {
+#ifdef DEBUG
+ refCnt = detail::DEAD;
+#endif
+ delete static_cast<T*>(this);
+ }
+ }
+
+ // Compatibility with wtf::RefPtr.
+ void ref() { AddRef(); }
+ void deref() { Release(); }
+ int refCount() const { return refCnt; }
+ bool hasOneRef() const {
+ MOZ_ASSERT(refCnt > 0);
+ return refCnt == 1;
+ }
+
+ private:
+ typename Conditional<Atomicity == AtomicRefCount, Atomic<int>, int>::Type refCnt;
+};
+
+}
+
+template<typename T>
+class RefCounted : public detail::RefCounted<T, detail::NonAtomicRefCount>
+{
+ public:
+ ~RefCounted() {
+ MOZ_STATIC_ASSERT((IsBaseOf<RefCounted, T>::value),
+ "T must derive from RefCounted<T>");
+ }
+};
+
+/**
+ * AtomicRefCounted<T> is like RefCounted<T>, with an atomically updated
+ * reference counter.
+ */
+template<typename T>
+class AtomicRefCounted : public detail::RefCounted<T, detail::AtomicRefCount>
+{
+ public:
+ ~AtomicRefCounted() {
+ MOZ_STATIC_ASSERT((IsBaseOf<AtomicRefCounted, T>::value),
+ "T must derive from AtomicRefCounted<T>");
+ }
+};
+
+/**
+ * RefPtr points to a refcounted thing that has AddRef and Release
+ * methods to increase/decrease the refcount, respectively. After a
+ * RefPtr<T> is assigned a T*, the T* can be used through the RefPtr
+ * as if it were a T*.
+ *
+ * A RefPtr can forget its underlying T*, which results in the T*
+ * being wrapped in a temporary object until the T* is either
+ * re-adopted from or released by the temporary.
+ */
+template<typename T>
+class RefPtr
+{
+ // To allow them to use unref()
+ friend class TemporaryRef<T>;
+ friend class OutParamRef<T>;
+
+ struct DontRef {};
+
+ public:
+ RefPtr() : ptr(0) { }
+ RefPtr(const RefPtr& o) : ptr(ref(o.ptr)) {}
+ RefPtr(const TemporaryRef<T>& o) : ptr(o.drop()) {}
+ RefPtr(T* t) : ptr(ref(t)) {}
+
+ template<typename U>
+ RefPtr(const RefPtr<U>& o) : ptr(ref(o.get())) {}
+
+ ~RefPtr() { unref(ptr); }
+
+ RefPtr& operator=(const RefPtr& o) {
+ assign(ref(o.ptr));
+ return *this;
+ }
+ RefPtr& operator=(const TemporaryRef<T>& o) {
+ assign(o.drop());
+ return *this;
+ }
+ RefPtr& operator=(T* t) {
+ assign(ref(t));
+ return *this;
+ }
+
+ template<typename U>
+ RefPtr& operator=(const RefPtr<U>& o) {
+ assign(ref(o.get()));
+ return *this;
+ }
+
+ TemporaryRef<T> forget() {
+ T* tmp = ptr;
+ ptr = 0;
+ return TemporaryRef<T>(tmp, DontRef());
+ }
+
+ T* get() const { return ptr; }
+ operator T*() const { return ptr; }
+ T* operator->() const { return ptr; }
+ T& operator*() const { return *ptr; }
+ template<typename U>
+ operator TemporaryRef<U>() { return TemporaryRef<U>(ptr); }
+
+ private:
+ void assign(T* t) {
+ unref(ptr);
+ ptr = t;
+ }
+
+ T* ptr;
+
+ static MOZ_ALWAYS_INLINE T* ref(T* t) {
+ if (t)
+ t->AddRef();
+ return t;
+ }
+
+ static MOZ_ALWAYS_INLINE void unref(T* t) {
+ if (t)
+ t->Release();
+ }
+};
+
+/**
+ * TemporaryRef<T> represents an object that holds a temporary
+ * reference to a T. TemporaryRef objects can't be manually ref'd or
+ * unref'd (being temporaries, not lvalues), so can only relinquish
+ * references to other objects, or unref on destruction.
+ */
+template<typename T>
+class TemporaryRef
+{
+ // To allow it to construct TemporaryRef from a bare T*
+ friend class RefPtr<T>;
+
+ typedef typename RefPtr<T>::DontRef DontRef;
+
+ public:
+ TemporaryRef(T* t) : ptr(RefPtr<T>::ref(t)) {}
+ TemporaryRef(const TemporaryRef& o) : ptr(o.drop()) {}
+
+ template<typename U>
+ TemporaryRef(const TemporaryRef<U>& o) : ptr(o.drop()) {}
+
+ ~TemporaryRef() { RefPtr<T>::unref(ptr); }
+
+ T* drop() const {
+ T* tmp = ptr;
+ ptr = 0;
+ return tmp;
+ }
+
+ private:
+ TemporaryRef(T* t, const DontRef&) : ptr(t) {}
+
+ mutable T* ptr;
+
+ TemporaryRef() MOZ_DELETE;
+ void operator=(const TemporaryRef&) MOZ_DELETE;
+};
+
+/**
+ * OutParamRef is a wrapper that tracks a refcounted pointer passed as
+ * an outparam argument to a function. OutParamRef implements COM T**
+ * outparam semantics: this requires the callee to AddRef() the T*
+ * returned through the T** outparam on behalf of the caller. This
+ * means the caller (through OutParamRef) must Release() the old
+ * object contained in the tracked RefPtr. It's OK if the callee
+ * returns the same T* passed to it through the T** outparam, as long
+ * as the callee obeys the COM discipline.
+ *
+ * Prefer returning TemporaryRef<T> from functions over creating T**
+ * outparams and passing OutParamRef<T> to T**. Prefer RefPtr<T>*
+ * outparams over T** outparams.
+ */
+template<typename T>
+class OutParamRef
+{
+ friend OutParamRef byRef<T>(RefPtr<T>&);
+
+ public:
+ ~OutParamRef() {
+ RefPtr<T>::unref(refPtr.ptr);
+ refPtr.ptr = tmp;
+ }
+
+ operator T**() { return &tmp; }
+
+ private:
+ OutParamRef(RefPtr<T>& p) : refPtr(p), tmp(p.get()) {}
+
+ RefPtr<T>& refPtr;
+ T* tmp;
+
+ OutParamRef() MOZ_DELETE;
+ OutParamRef& operator=(const OutParamRef&) MOZ_DELETE;
+};
+
+/**
+ * byRef cooperates with OutParamRef to implement COM outparam semantics.
+ */
+template<typename T>
+OutParamRef<T>
+byRef(RefPtr<T>& ptr)
+{
+ return OutParamRef<T>(ptr);
+}
+
+} // namespace mozilla
+
+#endif // mozilla_RefPtr_h_
+
+
+#if 0
+
+// Command line that builds these tests
+//
+// cp RefPtr.h test.cc && g++ -g -Wall -pedantic -DDEBUG -o test test.cc && ./test
+
+using namespace mozilla;
+
+struct Foo : public RefCounted<Foo>
+{
+ Foo() : dead(false) { }
+ ~Foo() {
+ MOZ_ASSERT(!dead);
+ dead = true;
+ numDestroyed++;
+ }
+
+ bool dead;
+ static int numDestroyed;
+};
+int Foo::numDestroyed;
+
+struct Bar : public Foo { };
+
+TemporaryRef<Foo>
+NewFoo()
+{
+ return RefPtr<Foo>(new Foo());
+}
+
+TemporaryRef<Foo>
+NewBar()
+{
+ return new Bar();
+}
+
+void
+GetNewFoo(Foo** f)
+{
+ *f = new Bar();
+ // Kids, don't try this at home
+ (*f)->AddRef();
+}
+
+void
+GetPassedFoo(Foo** f)
+{
+ // Kids, don't try this at home
+ (*f)->AddRef();
+}
+
+void
+GetNewFoo(RefPtr<Foo>* f)
+{
+ *f = new Bar();
+}
+
+void
+GetPassedFoo(RefPtr<Foo>* f)
+{}
+
+TemporaryRef<Foo>
+GetNullFoo()
+{
+ return 0;
+}
+
+int
+main(int argc, char** argv)
+{
+ // This should blow up
+// Foo* f = new Foo(); delete f;
+
+ MOZ_ASSERT(0 == Foo::numDestroyed);
+ {
+ RefPtr<Foo> f = new Foo();
+ MOZ_ASSERT(f->refCount() == 1);
+ }
+ MOZ_ASSERT(1 == Foo::numDestroyed);
+
+ {
+ RefPtr<Foo> f1 = NewFoo();
+ RefPtr<Foo> f2(NewFoo());
+ MOZ_ASSERT(1 == Foo::numDestroyed);
+ }
+ MOZ_ASSERT(3 == Foo::numDestroyed);
+
+ {
+ RefPtr<Foo> b = NewBar();
+ MOZ_ASSERT(3 == Foo::numDestroyed);
+ }
+ MOZ_ASSERT(4 == Foo::numDestroyed);
+
+ {
+ RefPtr<Foo> f1;
+ {
+ f1 = new Foo();
+ RefPtr<Foo> f2(f1);
+ RefPtr<Foo> f3 = f2;
+ MOZ_ASSERT(4 == Foo::numDestroyed);
+ }
+ MOZ_ASSERT(4 == Foo::numDestroyed);
+ }
+ MOZ_ASSERT(5 == Foo::numDestroyed);
+
+ {
+ RefPtr<Foo> f = new Foo();
+ f.forget();
+ MOZ_ASSERT(6 == Foo::numDestroyed);
+ }
+
+ {
+ RefPtr<Foo> f = new Foo();
+ GetNewFoo(byRef(f));
+ MOZ_ASSERT(7 == Foo::numDestroyed);
+ }
+ MOZ_ASSERT(8 == Foo::numDestroyed);
+
+ {
+ RefPtr<Foo> f = new Foo();
+ GetPassedFoo(byRef(f));
+ MOZ_ASSERT(8 == Foo::numDestroyed);
+ }
+ MOZ_ASSERT(9 == Foo::numDestroyed);
+
+ {
+ RefPtr<Foo> f = new Foo();
+ GetNewFoo(&f);
+ MOZ_ASSERT(10 == Foo::numDestroyed);
+ }
+ MOZ_ASSERT(11 == Foo::numDestroyed);
+
+ {
+ RefPtr<Foo> f = new Foo();
+ GetPassedFoo(&f);
+ MOZ_ASSERT(11 == Foo::numDestroyed);
+ }
+ MOZ_ASSERT(12 == Foo::numDestroyed);
+
+ {
+ RefPtr<Foo> f1 = new Bar();
+ }
+ MOZ_ASSERT(13 == Foo::numDestroyed);
+
+ {
+ RefPtr<Foo> f = GetNullFoo();
+ MOZ_ASSERT(13 == Foo::numDestroyed);
+ }
+ MOZ_ASSERT(13 == Foo::numDestroyed);
+
+ return 0;
+}
+
+#endif
diff --git a/mfbt/SHA1.cpp b/mfbt/SHA1.cpp
new file mode 100644
index 0000000..f11b064
--- /dev/null
+++ b/mfbt/SHA1.cpp
@@ -0,0 +1,327 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#include "mozilla/Assertions.h"
+#include "mozilla/Endian.h"
+#include "mozilla/SHA1.h"
+
+#include <string.h>
+
+using mozilla::NativeEndian;
+using mozilla::SHA1Sum;
+
+static inline uint32_t
+SHA_ROTL(uint32_t t, uint32_t n)
+{
+ MOZ_ASSERT(n < 32);
+ return (t << n) | (t >> (32 - n));
+}
+
+static void
+shaCompress(volatile unsigned* X, const uint32_t* datain);
+
+#define SHA_F1(X, Y, Z) ((((Y) ^ (Z)) & (X)) ^ (Z))
+#define SHA_F2(X, Y, Z) ((X) ^ (Y) ^ (Z))
+#define SHA_F3(X, Y, Z) (((X) & (Y)) | ((Z) & ((X) | (Y))))
+#define SHA_F4(X, Y, Z) ((X) ^ (Y) ^ (Z))
+
+#define SHA_MIX(n, a, b, c) XW(n) = SHA_ROTL(XW(a) ^ XW(b) ^ XW(c) ^XW(n), 1)
+
+SHA1Sum::SHA1Sum()
+ : size(0), mDone(false)
+{
+ // Initialize H with constants from FIPS180-1.
+ H[0] = 0x67452301L;
+ H[1] = 0xefcdab89L;
+ H[2] = 0x98badcfeL;
+ H[3] = 0x10325476L;
+ H[4] = 0xc3d2e1f0L;
+}
+
+/*
+ * Explanation of H array and index values:
+ *
+ * The context's H array is actually the concatenation of two arrays
+ * defined by SHA1, the H array of state variables (5 elements),
+ * and the W array of intermediate values, of which there are 16 elements.
+ * The W array starts at H[5], that is W[0] is H[5].
+ * Although these values are defined as 32-bit values, we use 64-bit
+ * variables to hold them because the AMD64 stores 64 bit values in
+ * memory MUCH faster than it stores any smaller values.
+ *
+ * Rather than passing the context structure to shaCompress, we pass
+ * this combined array of H and W values. We do not pass the address
+ * of the first element of this array, but rather pass the address of an
+ * element in the middle of the array, element X. Presently X[0] is H[11].
+ * So we pass the address of H[11] as the address of array X to shaCompress.
+ * Then shaCompress accesses the members of the array using positive AND
+ * negative indexes.
+ *
+ * Pictorially: (each element is 8 bytes)
+ * H | H0 H1 H2 H3 H4 W0 W1 W2 W3 W4 W5 W6 W7 W8 W9 Wa Wb Wc Wd We Wf |
+ * X |-11-10 -9 -8 -7 -6 -5 -4 -3 -2 -1 X0 X1 X2 X3 X4 X5 X6 X7 X8 X9 |
+ *
+ * The byte offset from X[0] to any member of H and W is always
+ * representable in a signed 8-bit value, which will be encoded
+ * as a single byte offset in the X86-64 instruction set.
+ * If we didn't pass the address of H[11], and instead passed the
+ * address of H[0], the offsets to elements H[16] and above would be
+ * greater than 127, not representable in a signed 8-bit value, and the
+ * x86-64 instruction set would encode every such offset as a 32-bit
+ * signed number in each instruction that accessed element H[16] or
+ * higher. This results in much bigger and slower code.
+ */
+#define H2X 11 /* X[0] is H[11], and H[0] is X[-11] */
+#define W2X 6 /* X[0] is W[6], and W[0] is X[-6] */
+
+/*
+ * SHA: Add data to context.
+ */
+void
+SHA1Sum::update(const void* dataIn, uint32_t len)
+{
+ MOZ_ASSERT(!mDone, "SHA1Sum can only be used to compute a single hash.");
+
+ const uint8_t* data = static_cast<const uint8_t*>(dataIn);
+
+ if (len == 0)
+ return;
+
+ /* Accumulate the byte count. */
+ unsigned int lenB = static_cast<unsigned int>(size) & 63U;
+
+ size += len;
+
+ /* Read the data into W and process blocks as they get full. */
+ unsigned int togo;
+ if (lenB > 0) {
+ togo = 64U - lenB;
+ if (len < togo)
+ togo = len;
+ memcpy(u.b + lenB, data, togo);
+ len -= togo;
+ data += togo;
+ lenB = (lenB + togo) & 63U;
+ if (!lenB)
+ shaCompress(&H[H2X], u.w);
+ }
+
+ while (len >= 64U) {
+ len -= 64U;
+ shaCompress(&H[H2X], reinterpret_cast<const uint32_t*>(data));
+ data += 64U;
+ }
+
+ if (len > 0)
+ memcpy(u.b, data, len);
+}
+
+
+/*
+ * SHA: Generate hash value
+ */
+void
+SHA1Sum::finish(SHA1Sum::Hash& hashOut)
+{
+ MOZ_ASSERT(!mDone, "SHA1Sum can only be used to compute a single hash.");
+
+ uint64_t size2 = size;
+ uint32_t lenB = uint32_t(size2) & 63;
+
+ static const uint8_t bulk_pad[64] =
+ { 0x80,0,0,0,0,0,0,0,0,0,
+ 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
+ 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 };
+
+ /* Pad with a binary 1 (e.g. 0x80), then zeroes, then length in bits. */
+ update(bulk_pad, (((55 + 64) - lenB) & 63) + 1);
+ MOZ_ASSERT((uint32_t(size) & 63) == 56);
+
+ /* Convert size from bytes to bits. */
+ size2 <<= 3;
+ u.w[14] = NativeEndian::swapToBigEndian(uint32_t(size2 >> 32));
+ u.w[15] = NativeEndian::swapToBigEndian(uint32_t(size2));
+ shaCompress(&H[H2X], u.w);
+
+ /* Output hash. */
+ u.w[0] = NativeEndian::swapToBigEndian(H[0]);
+ u.w[1] = NativeEndian::swapToBigEndian(H[1]);
+ u.w[2] = NativeEndian::swapToBigEndian(H[2]);
+ u.w[3] = NativeEndian::swapToBigEndian(H[3]);
+ u.w[4] = NativeEndian::swapToBigEndian(H[4]);
+ memcpy(hashOut, u.w, 20);
+ mDone = true;
+}
+
+/*
+ * SHA: Compression function, unrolled.
+ *
+ * Some operations in shaCompress are done as 5 groups of 16 operations.
+ * Others are done as 4 groups of 20 operations.
+ * The code below shows that structure.
+ *
+ * The functions that compute the new values of the 5 state variables
+ * A-E are done in 4 groups of 20 operations (or you may also think
+ * of them as being done in 16 groups of 5 operations). They are
+ * done by the SHA_RNDx macros below, in the right column.
+ *
+ * The functions that set the 16 values of the W array are done in
+ * 5 groups of 16 operations. The first group is done by the
+ * LOAD macros below, the latter 4 groups are done by SHA_MIX below,
+ * in the left column.
+ *
+ * gcc's optimizer observes that each member of the W array is assigned
+ * a value 5 times in this code. It reduces the number of store
+ * operations done to the W array in the context (that is, in the X array)
+ * by creating a W array on the stack, and storing the W values there for
+ * the first 4 groups of operations on W, and storing the values in the
+ * context's W array only in the fifth group. This is undesirable.
+ * It is MUCH bigger code than simply using the context's W array, because
+ * all the offsets to the W array in the stack are 32-bit signed offsets,
+ * and it is no faster than storing the values in the context's W array.
+ *
+ * The original code for sha_fast.c prevented this creation of a separate
+ * W array in the stack by creating a W array of 80 members, each of
+ * whose elements is assigned only once. It also separated the computations
+ * of the W array values and the computations of the values for the 5
+ * state variables into two separate passes, W's, then A-E's so that the
+ * second pass could be done all in registers (except for accessing the W
+ * array) on machines with fewer registers. The method is suboptimal
+ * for machines with enough registers to do it all in one pass, and it
+ * necessitates using many instructions with 32-bit offsets.
+ *
+ * This code eliminates the separate W array on the stack by a completely
+ * different means: by declaring the X array volatile. This prevents
+ * the optimizer from trying to reduce the use of the X array by the
+ * creation of a MORE expensive W array on the stack. The result is
+ * that all instructions use signed 8-bit offsets and not 32-bit offsets.
+ *
+ * The combination of this code and the -O3 optimizer flag on GCC 3.4.3
+ * results in code that is 3 times faster than the previous NSS sha_fast
+ * code on AMD64.
+ */
+static void
+shaCompress(volatile unsigned *X, const uint32_t *inbuf)
+{
+ unsigned A, B, C, D, E;
+
+#define XH(n) X[n - H2X]
+#define XW(n) X[n - W2X]
+
+#define K0 0x5a827999L
+#define K1 0x6ed9eba1L
+#define K2 0x8f1bbcdcL
+#define K3 0xca62c1d6L
+
+#define SHA_RND1(a, b, c, d, e, n) \
+ a = SHA_ROTL(b, 5) + SHA_F1(c, d, e) + a + XW(n) + K0; c = SHA_ROTL(c, 30)
+#define SHA_RND2(a, b, c, d, e, n) \
+ a = SHA_ROTL(b, 5) + SHA_F2(c, d, e) + a + XW(n) + K1; c = SHA_ROTL(c, 30)
+#define SHA_RND3(a, b, c, d, e, n) \
+ a = SHA_ROTL(b, 5) + SHA_F3(c, d, e) + a + XW(n) + K2; c = SHA_ROTL(c, 30)
+#define SHA_RND4(a, b, c, d, e, n) \
+ a = SHA_ROTL(b ,5) + SHA_F4(c, d, e) + a + XW(n) + K3; c = SHA_ROTL(c, 30)
+
+#define LOAD(n) XW(n) = NativeEndian::swapToBigEndian(inbuf[n])
+
+ A = XH(0);
+ B = XH(1);
+ C = XH(2);
+ D = XH(3);
+ E = XH(4);
+
+ LOAD(0); SHA_RND1(E,A,B,C,D, 0);
+ LOAD(1); SHA_RND1(D,E,A,B,C, 1);
+ LOAD(2); SHA_RND1(C,D,E,A,B, 2);
+ LOAD(3); SHA_RND1(B,C,D,E,A, 3);
+ LOAD(4); SHA_RND1(A,B,C,D,E, 4);
+ LOAD(5); SHA_RND1(E,A,B,C,D, 5);
+ LOAD(6); SHA_RND1(D,E,A,B,C, 6);
+ LOAD(7); SHA_RND1(C,D,E,A,B, 7);
+ LOAD(8); SHA_RND1(B,C,D,E,A, 8);
+ LOAD(9); SHA_RND1(A,B,C,D,E, 9);
+ LOAD(10); SHA_RND1(E,A,B,C,D,10);
+ LOAD(11); SHA_RND1(D,E,A,B,C,11);
+ LOAD(12); SHA_RND1(C,D,E,A,B,12);
+ LOAD(13); SHA_RND1(B,C,D,E,A,13);
+ LOAD(14); SHA_RND1(A,B,C,D,E,14);
+ LOAD(15); SHA_RND1(E,A,B,C,D,15);
+
+ SHA_MIX( 0, 13, 8, 2); SHA_RND1(D,E,A,B,C, 0);
+ SHA_MIX( 1, 14, 9, 3); SHA_RND1(C,D,E,A,B, 1);
+ SHA_MIX( 2, 15, 10, 4); SHA_RND1(B,C,D,E,A, 2);
+ SHA_MIX( 3, 0, 11, 5); SHA_RND1(A,B,C,D,E, 3);
+
+ SHA_MIX( 4, 1, 12, 6); SHA_RND2(E,A,B,C,D, 4);
+ SHA_MIX( 5, 2, 13, 7); SHA_RND2(D,E,A,B,C, 5);
+ SHA_MIX( 6, 3, 14, 8); SHA_RND2(C,D,E,A,B, 6);
+ SHA_MIX( 7, 4, 15, 9); SHA_RND2(B,C,D,E,A, 7);
+ SHA_MIX( 8, 5, 0, 10); SHA_RND2(A,B,C,D,E, 8);
+ SHA_MIX( 9, 6, 1, 11); SHA_RND2(E,A,B,C,D, 9);
+ SHA_MIX(10, 7, 2, 12); SHA_RND2(D,E,A,B,C,10);
+ SHA_MIX(11, 8, 3, 13); SHA_RND2(C,D,E,A,B,11);
+ SHA_MIX(12, 9, 4, 14); SHA_RND2(B,C,D,E,A,12);
+ SHA_MIX(13, 10, 5, 15); SHA_RND2(A,B,C,D,E,13);
+ SHA_MIX(14, 11, 6, 0); SHA_RND2(E,A,B,C,D,14);
+ SHA_MIX(15, 12, 7, 1); SHA_RND2(D,E,A,B,C,15);
+
+ SHA_MIX( 0, 13, 8, 2); SHA_RND2(C,D,E,A,B, 0);
+ SHA_MIX( 1, 14, 9, 3); SHA_RND2(B,C,D,E,A, 1);
+ SHA_MIX( 2, 15, 10, 4); SHA_RND2(A,B,C,D,E, 2);
+ SHA_MIX( 3, 0, 11, 5); SHA_RND2(E,A,B,C,D, 3);
+ SHA_MIX( 4, 1, 12, 6); SHA_RND2(D,E,A,B,C, 4);
+ SHA_MIX( 5, 2, 13, 7); SHA_RND2(C,D,E,A,B, 5);
+ SHA_MIX( 6, 3, 14, 8); SHA_RND2(B,C,D,E,A, 6);
+ SHA_MIX( 7, 4, 15, 9); SHA_RND2(A,B,C,D,E, 7);
+
+ SHA_MIX( 8, 5, 0, 10); SHA_RND3(E,A,B,C,D, 8);
+ SHA_MIX( 9, 6, 1, 11); SHA_RND3(D,E,A,B,C, 9);
+ SHA_MIX(10, 7, 2, 12); SHA_RND3(C,D,E,A,B,10);
+ SHA_MIX(11, 8, 3, 13); SHA_RND3(B,C,D,E,A,11);
+ SHA_MIX(12, 9, 4, 14); SHA_RND3(A,B,C,D,E,12);
+ SHA_MIX(13, 10, 5, 15); SHA_RND3(E,A,B,C,D,13);
+ SHA_MIX(14, 11, 6, 0); SHA_RND3(D,E,A,B,C,14);
+ SHA_MIX(15, 12, 7, 1); SHA_RND3(C,D,E,A,B,15);
+
+ SHA_MIX( 0, 13, 8, 2); SHA_RND3(B,C,D,E,A, 0);
+ SHA_MIX( 1, 14, 9, 3); SHA_RND3(A,B,C,D,E, 1);
+ SHA_MIX( 2, 15, 10, 4); SHA_RND3(E,A,B,C,D, 2);
+ SHA_MIX( 3, 0, 11, 5); SHA_RND3(D,E,A,B,C, 3);
+ SHA_MIX( 4, 1, 12, 6); SHA_RND3(C,D,E,A,B, 4);
+ SHA_MIX( 5, 2, 13, 7); SHA_RND3(B,C,D,E,A, 5);
+ SHA_MIX( 6, 3, 14, 8); SHA_RND3(A,B,C,D,E, 6);
+ SHA_MIX( 7, 4, 15, 9); SHA_RND3(E,A,B,C,D, 7);
+ SHA_MIX( 8, 5, 0, 10); SHA_RND3(D,E,A,B,C, 8);
+ SHA_MIX( 9, 6, 1, 11); SHA_RND3(C,D,E,A,B, 9);
+ SHA_MIX(10, 7, 2, 12); SHA_RND3(B,C,D,E,A,10);
+ SHA_MIX(11, 8, 3, 13); SHA_RND3(A,B,C,D,E,11);
+
+ SHA_MIX(12, 9, 4, 14); SHA_RND4(E,A,B,C,D,12);
+ SHA_MIX(13, 10, 5, 15); SHA_RND4(D,E,A,B,C,13);
+ SHA_MIX(14, 11, 6, 0); SHA_RND4(C,D,E,A,B,14);
+ SHA_MIX(15, 12, 7, 1); SHA_RND4(B,C,D,E,A,15);
+
+ SHA_MIX( 0, 13, 8, 2); SHA_RND4(A,B,C,D,E, 0);
+ SHA_MIX( 1, 14, 9, 3); SHA_RND4(E,A,B,C,D, 1);
+ SHA_MIX( 2, 15, 10, 4); SHA_RND4(D,E,A,B,C, 2);
+ SHA_MIX( 3, 0, 11, 5); SHA_RND4(C,D,E,A,B, 3);
+ SHA_MIX( 4, 1, 12, 6); SHA_RND4(B,C,D,E,A, 4);
+ SHA_MIX( 5, 2, 13, 7); SHA_RND4(A,B,C,D,E, 5);
+ SHA_MIX( 6, 3, 14, 8); SHA_RND4(E,A,B,C,D, 6);
+ SHA_MIX( 7, 4, 15, 9); SHA_RND4(D,E,A,B,C, 7);
+ SHA_MIX( 8, 5, 0, 10); SHA_RND4(C,D,E,A,B, 8);
+ SHA_MIX( 9, 6, 1, 11); SHA_RND4(B,C,D,E,A, 9);
+ SHA_MIX(10, 7, 2, 12); SHA_RND4(A,B,C,D,E,10);
+ SHA_MIX(11, 8, 3, 13); SHA_RND4(E,A,B,C,D,11);
+ SHA_MIX(12, 9, 4, 14); SHA_RND4(D,E,A,B,C,12);
+ SHA_MIX(13, 10, 5, 15); SHA_RND4(C,D,E,A,B,13);
+ SHA_MIX(14, 11, 6, 0); SHA_RND4(B,C,D,E,A,14);
+ SHA_MIX(15, 12, 7, 1); SHA_RND4(A,B,C,D,E,15);
+
+ XH(0) += A;
+ XH(1) += B;
+ XH(2) += C;
+ XH(3) += D;
+ XH(4) += E;
+}
diff --git a/mfbt/SHA1.h b/mfbt/SHA1.h
new file mode 100644
index 0000000..a6604e6
--- /dev/null
+++ b/mfbt/SHA1.h
@@ -0,0 +1,61 @@
+/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+/* Simple class for computing SHA1. */
+
+#ifndef mozilla_SHA1_h_
+#define mozilla_SHA1_h_
+
+#include "mozilla/StandardInteger.h"
+#include "mozilla/Types.h"
+
+#include <stddef.h>
+
+namespace mozilla {
+
+/**
+ * This class computes the SHA1 hash of a byte sequence, or of the concatenation
+ * of multiple sequences. For example, computing the SHA1 of two sequences of
+ * bytes could be done as follows:
+ *
+ * void SHA1(const uint8_t* buf1, uint32_t size1,
+ * const uint8_t* buf2, uint32_t size2,
+ * SHA1Sum::Hash& hash)
+ * {
+ * SHA1Sum s;
+ * s.update(buf1, size1);
+ * s.update(buf2, size2);
+ * s.finish(hash);
+ * }
+ *
+ * The finish method may only be called once and cannot be followed by calls
+ * to update.
+ */
+class SHA1Sum
+{
+ union {
+ uint32_t w[16]; /* input buffer */
+ uint8_t b[64];
+ } u;
+ uint64_t size; /* count of hashed bytes. */
+ unsigned H[22]; /* 5 state variables, 16 tmp values, 1 extra */
+ bool mDone;
+
+ public:
+ MFBT_API SHA1Sum();
+
+ static const size_t HashSize = 20;
+ typedef uint8_t Hash[HashSize];
+
+ /* Add len bytes of dataIn to the data sequence being hashed. */
+ MFBT_API void update(const void* dataIn, uint32_t len);
+
+ /* Compute the final hash of all data into hashOut. */
+ MFBT_API void finish(SHA1Sum::Hash& hashOut);
+};
+
+} /* namespace mozilla */
+
+#endif /* mozilla_SHA1_h_ */
diff --git a/mfbt/STYLE b/mfbt/STYLE
new file mode 100644
index 0000000..2d94c3a
--- /dev/null
+++ b/mfbt/STYLE
@@ -0,0 +1,383 @@
+= mfbt style rules =
+
+== Line length ==
+
+The line limit is 80 characters, except that excessively long blocks of
+preprocessor directives may exceed this if it makes the code more readable (e.g.
+MOZ_STATIC_ASSERT in Assertions.h.), and unbreakable text in comments (e.g.
+URLs) may exceed this as well. Wrap expressions after binary operators.
+
+== Capitalization ==
+
+Standalone functions, classes, structs, and template parameters are named
+InterCaps-style. Member functions and fields in classes and structs are named
+camelCaps-style.
+
+== Indentation ==
+
+Indentation is two spaces, never tabs.
+
+ if (x == 2)
+ return 17;
+
+== Whitespace ==
+
+Surround binary operators with a single space on either side.
+
+ if (x == 2)
+ return 17;
+
+When describing pointer types, the * shall be adjacent to the type name. (Same
+goes for references -- & goes by the type name.)
+
+ int
+ Foo(int* p)
+ {
+ typedef void* VoidPtr;
+ int& i = *p;
+ }
+
+A corollary: don't mix declaration types by declaring a T and a T* (or a T**,
+&c.) in the same declaration.
+
+ T* foo, bar; // BAD
+
+== Expressions ==
+
+Ternary expressions (a ? b : c) should use only one line if sufficiently short.
+Longer ternary expressions should use multiple lines. The condition,
+consequent, and alternative should each be on separate lines (each part
+overflowing to additional lines as necessary), and the ? and : should be aligned
+with the start of the condition:
+
+ size_t
+ BinaryTree::height()
+ {
+ return isLeaf()
+ ? 0
+ : 1 + std::max(left()->height(),
+ right()->height());
+ }
+
+== Bracing ==
+
+Don't brace single statements.
+
+ if (y == 7)
+ return 3;
+ for (size_t i = 0; i < 5; i++)
+ frob(i);
+
+But do brace them if the statement (or condition(s) or any additional
+consequents, if the braces would be associated with an if statement) occupies
+multiple lines.
+
+ if (cond1 ||
+ cond2)
+ {
+ action();
+ }
+ if (cond1) {
+ consequent();
+ } else {
+ alternative(arg1,
+ arg2);
+ }
+ if (cond1 || cond2) {
+ callMethod(arg1,
+ arg2);
+ }
+ for (size_t j = 0;
+ j < 17;
+ j++)
+ {
+ action();
+ }
+
+Braces in control flow go at the end of the line except when associated with an
+|if| or loop-head where the condition covers multiple lines
+
+== Classes and structs ==
+
+Inside class and structure definitions, public/private consume one level of
+indentation.
+
+ class Baz
+ {
+ public:
+ Baz() { }
+ };
+
+The absence of public/private in structs in which all members are public still
+consumes a level.
+
+ struct Foo
+ {
+ int field;
+ };
+
+Braces delimiting a class or struct go on their own lines.
+
+Member initialization in constructors should be formatted as follows:
+
+ class Fnord
+ {
+ size_t s1, s2, s3, s4, s5;
+
+ public:
+ Fnord(size_t s) : s1(s), s2(s), s3(s), s4(s), s5(s) { }
+ Fnord()
+ : s1(0), /* member initialization can be compressed if desired */
+ s2(0),
+ s3(0),
+ s4(0),
+ s5(0)
+ {
+ ...
+ }
+ };
+
+Fields should go first in the class so that the basic structure is all in one
+place, consistently.
+
+Use the inline keyword to annotate functions defined inline in a header. (If
+the function is defined inline in the class, don't bother adding it
+redundantly.)
+
+Explicitly delete (using Attributes.h's MOZ_DELETE) the copy constructor and
+assignment operator from classes not intended to be copied or assigned to avoid
+mistakes.
+
+ class Funky
+ {
+ public:
+ Funky() { }
+
+ private:
+ Funky(const Funky& other) MOZ_DELETE;
+ void operator=(const Funky& other) MOZ_DELETE;
+ };
+
+Include a blank line between sections of structs and classes with different
+access control.
+
+The "get" prefix is used when a method is fallible. If it's infallible, don't
+use it.
+
+ class String
+ {
+ public:
+ size_t length() const; // not getLength()
+ };
+
+== Templates ==
+
+Capitalize template parameter names to distinguish them from fields.
+
+ template<size_t KeySize, typename T>
+ class BloomFilter
+ {
+ };
+
+Use single-letter names if it makes sense (T for an arbitrary type, K for key
+type, V for value type, &c.). Otherwise use InterCaps-style names.
+
+When declaring or defining a function, template<...> goes on one line, the
+return type and other specifiers go on another line, and the function name and
+argument list go on a third line.
+
+ template<typename T>
+ inline bool
+ Vector::add(T t)
+ {
+ }
+
+== Namespaces ==
+
+All C++ code shall be in the mozilla namespace, except that functionality only
+used to implement external-facing API should be in the mozilla::detail
+namespace, indicating that it should not be directly used.
+
+Namespace opening braces go on the same line as the namespace declaration.
+Namespace closing braces shall be commented. Namespace contents are not
+indented.
+
+ namespace mozilla {
+ ...
+ } // namespace mozilla
+
+Don't use |using| in a header unless it's confined to a class or method.
+Implementation files for out-of-line functionality may use |using|.
+
+Name data structures and methods which must be usable in C code with a Moz*
+prefix, e.g. MozCustomStructure. If the data structure is not meant to be used
+outside of the header in which it is found (i.e. it would be in mozilla::detail
+but for its being required to work in C code), add a corresponding comment to
+highlight this.
+
+== #includes ==
+
+Headers that include mfbt headers use a fully-qualified include path, even if
+full qualification is not strictly necessary.
+
+ #include "mozilla/Assertions.h"
+
+mfbt headers should be included first, alphabetically. Standard includes should
+follow, separated from mfbt includes by a blank line.
+
+ #include "mozilla/Assertions.h"
+ #include "mozilla/Attributes.h"
+
+ #include <string.h>
+
+If a header dependency is limited simply to the existence of a class,
+forward-declare it rather than #include that header.
+
+ namespace mozilla {
+
+ class BloomFilter;
+ extern bool
+ Test(BloomFilter* bf);
+
+ } // namespace mozilla
+
+== Preprocessor ==
+
+Include guards should be named by determining the fully-qualified include path,
+then substituting _ for / and . in it, and finally appending a trailing _. For
+example, "mozilla/Assertions.h" becomes mozilla_Assertions_h_.
+
+Nested preprocessor directives indent the directive name (but not the #) by two
+spaces.
+
+ #ifdef __clang__
+ # define FOO ...
+ #else
+ # define FOO ...
+ #endif
+
+Comments within nested preprocessor directives align with directive names at
+that nesting depth.
+
+ #if defined(__GNUC__)
+ /* gcc supports C++11 override syntax. */
+ # define MOZ_OVERRIDE override
+ #else
+ # define MOZ_OVERRIDE /* unsupported */
+ #endif
+
+Feature-testing macros may be defined to nothing. Macros intended to be
+textually expanded should be defined to a comment indicating non-support, as
+above or as appropriate to the situation.
+
+No particular preference is expressed between testing for a macro being defined
+using defined(...) and using #ifdef.
+
+When defining a macro with different expansions for different compilers, the top
+level of distinction should be the compiler, and the next nested level should be
+the compiler version. Clang seems likely to be around for awhile, so to reduce
+confusion test for it separately from gcc even when it's not strictly necessary.
+
+ #if defined(__clang__)
+ #elif defined(__GNUC__)
+ # if __GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6)
+ # else
+ # endif
+ #elif defined(_MSC_VER)
+ #endif
+
+But don't distinguish clang's feature support using version checks: use the
+__has_feature() and __has_extension() macros instead, because vendors may
+customize clang's version numbers.
+
+Use a MOZ_* prefix when defining macros (e.g. MOZ_OVERRIDE, MOZ_LIKELY, and so
+on) that are part of the mfbt interface. (C++ implementation files implementing
+mfbt's interface but which are not directly part of that interface may ignore
+this rule.)
+
+Prefer inline functions to macros whenever possible.
+
+== Comments ==
+
+Header files shall have a short descriptive comment underneath license
+boilerplate indicating what functionality the file implements, to be picked up
+by MXR and displayed in directory listings. (But see bug 717196, which
+currently prevents MXR from doing this if the MPL2 boilerplate is used.)
+
+ Assertions.h:
+ ...license boilerplate...
+
+ /* Implementations of runtime and static assertion macros for C and C++. */
+
+Classes intended for public use shall have interface comments explaining their
+functionality from the user's perspective. These comments shall include
+examples of how the relevant functionality might be used. These interface
+comments use /** */ doxygen/Javadoc-style comments.
+
+ /**
+ * The Frobber class simplifies the process of frobbing.
+ */
+ class Frobber
+ {
+ };
+
+Comments describing implementation details (tradeoffs considered, assumptions
+made, mathematical background, &c.) occur separately from interface comments so
+that users need not consider them. They should go inside the class definition
+or inside the appropriate method, depending on the specificity of the comment.
+
+Headers which are intended to be C-compatible shall use only /**/-style
+comments. (Code examples nested inside documentation comments may use //-style
+comments.) Headers which are C++-compatible may also use //-style comments.
+
+Non-interface comments that are /**/-style shall not also be doxygen-style.
+
+Use Python-style ** to denote exponentiation inside comments, not ^ (which can
+be confused with C-style bitwise xor). If you're writing sufficiently complex
+math, feel free to descend into LaTeX math mode ;-) inside implementation
+comments if you need to. (But keep it out of interface comments, because most
+people probably haven't seen LaTeX.)
+
+== Miscellaneous ==
+
+Enclose C-compatible code in |extern "C"| blocks, and #ifdef __cplusplus the
+block start/end as needed. The contents of these blocks should not be indented.
+
+Add new functionality to new headers unless an existing header makes sense.
+Err on the side of more headers rather than fewer, as this helps to minimize
+dependencies. Don't add anything to Util.h, which will be split into multiple
+headers at some point (bug 713082).
+
+Don't use bool for argument types unless the method is a "set" or "enable"-style
+method where the method name and bool value together indicate the sense of its
+effect. Use well-named enums in all other places, so that the semantics of the
+argument are clear at a glance and do not require knowing how the method
+interprets that argument.
+
+ void
+ setVisible(bool visible); // true clearly means visible, false clearly not
+ enum Enumerability {
+ Enumerable,
+ NonEnumerable
+ };
+ bool
+ DefineProperty(JSObject* obj, const char* name, Value v, Enumerability e);
+
+Use NULL for the null pointer constant.
+
+If a consequent in an if-statement ends with a return, don't specify an else.
+The else would be redundant with the return, and not using it avoids excess
+indentation. If you feel the if-else alternation is important as a way to
+think about the choice being made, consider a ternary expression instead.
+
+ // BAD
+ if (f())
+ return 2;
+ else
+ return 5;
+ // GOOD
+ if (f())
+ return 2;
+ return 5;
+ // GOOD
+ return f() ? 2 : 5
diff --git a/mfbt/Scoped.h b/mfbt/Scoped.h
new file mode 100644
index 0000000..677a1a3
--- /dev/null
+++ b/mfbt/Scoped.h
@@ -0,0 +1,271 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+/* A number of structures to simplify scope-based RAII management. */
+
+#ifndef mozilla_Scoped_h_
+#define mozilla_Scoped_h_
+
+/*
+ * Resource Acquisition Is Initialization is a programming idiom used
+ * to write robust code that is able to deallocate resources properly,
+ * even in presence of execution errors or exceptions that need to be
+ * propagated. The Scoped* classes defined in this header perform the
+ * deallocation of the resource they hold once program execution
+ * reaches the end of the scope for which they have been defined.
+ *
+ * This header provides the following RAII classes:
+ *
+ * - |ScopedFreePtr| - a container for a pointer, that automatically calls
+ * |free()| at the end of the scope;
+ * - |ScopedDeletePtr| - a container for a pointer, that automatically calls
+ * |delete| at the end of the scope;
+ * - |ScopedDeleteArray| - a container for a pointer to an array, that
+ * automatically calls |delete[]| at the end of the scope.
+ *
+ * The general scenario for each of the RAII classes is the following:
+ *
+ * ScopedClass foo(create_value());
+ * // ... In this scope, |foo| is defined. Use |foo.get()| or |foo.rwget()|
+ * to access the value.
+ * // ... In case of |return| or |throw|, |foo| is deallocated automatically.
+ * // ... If |foo| needs to be returned or stored, use |foo.forget()|
+ *
+ * Note that the RAII classes defined in this header do _not_ perform any form
+ * of reference-counting or garbage-collection. These classes have exactly two
+ * behaviors:
+ *
+ * - if |forget()| has not been called, the resource is always deallocated at
+ * the end of the scope;
+ * - if |forget()| has been called, any control on the resource is unbound
+ * and the resource is not deallocated by the class.
+ *
+ * Extension:
+ *
+ * In addition, this header provides class |Scoped| and macros |SCOPED_TEMPLATE|
+ * and |MOZ_TYPE_SPECIFIC_SCOPED_POINTER_TEMPLATE| to simplify the definition
+ * of RAII classes for other scenarios. These macros have been used to
+ * automatically close file descriptors/file handles when reaching the end of
+ * the scope, graphics contexts, etc.
+ */
+
+#include "mozilla/Attributes.h"
+#include "mozilla/GuardObjects.h"
+
+namespace mozilla {
+
+/*
+ * Scoped is a helper to create RAII wrappers
+ * Type argument |Traits| is expected to have the following structure:
+ *
+ * struct Traits {
+ * // Define the type of the value stored in the wrapper
+ * typedef value_type type;
+ * // Returns the value corresponding to the uninitialized or freed state
+ * const static type empty();
+ * // Release resources corresponding to the wrapped value
+ * // This function is responsible for not releasing an |empty| value
+ * const static void release(type);
+ * }
+ */
+template<typename Traits>
+class Scoped
+{
+ public:
+ typedef typename Traits::type Resource;
+
+ explicit Scoped(MOZ_GUARD_OBJECT_NOTIFIER_ONLY_PARAM)
+ : value(Traits::empty())
+ {
+ MOZ_GUARD_OBJECT_NOTIFIER_INIT;
+ }
+ explicit Scoped(const Resource& v
+ MOZ_GUARD_OBJECT_NOTIFIER_PARAM)
+ : value(v)
+ {
+ MOZ_GUARD_OBJECT_NOTIFIER_INIT;
+ }
+ ~Scoped() {
+ Traits::release(value);
+ }
+
+ // Constant getter
+ operator const Resource&() const { return value; }
+ const Resource& operator->() const { return value; }
+ const Resource& get() const { return value; }
+ // Non-constant getter.
+ Resource& rwget() { return value; }
+
+ /*
+ * Forget the resource.
+ *
+ * Once |forget| has been called, the |Scoped| is neutralized, i.e. it will
+ * have no effect at destruction (unless it is reset to another resource by
+ * |operator=|).
+ *
+ * @return The original resource.
+ */
+ Resource forget() {
+ Resource tmp = value;
+ value = Traits::empty();
+ return tmp;
+ }
+
+ /*
+ * Perform immediate clean-up of this |Scoped|.
+ *
+ * If this |Scoped| is currently empty, this method has no effect.
+ */
+ void dispose() {
+ Traits::release(value);
+ value = Traits::empty();
+ }
+
+ bool operator==(const Resource& other) const {
+ return value == other;
+ }
+
+ /*
+ * Replace the resource with another resource.
+ *
+ * Calling |operator=| has the side-effect of triggering clean-up. If you do
+ * not want to trigger clean-up, you should first invoke |forget|.
+ *
+ * @return this
+ */
+ Scoped<Traits>& operator=(const Resource& other) {
+ return reset(other);
+ }
+ Scoped<Traits>& reset(const Resource& other) {
+ Traits::release(value);
+ value = other;
+ return *this;
+ }
+
+ private:
+ explicit Scoped(const Scoped<Traits>& value) MOZ_DELETE;
+ Scoped<Traits>& operator=(const Scoped<Traits>& value) MOZ_DELETE;
+
+ private:
+ Resource value;
+ MOZ_DECL_USE_GUARD_OBJECT_NOTIFIER
+};
+
+/*
+ * SCOPED_TEMPLATE defines a templated class derived from Scoped
+ * This allows to implement templates such as ScopedFreePtr.
+ *
+ * @param name The name of the class to define.
+ * @param Traits A struct implementing clean-up. See the implementations
+ * for more details.
+ */
+#define SCOPED_TEMPLATE(name, Traits) \
+template<typename Type> \
+struct name : public mozilla::Scoped<Traits<Type> > \
+{ \
+ typedef mozilla::Scoped<Traits<Type> > Super; \
+ typedef typename Super::Resource Resource; \
+ name& operator=(Resource ptr) { \
+ Super::operator=(ptr); \
+ return *this; \
+ } \
+ explicit name(MOZ_GUARD_OBJECT_NOTIFIER_ONLY_PARAM) \
+ : Super(MOZ_GUARD_OBJECT_NOTIFIER_ONLY_PARAM_TO_PARENT) \
+ {} \
+ explicit name(Resource ptr \
+ MOZ_GUARD_OBJECT_NOTIFIER_PARAM) \
+ : Super(ptr MOZ_GUARD_OBJECT_NOTIFIER_PARAM_TO_PARENT) \
+ {} \
+ private: \
+ explicit name(name& source) MOZ_DELETE; \
+ name& operator=(name& source) MOZ_DELETE; \
+};
+
+/*
+ * ScopedFreePtr is a RAII wrapper for pointers that need to be free()d.
+ *
+ * struct S { ... };
+ * ScopedFreePtr<S> foo = malloc(sizeof(S));
+ * ScopedFreePtr<char> bar = strdup(str);
+ */
+template<typename T>
+struct ScopedFreePtrTraits
+{
+ typedef T* type;
+ static T* empty() { return NULL; }
+ static void release(T* ptr) { free(ptr); }
+};
+SCOPED_TEMPLATE(ScopedFreePtr, ScopedFreePtrTraits)
+
+/*
+ * ScopedDeletePtr is a RAII wrapper for pointers that need to be deleted.
+ *
+ * struct S { ... };
+ * ScopedDeletePtr<S> foo = new S();
+ */
+template<typename T>
+struct ScopedDeletePtrTraits : public ScopedFreePtrTraits<T>
+{
+ static void release(T* ptr) { delete ptr; }
+};
+SCOPED_TEMPLATE(ScopedDeletePtr, ScopedDeletePtrTraits)
+
+/*
+ * ScopedDeleteArray is a RAII wrapper for pointers that need to be delete[]ed.
+ *
+ * struct S { ... };
+ * ScopedDeleteArray<S> foo = new S[42];
+ */
+template<typename T>
+struct ScopedDeleteArrayTraits : public ScopedFreePtrTraits<T>
+{
+ static void release(T* ptr) { delete [] ptr; }
+};
+SCOPED_TEMPLATE(ScopedDeleteArray, ScopedDeleteArrayTraits)
+
+/*
+ * MOZ_TYPE_SPECIFIC_SCOPED_POINTER_TEMPLATE makes it easy to create scoped
+ * pointers for types with custom deleters; just overload
+ * TypeSpecificDelete(T*) in the same namespace as T to call the deleter for
+ * type T.
+ *
+ * @param name The name of the class to define.
+ * @param Type A struct implementing clean-up. See the implementations
+ * for more details.
+ * *param Deleter The function that is used to delete/destroy/free a
+ * non-null value of Type*.
+ *
+ * Example:
+ *
+ * MOZ_TYPE_SPECIFIC_SCOPED_POINTER_TEMPLATE(ScopedPRFileDesc, PRFileDesc, \
+ * PR_Close)
+ * ...
+ * {
+ * ScopedPRFileDesc file(PR_OpenFile(...));
+ * ...
+ * } // file is closed with PR_Close here
+ */
+#define MOZ_TYPE_SPECIFIC_SCOPED_POINTER_TEMPLATE(name, Type, Deleter) \
+template <> inline void TypeSpecificDelete(Type * value) { Deleter(value); } \
+typedef ::mozilla::TypeSpecificScopedPointer<Type> name;
+
+template <typename T> void TypeSpecificDelete(T * value);
+
+template <typename T>
+struct TypeSpecificScopedPointerTraits
+{
+ typedef T* type;
+ const static type empty() { return NULL; }
+ const static void release(type value)
+ {
+ if (value)
+ TypeSpecificDelete(value);
+ }
+};
+
+SCOPED_TEMPLATE(TypeSpecificScopedPointer, TypeSpecificScopedPointerTraits)
+
+} /* namespace mozilla */
+
+#endif // mozilla_Scoped_h_
diff --git a/mfbt/SplayTree.h b/mfbt/SplayTree.h
new file mode 100644
index 0000000..f9a10d3
--- /dev/null
+++ b/mfbt/SplayTree.h
@@ -0,0 +1,285 @@
+/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
+ * vim: set ts=8 sw=4 et tw=99 ft=cpp:
+ *
+ * This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+/**
+ * A sorted tree with optimal access times, where recently-accessed elements
+ * are faster to access again.
+ */
+
+#ifndef mozilla_SplayTree_h_
+#define mozilla_SplayTree_h_
+
+#include "mozilla/Assertions.h"
+#include "mozilla/NullPtr.h"
+
+namespace mozilla {
+
+template<class T, class C>
+class SplayTree;
+
+template<typename T>
+class SplayTreeNode
+{
+ public:
+ template<class A, class B>
+ friend class SplayTree;
+
+ SplayTreeNode()
+ : left(nullptr), right(nullptr), parent(nullptr)
+ {}
+
+ private:
+ T* left;
+ T* right;
+ T* parent;
+};
+
+
+/**
+ * Class which represents a splay tree.
+ * Splay trees are balanced binary search trees for which search, insert and
+ * remove are all amortized O(log n), but where accessing a node makes it
+ * faster to access that node in the future.
+ *
+ * T indicates the type of tree elements, Comparator must have a static
+ * compare(const T&, const T&) method ordering the elements. The compare
+ * method must be free from side effects.
+ */
+template<typename T, class Comparator>
+class SplayTree
+{
+ T* root;
+ T* freeList;
+
+ public:
+ SplayTree()
+ : root(nullptr), freeList(nullptr)
+ {}
+
+ bool empty() const {
+ return !root;
+ }
+
+ bool contains(const T& v)
+ {
+ if (empty())
+ return false;
+
+ T* last = lookup(v);
+ splay(last);
+ checkCoherency(root, nullptr);
+ return Comparator::compare(v, *last) == 0;
+ }
+
+ bool insert(T* v)
+ {
+ MOZ_ASSERT(!contains(*v), "Duplicate elements are not allowed.");
+
+ if (!root) {
+ root = v;
+ return true;
+ }
+ T* last = lookup(*v);
+ int cmp = Comparator::compare(*v, *last);
+
+ T** parentPointer = (cmp < 0) ? &last->left : &last->right;
+ MOZ_ASSERT(!*parentPointer);
+ *parentPointer = v;
+ v->parent = last;
+
+ splay(v);
+ checkCoherency(root, nullptr);
+ return true;
+ }
+
+ T* remove(const T& v)
+ {
+ T* last = lookup(v);
+ MOZ_ASSERT(last, "This tree must contain the element being removed.");
+ MOZ_ASSERT(Comparator::compare(v, *last) == 0);
+
+ // Splay the tree so that the item to remove is the root.
+ splay(last);
+ MOZ_ASSERT(last == root);
+
+ // Find another node which can be swapped in for the root: either the
+ // rightmost child of the root's left, or the leftmost child of the
+ // root's right.
+ T* swap;
+ T* swapChild;
+ if (root->left) {
+ swap = root->left;
+ while (swap->right)
+ swap = swap->right;
+ swapChild = swap->left;
+ } else if (root->right) {
+ swap = root->right;
+ while (swap->left)
+ swap = swap->left;
+ swapChild = swap->right;
+ } else {
+ T* result = root;
+ root = nullptr;
+ return result;
+ }
+
+ // The selected node has at most one child, in swapChild. Detach it
+ // from the subtree by replacing it with that child.
+ if (swap == swap->parent->left)
+ swap->parent->left = swapChild;
+ else
+ swap->parent->right = swapChild;
+ if (swapChild)
+ swapChild->parent = swap->parent;
+
+ // Make the selected node the new root.
+ root = swap;
+ root->parent = nullptr;
+ root->left = last->left;
+ root->right = last->right;
+ if (root->left) {
+ root->left->parent = root;
+ }
+ if (root->right) {
+ root->right->parent = root;
+ }
+
+ checkCoherency(root, nullptr);
+ return last;
+ }
+
+ T* removeMin()
+ {
+ MOZ_ASSERT(root, "No min to remove!");
+
+ T* min = root;
+ while (min->left)
+ min = min->left;
+ return remove(*min);
+ }
+
+ private:
+ /**
+ * Returns the node in this comparing equal to |v|, or a node just greater or
+ * just less than |v| if there is no such node.
+ */
+ T* lookup(const T& v)
+ {
+ MOZ_ASSERT(!empty());
+
+ T* node = root;
+ T* parent;
+ do {
+ parent = node;
+ int c = Comparator::compare(v, *node);
+ if (c == 0)
+ return node;
+ else if (c < 0)
+ node = node->left;
+ else
+ node = node->right;
+ } while (node);
+ return parent;
+ }
+
+ /**
+ * Rotate the tree until |node| is at the root of the tree. Performing
+ * the rotations in this fashion preserves the amortized balancing of
+ * the tree.
+ */
+ void splay(T* node)
+ {
+ MOZ_ASSERT(node);
+
+ while (node != root) {
+ T* parent = node->parent;
+ if (parent == root) {
+ // Zig rotation.
+ rotate(node);
+ MOZ_ASSERT(node == root);
+ return;
+ }
+ T* grandparent = parent->parent;
+ if ((parent->left == node) == (grandparent->left == parent)) {
+ // Zig-zig rotation.
+ rotate(parent);
+ rotate(node);
+ } else {
+ // Zig-zag rotation.
+ rotate(node);
+ rotate(node);
+ }
+ }
+ }
+
+ void rotate(T* node)
+ {
+ // Rearrange nodes so that node becomes the parent of its current
+ // parent, while preserving the sortedness of the tree.
+ T* parent = node->parent;
+ if (parent->left == node) {
+ // x y
+ // y c ==> a x
+ // a b b c
+ parent->left = node->right;
+ if (node->right)
+ node->right->parent = parent;
+ node->right = parent;
+ } else {
+ MOZ_ASSERT(parent->right == node);
+ // x y
+ // a y ==> x c
+ // b c a b
+ parent->right = node->left;
+ if (node->left)
+ node->left->parent = parent;
+ node->left = parent;
+ }
+ node->parent = parent->parent;
+ parent->parent = node;
+ if (T* grandparent = node->parent) {
+ if (grandparent->left == parent)
+ grandparent->left = node;
+ else
+ grandparent->right = node;
+ } else {
+ root = node;
+ }
+ }
+
+ T* checkCoherency(T* node, T* minimum)
+ {
+#ifdef DEBUG
+ MOZ_ASSERT_IF(root, !root->parent);
+ if (!node) {
+ MOZ_ASSERT(!root);
+ return nullptr;
+ }
+ MOZ_ASSERT_IF(!node->parent, node == root);
+ MOZ_ASSERT_IF(minimum, Comparator::compare(*minimum, *node) < 0);
+ if (node->left) {
+ MOZ_ASSERT(node->left->parent == node);
+ T* leftMaximum = checkCoherency(node->left, minimum);
+ MOZ_ASSERT(Comparator::compare(*leftMaximum, *node) < 0);
+ }
+ if (node->right) {
+ MOZ_ASSERT(node->right->parent == node);
+ return checkCoherency(node->right, node);
+ }
+ return node;
+#else
+ return nullptr;
+#endif
+ }
+
+ SplayTree(const SplayTree&) MOZ_DELETE;
+ void operator=(const SplayTree&) MOZ_DELETE;
+};
+
+} /* namespace mozilla */
+
+#endif /* mozilla_SplayTree_h_ */
diff --git a/mfbt/StandardInteger.h b/mfbt/StandardInteger.h
new file mode 100644
index 0000000..8e4c857
--- /dev/null
+++ b/mfbt/StandardInteger.h
@@ -0,0 +1,43 @@
+/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+/* Implements the C99 <stdint.h> interface for C and C++ code. */
+
+#ifndef mozilla_StandardInteger_h_
+#define mozilla_StandardInteger_h_
+
+/*
+ * The C99 standard header <stdint.h> exposes typedefs for common fixed-width
+ * integer types. It would be feasible to simply #include <stdint.h>, but
+ * MSVC++ versions prior to 2010 don't provide <stdint.h>. We could solve this
+ * by reimplementing <stdint.h> for MSVC++ 2008 and earlier. But then we reach
+ * a second problem: our custom <stdint.h> might conflict with a <stdint.h>
+ * defined by an embedder already looking to work around the MSVC++ <stdint.h>
+ * absence.
+ *
+ * We address these issues in this manner:
+ *
+ * 1. If the preprocessor macro MOZ_CUSTOM_STDINT_H is defined to a path to a
+ * custom <stdint.h> implementation, we will #include it. Embedders using
+ * a custom <stdint.h> must define this macro to an implementation that
+ * will work with their embedding.
+ * 2. Otherwise, if we are compiling with a an MSVC++ version without
+ * <stdint.h>, #include our custom <stdint.h> reimplementation.
+ * 3. Otherwise, #include the standard <stdint.h> provided by the compiler.
+ *
+ * Note that we can't call this file "stdint.h" or something case-insensitively
+ * equal to "stdint.h" because then MSVC (and other compilers on
+ * case-insensitive file systems) will include this file, rather than the system
+ * stdint.h, when we ask for <stdint.h> below.
+ */
+#if defined(MOZ_CUSTOM_STDINT_H)
+# include MOZ_CUSTOM_STDINT_H
+#elif defined(_MSC_VER) && _MSC_VER < 1600
+# include "mozilla/MSStdInt.h"
+#else
+# include <stdint.h>
+#endif
+
+#endif /* mozilla_StandardInteger_h_ */
diff --git a/mfbt/ThreadLocal.h b/mfbt/ThreadLocal.h
new file mode 100644
index 0000000..2b4eb30
--- /dev/null
+++ b/mfbt/ThreadLocal.h
@@ -0,0 +1,147 @@
+/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+/* Cross-platform lightweight thread local data wrappers. */
+
+#ifndef mozilla_ThreadLocal_h_
+#define mozilla_ThreadLocal_h_
+
+#if defined(XP_WIN)
+// This file will get included in any file that wants to add a profiler mark.
+// In order to not bring <windows.h> together we could include windef.h and
+// winbase.h which are sufficient to get the prototypes for the Tls* functions.
+// # include <windef.h>
+// # include <winbase.h>
+// Unfortunately, even including these headers causes us to add a bunch of ugly
+// stuff to our namespace e.g #define CreateEvent CreateEventW
+extern "C" {
+__declspec(dllimport) void* __stdcall TlsGetValue(unsigned long);
+__declspec(dllimport) int __stdcall TlsSetValue(unsigned long, void*);
+__declspec(dllimport) unsigned long __stdcall TlsAlloc();
+}
+#else
+# include <pthread.h>
+# include <signal.h>
+#endif
+
+#include "mozilla/Assertions.h"
+#include "mozilla/Attributes.h"
+
+namespace mozilla {
+
+// sig_safe_t denotes an atomic type which can be read or stored in a single
+// instruction. This means that data of this type is safe to be manipulated
+// from a signal handler, or other similar asynchronous execution contexts.
+#if defined(XP_WIN)
+typedef unsigned long sig_safe_t;
+#else
+typedef sig_atomic_t sig_safe_t;
+#endif
+
+/*
+ * Thread Local Storage helpers.
+ *
+ * Usage:
+ *
+ * Only static-storage-duration (e.g. global variables, or static class members)
+ * objects of this class should be instantiated. This class relies on
+ * zero-initialization, which is implicit for static-storage-duration objects.
+ * It doesn't have a custom default constructor, to avoid static initializers.
+ *
+ * API usage:
+ *
+ * // Create a TLS item
+ * mozilla::ThreadLocal<int> tlsKey;
+ * if (!tlsKey.init()) {
+ * // deal with the error
+ * }
+ *
+ * // Set the TLS value
+ * tlsKey.set(123);
+ *
+ * // Get the TLS value
+ * int value = tlsKey.get();
+ */
+template<typename T>
+class ThreadLocal
+{
+#if defined(XP_WIN)
+ typedef unsigned long key_t;
+#else
+ typedef pthread_key_t key_t;
+#endif
+
+ union Helper {
+ void* ptr;
+ T value;
+ };
+
+ public:
+ MOZ_WARN_UNUSED_RESULT inline bool init();
+
+ inline T get() const;
+
+ inline void set(const T value);
+
+ bool initialized() const {
+ return inited;
+ }
+
+ private:
+ key_t key;
+ bool inited;
+};
+
+template<typename T>
+inline bool
+ThreadLocal<T>::init()
+{
+ MOZ_STATIC_ASSERT(sizeof(T) <= sizeof(void*),
+ "mozilla::ThreadLocal can't be used for types larger than "
+ "a pointer");
+ MOZ_ASSERT(!initialized());
+#ifdef XP_WIN
+ key = TlsAlloc();
+ inited = key != 0xFFFFFFFFUL; // TLS_OUT_OF_INDEXES
+#else
+ inited = !pthread_key_create(&key, NULL);
+#endif
+ return inited;
+}
+
+template<typename T>
+inline T
+ThreadLocal<T>::get() const
+{
+ MOZ_ASSERT(initialized());
+ Helper h;
+#ifdef XP_WIN
+ h.ptr = TlsGetValue(key);
+#else
+ h.ptr = pthread_getspecific(key);
+#endif
+ return h.value;
+}
+
+template<typename T>
+inline void
+ThreadLocal<T>::set(const T value)
+{
+ MOZ_ASSERT(initialized());
+ Helper h;
+ h.value = value;
+ bool succeeded;
+#ifdef XP_WIN
+ succeeded = TlsSetValue(key, h.ptr);
+#else
+ succeeded = !pthread_setspecific(key, h.ptr);
+#endif
+ if (!succeeded)
+ MOZ_CRASH();
+}
+
+} // namespace mozilla
+
+#endif // mozilla_ThreadLocal_h_
diff --git a/mfbt/TypeTraits.h b/mfbt/TypeTraits.h
new file mode 100644
index 0000000..1a1f9cb
--- /dev/null
+++ b/mfbt/TypeTraits.h
@@ -0,0 +1,668 @@
+/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+/* Template-based metaprogramming and type-testing facilities. */
+
+#ifndef mozilla_TypeTraits_h_
+#define mozilla_TypeTraits_h_
+
+/*
+ * These traits are approximate copies of the traits and semantics from C++11's
+ * <type_traits> header. Don't add traits not in that header! When all
+ * platforms provide that header, we can convert all users and remove this one.
+ */
+
+#include <wchar.h>
+
+namespace mozilla {
+
+/* Forward declarations. */
+
+template<typename> struct RemoveCV;
+
+/* 20.9.3 Helper classes [meta.help] */
+
+/**
+ * Helper class used as a base for various type traits, exposed publicly
+ * because <type_traits> exposes it as well.
+ */
+template<typename T, T Value>
+struct IntegralConstant
+{
+ static const T value = Value;
+ typedef T ValueType;
+ typedef IntegralConstant<T, Value> Type;
+};
+
+/** Convenient aliases. */
+typedef IntegralConstant<bool, true> TrueType;
+typedef IntegralConstant<bool, false> FalseType;
+
+/* 20.9.4 Unary type traits [meta.unary] */
+
+/* 20.9.4.1 Primary type categories [meta.unary.cat] */
+
+namespace detail {
+
+template <typename T>
+struct IsIntegralHelper : FalseType {};
+
+template<> struct IsIntegralHelper<char> : TrueType {};
+template<> struct IsIntegralHelper<signed char> : TrueType {};
+template<> struct IsIntegralHelper<unsigned char> : TrueType {};
+template<> struct IsIntegralHelper<short> : TrueType {};
+template<> struct IsIntegralHelper<unsigned short> : TrueType {};
+template<> struct IsIntegralHelper<int> : TrueType {};
+template<> struct IsIntegralHelper<unsigned int> : TrueType {};
+template<> struct IsIntegralHelper<long> : TrueType {};
+template<> struct IsIntegralHelper<unsigned long> : TrueType {};
+template<> struct IsIntegralHelper<long long> : TrueType {};
+template<> struct IsIntegralHelper<unsigned long long> : TrueType {};
+template<> struct IsIntegralHelper<bool> : TrueType {};
+template<> struct IsIntegralHelper<wchar_t> : TrueType {};
+
+} /* namespace detail */
+
+/**
+ * IsIntegral determines whether a type is an integral type.
+ *
+ * mozilla::IsIntegral<int>::value is true;
+ * mozilla::IsIntegral<unsigned short>::value is true;
+ * mozilla::IsIntegral<const long>::value is true;
+ * mozilla::IsIntegral<int*>::value is false;
+ * mozilla::IsIntegral<double>::value is false;
+ *
+ * Note that the behavior of IsIntegral on char16_t and char32_t is
+ * unspecified.
+ */
+template<typename T>
+struct IsIntegral : detail::IsIntegralHelper<typename RemoveCV<T>::Type>
+{};
+
+template<typename T, typename U>
+struct IsSame;
+
+namespace detail {
+
+template<typename T>
+struct IsFloatingPointHelper
+ : IntegralConstant<bool,
+ IsSame<T, float>::value ||
+ IsSame<T, double>::value ||
+ IsSame<T, long double>::value>
+{};
+
+} // namespace detail
+
+/**
+ * IsFloatingPoint determines whether a type is a floating point type (float,
+ * double, long double).
+ *
+ * mozilla::IsFloatingPoint<int>::value is false;
+ * mozilla::IsFloatingPoint<const float>::value is true;
+ * mozilla::IsFloatingPoint<long double>::value is true;
+ * mozilla::IsFloatingPoint<double*>::value is false.
+ */
+template<typename T>
+struct IsFloatingPoint
+ : detail::IsFloatingPointHelper<typename RemoveCV<T>::Type>
+{};
+
+/**
+ * IsPointer determines whether a type is a pointer type (but not a pointer-to-
+ * member type).
+ *
+ * mozilla::IsPointer<struct S*>::value is true;
+ * mozilla::IsPointer<int**>::value is true;
+ * mozilla::IsPointer<void (*)(void)>::value is true;
+ * mozilla::IsPointer<int>::value is false;
+ * mozilla::IsPointer<struct S>::value is false.
+ */
+template<typename T>
+struct IsPointer : FalseType {};
+
+template<typename T>
+struct IsPointer<T*> : TrueType {};
+
+/* 20.9.4.2 Composite type traits [meta.unary.comp] */
+
+/**
+ * IsArithmetic determines whether a type is arithmetic. A type is arithmetic
+ * iff it is an integral type or a floating point type.
+ *
+ * mozilla::IsArithmetic<int>::value is true;
+ * mozilla::IsArithmetic<double>::value is true;
+ * mozilla::IsArithmetic<long double*>::value is false.
+ */
+template<typename T>
+struct IsArithmetic
+ : IntegralConstant<bool, IsIntegral<T>::value || IsFloatingPoint<T>::value>
+{};
+
+/* 20.9.4.3 Type properties [meta.unary.prop] */
+
+/**
+ * IsConst determines whether a type is const or not.
+ *
+ * mozilla::IsConst<int>::value is false;
+ * mozilla::IsConst<void* const>::value is true;
+ * mozilla::IsConst<const char*>::value is false.
+ */
+template<typename T>
+struct IsConst : FalseType {};
+
+template<typename T>
+struct IsConst<const T> : TrueType {};
+
+/**
+ * IsVolatile determines whether a type is volatile or not.
+ *
+ * mozilla::IsVolatile<int>::value is false;
+ * mozilla::IsVolatile<void* volatile>::value is true;
+ * mozilla::IsVolatile<volatile char*>::value is false.
+ */
+template<typename T>
+struct IsVolatile : FalseType {};
+
+template<typename T>
+struct IsVolatile<volatile T> : TrueType {};
+
+/**
+ * Traits class for identifying POD types. Until C++11 there's no automatic
+ * way to detect PODs, so for the moment this is done manually. Users may
+ * define specializations of this class that inherit from mozilla::TrueType and
+ * mozilla::FalseType (or equivalently mozilla::IntegralConstant<bool, true or
+ * false>, or conveniently from mozilla::IsPod for composite types) as needed to
+ * ensure correct IsPod behavior.
+ */
+template<typename T>
+struct IsPod : public FalseType {};
+
+template<> struct IsPod<char> : TrueType {};
+template<> struct IsPod<signed char> : TrueType {};
+template<> struct IsPod<unsigned char> : TrueType {};
+template<> struct IsPod<short> : TrueType {};
+template<> struct IsPod<unsigned short> : TrueType {};
+template<> struct IsPod<int> : TrueType {};
+template<> struct IsPod<unsigned int> : TrueType {};
+template<> struct IsPod<long> : TrueType {};
+template<> struct IsPod<unsigned long> : TrueType {};
+template<> struct IsPod<long long> : TrueType {};
+template<> struct IsPod<unsigned long long> : TrueType {};
+template<> struct IsPod<bool> : TrueType {};
+template<> struct IsPod<float> : TrueType {};
+template<> struct IsPod<double> : TrueType {};
+template<> struct IsPod<wchar_t> : TrueType {};
+template<typename T> struct IsPod<T*> : TrueType {};
+
+namespace detail {
+
+template<typename T, bool = IsFloatingPoint<T>::value>
+struct IsSignedHelper;
+
+template<typename T>
+struct IsSignedHelper<T, true> : TrueType {};
+
+template<typename T>
+struct IsSignedHelper<T, false>
+ : IntegralConstant<bool, IsArithmetic<T>::value && T(-1) < T(1)>
+{};
+
+} // namespace detail
+
+/**
+ * IsSigned determines whether a type is a signed arithmetic type. |char| is
+ * considered a signed type if it has the same representation as |signed char|.
+ *
+ * Don't use this if the type might be user-defined! You might or might not get
+ * a compile error, depending.
+ *
+ * mozilla::IsSigned<int>::value is true;
+ * mozilla::IsSigned<const unsigned int>::value is false;
+ * mozilla::IsSigned<unsigned char>::value is false;
+ * mozilla::IsSigned<float>::value is true.
+ */
+template<typename T>
+struct IsSigned : detail::IsSignedHelper<T> {};
+
+namespace detail {
+
+template<typename T, bool = IsFloatingPoint<T>::value>
+struct IsUnsignedHelper;
+
+template<typename T>
+struct IsUnsignedHelper<T, true> : FalseType {};
+
+template<typename T>
+struct IsUnsignedHelper<T, false>
+ : IntegralConstant<bool,
+ IsArithmetic<T>::value &&
+ (IsSame<typename RemoveCV<T>::Type, bool>::value ||
+ T(1) < T(-1))>
+{};
+
+} // namespace detail
+
+/**
+ * IsUnsigned determines whether a type is an unsigned arithmetic type.
+ *
+ * Don't use this if the type might be user-defined! You might or might not get
+ * a compile error, depending.
+ *
+ * mozilla::IsUnsigned<int>::value is false;
+ * mozilla::IsUnsigned<const unsigned int>::value is true;
+ * mozilla::IsUnsigned<unsigned char>::value is true;
+ * mozilla::IsUnsigned<float>::value is false.
+ */
+template<typename T>
+struct IsUnsigned : detail::IsUnsignedHelper<T> {};
+
+/* 20.9.5 Type property queries [meta.unary.prop.query] */
+
+/* 20.9.6 Relationships between types [meta.rel] */
+
+/**
+ * IsSame tests whether two types are the same type.
+ *
+ * mozilla::IsSame<int, int>::value is true;
+ * mozilla::IsSame<int*, int*>::value is true;
+ * mozilla::IsSame<int, unsigned int>::value is false;
+ * mozilla::IsSame<void, void>::value is true;
+ * mozilla::IsSame<const int, int>::value is false;
+ * mozilla::IsSame<struct S, struct S>::value is true.
+ */
+template<typename T, typename U>
+struct IsSame : FalseType {};
+
+template<typename T>
+struct IsSame<T, T> : TrueType {};
+
+namespace detail {
+
+// The trickery used to implement IsBaseOf here makes it possible to use it for
+// the cases of private and multiple inheritance. This code was inspired by the
+// sample code here:
+//
+// http://stackoverflow.com/questions/2910979/how-is-base-of-works
+template<class Base, class Derived>
+struct BaseOfHelper
+{
+ public:
+ operator Base*() const;
+ operator Derived*();
+};
+
+template<class Base, class Derived>
+struct BaseOfTester
+{
+ private:
+ template<class T>
+ static char test(Derived*, T);
+ static int test(Base*, int);
+
+ public:
+ static const bool value =
+ sizeof(test(BaseOfHelper<Base, Derived>(), int())) == sizeof(char);
+};
+
+template<class Base, class Derived>
+struct BaseOfTester<Base, const Derived>
+{
+ private:
+ template<class T>
+ static char test(Derived*, T);
+ static int test(Base*, int);
+
+ public:
+ static const bool value =
+ sizeof(test(BaseOfHelper<Base, Derived>(), int())) == sizeof(char);
+};
+
+template<class Base, class Derived>
+struct BaseOfTester<Base&, Derived&> : FalseType {};
+
+template<class Type>
+struct BaseOfTester<Type, Type> : TrueType {};
+
+template<class Type>
+struct BaseOfTester<Type, const Type> : TrueType {};
+
+} /* namespace detail */
+
+/*
+ * IsBaseOf allows to know whether a given class is derived from another.
+ *
+ * Consider the following class definitions:
+ *
+ * class A {};
+ * class B : public A {};
+ * class C {};
+ *
+ * mozilla::IsBaseOf<A, B>::value is true;
+ * mozilla::IsBaseOf<A, C>::value is false;
+ */
+template<class Base, class Derived>
+struct IsBaseOf
+ : IntegralConstant<bool, detail::BaseOfTester<Base, Derived>::value>
+{};
+
+namespace detail {
+
+template<typename From, typename To>
+struct ConvertibleTester
+{
+ private:
+ static From create();
+
+ template<typename From1, typename To1>
+ static char test(To to);
+
+ template<typename From1, typename To1>
+ static int test(...);
+
+ public:
+ static const bool value =
+ sizeof(test<From, To>(create())) == sizeof(char);
+};
+
+} // namespace detail
+
+/**
+ * IsConvertible determines whether a value of type From will implicitly convert
+ * to a value of type To. For example:
+ *
+ * struct A {};
+ * struct B : public A {};
+ * struct C {};
+ *
+ * mozilla::IsConvertible<A, A>::value is true;
+ * mozilla::IsConvertible<A*, A*>::value is true;
+ * mozilla::IsConvertible<B, A>::value is true;
+ * mozilla::IsConvertible<B*, A*>::value is true;
+ * mozilla::IsConvertible<C, A>::value is false;
+ * mozilla::IsConvertible<A, C>::value is false;
+ * mozilla::IsConvertible<A*, C*>::value is false;
+ * mozilla::IsConvertible<C*, A*>::value is false.
+ *
+ * For obscure reasons, you can't use IsConvertible when the types being tested
+ * are related through private inheritance, and you'll get a compile error if
+ * you try. Just don't do it!
+ */
+template<typename From, typename To>
+struct IsConvertible
+ : IntegralConstant<bool, detail::ConvertibleTester<From, To>::value>
+{};
+
+/* 20.9.7 Transformations between types [meta.trans] */
+
+/* 20.9.7.1 Const-volatile modifications [meta.trans.cv] */
+
+/**
+ * RemoveConst removes top-level const qualifications on a type.
+ *
+ * mozilla::RemoveConst<int>::Type is int;
+ * mozilla::RemoveConst<const int>::Type is int;
+ * mozilla::RemoveConst<const int*>::Type is const int*;
+ * mozilla::RemoveConst<int* const>::Type is int*.
+ */
+template<typename T>
+struct RemoveConst
+{
+ typedef T Type;
+};
+
+template<typename T>
+struct RemoveConst<const T>
+{
+ typedef T Type;
+};
+
+/**
+ * RemoveVolatile removes top-level volatile qualifications on a type.
+ *
+ * mozilla::RemoveVolatile<int>::Type is int;
+ * mozilla::RemoveVolatile<volatile int>::Type is int;
+ * mozilla::RemoveVolatile<volatile int*>::Type is volatile int*;
+ * mozilla::RemoveVolatile<int* volatile>::Type is int*.
+ */
+template<typename T>
+struct RemoveVolatile
+{
+ typedef T Type;
+};
+
+template<typename T>
+struct RemoveVolatile<volatile T>
+{
+ typedef T Type;
+};
+
+/**
+ * RemoveCV removes top-level const and volatile qualifications on a type.
+ *
+ * mozilla::RemoveCV<int>::Type is int;
+ * mozilla::RemoveCV<const int>::Type is int;
+ * mozilla::RemoveCV<volatile int>::Type is int;
+ * mozilla::RemoveCV<int* const volatile>::Type is int*.
+ */
+template<typename T>
+struct RemoveCV
+{
+ typedef typename RemoveConst<typename RemoveVolatile<T>::Type>::Type Type;
+};
+
+/* 20.9.7.2 Reference modifications [meta.trans.ref] */
+
+/* 20.9.7.3 Sign modifications [meta.trans.sign] */
+
+template<bool B, typename T = void>
+struct EnableIf;
+
+template<bool Condition, typename A, typename B>
+struct Conditional;
+
+namespace detail {
+
+template<bool MakeConst, typename T>
+struct WithC : Conditional<MakeConst, const T, T>
+{};
+
+template<bool MakeVolatile, typename T>
+struct WithV : Conditional<MakeVolatile, volatile T, T>
+{};
+
+
+template<bool MakeConst, bool MakeVolatile, typename T>
+struct WithCV : WithC<MakeConst, typename WithV<MakeVolatile, T>::Type>
+{};
+
+template<typename T>
+struct CorrespondingSigned;
+
+template<>
+struct CorrespondingSigned<char> { typedef signed char Type; };
+template<>
+struct CorrespondingSigned<unsigned char> { typedef signed char Type; };
+template<>
+struct CorrespondingSigned<unsigned short> { typedef short Type; };
+template<>
+struct CorrespondingSigned<unsigned int> { typedef int Type; };
+template<>
+struct CorrespondingSigned<unsigned long> { typedef long Type; };
+template<>
+struct CorrespondingSigned<unsigned long long> { typedef long long Type; };
+
+template<typename T,
+ typename CVRemoved = typename RemoveCV<T>::Type,
+ bool IsSignedIntegerType = IsSigned<CVRemoved>::value &&
+ !IsSame<char, CVRemoved>::value>
+struct MakeSigned;
+
+template<typename T, typename CVRemoved>
+struct MakeSigned<T, CVRemoved, true>
+{
+ typedef T Type;
+};
+
+template<typename T, typename CVRemoved>
+struct MakeSigned<T, CVRemoved, false>
+ : WithCV<IsConst<T>::value, IsVolatile<T>::value,
+ typename CorrespondingSigned<CVRemoved>::Type>
+{};
+
+} // namespace detail
+
+/**
+ * MakeSigned produces the corresponding signed integer type for a given
+ * integral type T, with the const/volatile qualifiers of T. T must be a
+ * possibly-const/volatile-qualified integral type that isn't bool.
+ *
+ * If T is already a signed integer type (not including char!), then T is
+ * produced.
+ *
+ * Otherwise, if T is an unsigned integer type, the signed variety of T, with
+ * T's const/volatile qualifiers, is produced.
+ *
+ * Otherwise, the integral type of the same size as T, with the lowest rank,
+ * with T's const/volatile qualifiers, is produced. (This basically only acts
+ * to produce signed char when T = char.)
+ *
+ * mozilla::MakeSigned<unsigned long>::Type is signed long;
+ * mozilla::MakeSigned<volatile int>::Type is volatile int;
+ * mozilla::MakeSigned<const unsigned short>::Type is const signed short;
+ * mozilla::MakeSigned<const char>::Type is const signed char;
+ * mozilla::MakeSigned<bool> is an error;
+ * mozilla::MakeSigned<void*> is an error.
+ */
+template<typename T>
+struct MakeSigned
+ : EnableIf<IsIntegral<T>::value && !IsSame<bool, typename RemoveCV<T>::Type>::value,
+ typename detail::MakeSigned<T>
+ >::Type
+{};
+
+namespace detail {
+
+template<typename T>
+struct CorrespondingUnsigned;
+
+template<>
+struct CorrespondingUnsigned<char> { typedef unsigned char Type; };
+template<>
+struct CorrespondingUnsigned<signed char> { typedef unsigned char Type; };
+template<>
+struct CorrespondingUnsigned<short> { typedef unsigned short Type; };
+template<>
+struct CorrespondingUnsigned<int> { typedef unsigned int Type; };
+template<>
+struct CorrespondingUnsigned<long> { typedef unsigned long Type; };
+template<>
+struct CorrespondingUnsigned<long long> { typedef unsigned long long Type; };
+
+
+template<typename T,
+ typename CVRemoved = typename RemoveCV<T>::Type,
+ bool IsUnsignedIntegerType = IsUnsigned<CVRemoved>::value &&
+ !IsSame<char, CVRemoved>::value>
+struct MakeUnsigned;
+
+template<typename T, typename CVRemoved>
+struct MakeUnsigned<T, CVRemoved, true>
+{
+ typedef T Type;
+};
+
+template<typename T, typename CVRemoved>
+struct MakeUnsigned<T, CVRemoved, false>
+ : WithCV<IsConst<T>::value, IsVolatile<T>::value,
+ typename CorrespondingUnsigned<CVRemoved>::Type>
+{};
+
+} // namespace detail
+
+/**
+ * MakeUnsigned produces the corresponding unsigned integer type for a given
+ * integral type T, with the const/volatile qualifiers of T. T must be a
+ * possibly-const/volatile-qualified integral type that isn't bool.
+ *
+ * If T is already an unsigned integer type (not including char!), then T is
+ * produced.
+ *
+ * Otherwise, if T is an signed integer type, the unsigned variety of T, with
+ * T's const/volatile qualifiers, is produced.
+ *
+ * Otherwise, the unsigned integral type of the same size as T, with the lowest
+ * rank, with T's const/volatile qualifiers, is produced. (This basically only
+ * acts to produce unsigned char when T = char.)
+ *
+ * mozilla::MakeUnsigned<signed long>::Type is unsigned long;
+ * mozilla::MakeUnsigned<volatile unsigned int>::Type is volatile unsigned int;
+ * mozilla::MakeUnsigned<const signed short>::Type is const unsigned short;
+ * mozilla::MakeUnsigned<const char>::Type is const unsigned char;
+ * mozilla::MakeUnsigned<bool> is an error;
+ * mozilla::MakeUnsigned<void*> is an error.
+ */
+template<typename T>
+struct MakeUnsigned
+ : EnableIf<IsIntegral<T>::value && !IsSame<bool, typename RemoveCV<T>::Type>::value,
+ typename detail::MakeUnsigned<T>
+ >::Type
+{};
+
+/* 20.9.7.4 Array modifications [meta.trans.arr] */
+
+/* 20.9.7.5 Pointer modifications [meta.trans.ptr] */
+
+/* 20.9.7.6 Other transformations [meta.trans.other] */
+
+/**
+ * EnableIf is a struct containing a typedef of T if and only if B is true.
+ *
+ * mozilla::EnableIf<true, int>::Type is int;
+ * mozilla::EnableIf<false, int>::Type is a compile-time error.
+ *
+ * Use this template to implement SFINAE-style (Substitution Failure Is not An
+ * Error) requirements. For example, you might use it to impose a restriction
+ * on a template parameter:
+ *
+ * template<typename T>
+ * class PodVector // vector optimized to store POD (memcpy-able) types
+ * {
+ * EnableIf<IsPod<T>::value, T>::Type* vector;
+ * size_t length;
+ * ...
+ * };
+ */
+template<bool B, typename T>
+struct EnableIf
+{};
+
+template<typename T>
+struct EnableIf<true, T>
+{
+ typedef T Type;
+};
+
+/**
+ * Conditional selects a class between two, depending on a given boolean value.
+ *
+ * mozilla::Conditional<true, A, B>::Type is A;
+ * mozilla::Conditional<false, A, B>::Type is B;
+ */
+template<bool Condition, typename A, typename B>
+struct Conditional
+{
+ typedef A Type;
+};
+
+template<class A, class B>
+struct Conditional<false, A, B>
+{
+ typedef B Type;
+};
+
+} /* namespace mozilla */
+
+#endif /* mozilla_TypeTraits_h_ */
diff --git a/mfbt/TypedEnum.h b/mfbt/TypedEnum.h
new file mode 100644
index 0000000..889960a
--- /dev/null
+++ b/mfbt/TypedEnum.h
@@ -0,0 +1,213 @@
+/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+/* Macros to emulate C++11 typed enums and enum classes. */
+
+#ifndef mozilla_TypedEnum_h_
+#define mozilla_TypedEnum_h_
+
+#include "mozilla/Attributes.h"
+
+#if defined(__cplusplus)
+
+#if defined(__clang__)
+ /*
+ * Per Clang documentation, "Note that marketing version numbers should not
+ * be used to check for language features, as different vendors use different
+ * numbering schemes. Instead, use the feature checking macros."
+ */
+# ifndef __has_extension
+# define __has_extension __has_feature /* compatibility, for older versions of clang */
+# endif
+# if __has_extension(cxx_strong_enums)
+# define MOZ_HAVE_CXX11_ENUM_TYPE
+# define MOZ_HAVE_CXX11_STRONG_ENUMS
+# endif
+#elif defined(__GNUC__)
+# if defined(__GXX_EXPERIMENTAL_CXX0X__) || __cplusplus >= 201103L
+# if MOZ_GCC_VERSION_AT_LEAST(4, 5, 1)
+# define MOZ_HAVE_CXX11_ENUM_TYPE
+# define MOZ_HAVE_CXX11_STRONG_ENUMS
+# endif
+# endif
+#elif defined(_MSC_VER)
+# if _MSC_VER >= 1400
+# define MOZ_HAVE_CXX11_ENUM_TYPE
+# endif
+# if _MSC_VER >= 1700
+# define MOZ_HAVE_CXX11_STRONG_ENUMS
+# endif
+#endif
+
+/**
+ * MOZ_ENUM_TYPE specifies the underlying numeric type for an enum. It's
+ * specified by placing MOZ_ENUM_TYPE(type) immediately after the enum name in
+ * its declaration, and before the opening curly brace, like
+ *
+ * enum MyEnum MOZ_ENUM_TYPE(uint16_t)
+ * {
+ * A,
+ * B = 7,
+ * C
+ * };
+ *
+ * In supporting compilers, the macro will expand to ": uint16_t". The
+ * compiler will allocate exactly two bytes for MyEnum and will require all
+ * enumerators to have values between 0 and 65535. (Thus specifying "B =
+ * 100000" instead of "B = 7" would fail to compile.) In old compilers the
+ * macro expands to the empty string, and the underlying type is generally
+ * undefined.
+ */
+#ifdef MOZ_HAVE_CXX11_ENUM_TYPE
+# define MOZ_ENUM_TYPE(type) : type
+#else
+# define MOZ_ENUM_TYPE(type) /* no support */
+#endif
+
+/**
+ * MOZ_BEGIN_ENUM_CLASS and MOZ_END_ENUM_CLASS provide access to the
+ * strongly-typed enumeration feature of C++11 ("enum class"). If supported
+ * by the compiler, an enum defined using these macros will not be implicitly
+ * converted to any other type, and its enumerators will be scoped using the
+ * enumeration name. Place MOZ_BEGIN_ENUM_CLASS(EnumName, type) in place of
+ * "enum EnumName {", and MOZ_END_ENUM_CLASS(EnumName) in place of the closing
+ * "};". For example,
+ *
+ * MOZ_BEGIN_ENUM_CLASS(Enum, int32_t)
+ * A,
+ * B = 6
+ * MOZ_END_ENUM_CLASS(Enum)
+ *
+ * This will make "Enum::A" and "Enum::B" appear in the global scope, but "A"
+ * and "B" will not. In compilers that support C++11 strongly-typed
+ * enumerations, implicit conversions of Enum values to numeric types will
+ * fail. In other compilers, Enum itself will actually be defined as a class,
+ * and some implicit conversions will fail while others will succeed.
+ *
+ * The type argument specifies the underlying type for the enum where
+ * supported, as with MOZ_ENUM_TYPE(). For simplicity, it is currently
+ * mandatory. As with MOZ_ENUM_TYPE(), it will do nothing on compilers that do
+ * not support it.
+ *
+ * Note that the workaround implemented here is not compatible with enums
+ * nested inside a class.
+ */
+#if defined(MOZ_HAVE_CXX11_STRONG_ENUMS)
+ /*
+ * All compilers that support strong enums also support an explicit
+ * underlying type, so no extra check is needed.
+ */
+# define MOZ_BEGIN_ENUM_CLASS(Name, type) enum class Name : type {
+# define MOZ_END_ENUM_CLASS(Name) };
+#else
+ /**
+ * We need Name to both name a type, and scope the provided enumerator
+ * names. Namespaces and classes both provide scoping, but namespaces
+ * aren't types, so we need to use a class that wraps the enum values. We
+ * have an implicit conversion from the inner enum type to the class, so
+ * statements like
+ *
+ * Enum x = Enum::A;
+ *
+ * will still work. We need to define an implicit conversion from the class
+ * to the inner enum as well, so that (for instance) switch statements will
+ * work. This means that the class can be implicitly converted to a numeric
+ * value as well via the enum type, since C++ allows an implicit
+ * user-defined conversion followed by a standard conversion to still be
+ * implicit.
+ *
+ * We have an explicit constructor from int defined, so that casts like
+ * (Enum)7 will still work. We also have a zero-argument constructor with
+ * no arguments, so declaration without initialization (like "Enum foo;")
+ * will work.
+ *
+ * Additionally, we'll delete as many operators as possible for the inner
+ * enum type, so statements like this will still fail:
+ *
+ * f(5 + Enum::B); // deleted operator+
+ *
+ * But we can't prevent things like this, because C++ doesn't allow
+ * overriding conversions or assignment operators for enums:
+ *
+ * int x = Enum::A;
+ * int f()
+ * {
+ * return Enum::A;
+ * }
+ */
+# define MOZ_BEGIN_ENUM_CLASS(Name, type) \
+ class Name \
+ { \
+ public: \
+ enum Enum MOZ_ENUM_TYPE(type) \
+ {
+# define MOZ_END_ENUM_CLASS(Name) \
+ }; \
+ Name() {} \
+ Name(Enum aEnum) : mEnum(aEnum) {} \
+ explicit Name(int num) : mEnum((Enum)num) {} \
+ operator Enum() const { return mEnum; } \
+ private: \
+ Enum mEnum; \
+ }; \
+ inline int operator+(const int&, const Name::Enum&) MOZ_DELETE; \
+ inline int operator+(const Name::Enum&, const int&) MOZ_DELETE; \
+ inline int operator-(const int&, const Name::Enum&) MOZ_DELETE; \
+ inline int operator-(const Name::Enum&, const int&) MOZ_DELETE; \
+ inline int operator*(const int&, const Name::Enum&) MOZ_DELETE; \
+ inline int operator*(const Name::Enum&, const int&) MOZ_DELETE; \
+ inline int operator/(const int&, const Name::Enum&) MOZ_DELETE; \
+ inline int operator/(const Name::Enum&, const int&) MOZ_DELETE; \
+ inline int operator%(const int&, const Name::Enum&) MOZ_DELETE; \
+ inline int operator%(const Name::Enum&, const int&) MOZ_DELETE; \
+ inline int operator+(const Name::Enum&) MOZ_DELETE; \
+ inline int operator-(const Name::Enum&) MOZ_DELETE; \
+ inline int& operator++(Name::Enum&) MOZ_DELETE; \
+ inline int operator++(Name::Enum&, int) MOZ_DELETE; \
+ inline int& operator--(Name::Enum&) MOZ_DELETE; \
+ inline int operator--(Name::Enum&, int) MOZ_DELETE; \
+ inline bool operator==(const int&, const Name::Enum&) MOZ_DELETE; \
+ inline bool operator==(const Name::Enum&, const int&) MOZ_DELETE; \
+ inline bool operator!=(const int&, const Name::Enum&) MOZ_DELETE; \
+ inline bool operator!=(const Name::Enum&, const int&) MOZ_DELETE; \
+ inline bool operator>(const int&, const Name::Enum&) MOZ_DELETE; \
+ inline bool operator>(const Name::Enum&, const int&) MOZ_DELETE; \
+ inline bool operator<(const int&, const Name::Enum&) MOZ_DELETE; \
+ inline bool operator<(const Name::Enum&, const int&) MOZ_DELETE; \
+ inline bool operator>=(const int&, const Name::Enum&) MOZ_DELETE; \
+ inline bool operator>=(const Name::Enum&, const int&) MOZ_DELETE; \
+ inline bool operator<=(const int&, const Name::Enum&) MOZ_DELETE; \
+ inline bool operator<=(const Name::Enum&, const int&) MOZ_DELETE; \
+ inline bool operator!(const Name::Enum&) MOZ_DELETE; \
+ inline bool operator&&(const bool&, const Name::Enum&) MOZ_DELETE; \
+ inline bool operator&&(const Name::Enum&, const bool&) MOZ_DELETE; \
+ inline bool operator||(const bool&, const Name::Enum&) MOZ_DELETE; \
+ inline bool operator||(const Name::Enum&, const bool&) MOZ_DELETE; \
+ inline int operator~(const Name::Enum&) MOZ_DELETE; \
+ inline int operator&(const int&, const Name::Enum&) MOZ_DELETE; \
+ inline int operator&(const Name::Enum&, const int&) MOZ_DELETE; \
+ inline int operator|(const int&, const Name::Enum&) MOZ_DELETE; \
+ inline int operator|(const Name::Enum&, const int&) MOZ_DELETE; \
+ inline int operator^(const int&, const Name::Enum&) MOZ_DELETE; \
+ inline int operator^(const Name::Enum&, const int&) MOZ_DELETE; \
+ inline int operator<<(const int&, const Name::Enum&) MOZ_DELETE; \
+ inline int operator<<(const Name::Enum&, const int&) MOZ_DELETE; \
+ inline int operator>>(const int&, const Name::Enum&) MOZ_DELETE; \
+ inline int operator>>(const Name::Enum&, const int&) MOZ_DELETE; \
+ inline int& operator+=(int&, const Name::Enum&) MOZ_DELETE; \
+ inline int& operator-=(int&, const Name::Enum&) MOZ_DELETE; \
+ inline int& operator*=(int&, const Name::Enum&) MOZ_DELETE; \
+ inline int& operator/=(int&, const Name::Enum&) MOZ_DELETE; \
+ inline int& operator%=(int&, const Name::Enum&) MOZ_DELETE; \
+ inline int& operator&=(int&, const Name::Enum&) MOZ_DELETE; \
+ inline int& operator|=(int&, const Name::Enum&) MOZ_DELETE; \
+ inline int& operator^=(int&, const Name::Enum&) MOZ_DELETE; \
+ inline int& operator<<=(int&, const Name::Enum&) MOZ_DELETE; \
+ inline int& operator>>=(int&, const Name::Enum&) MOZ_DELETE;
+#endif
+
+#endif /* __cplusplus */
+
+#endif /* mozilla_TypedEnum_h_ */
diff --git a/mfbt/Types.h b/mfbt/Types.h
new file mode 100644
index 0000000..1ba98e5
--- /dev/null
+++ b/mfbt/Types.h
@@ -0,0 +1,144 @@
+/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+/* mfbt foundational types and macros. */
+
+#ifndef mozilla_Types_h_
+#define mozilla_Types_h_
+
+/*
+ * This header must be valid C and C++, includable by code embedding either
+ * SpiderMonkey or Gecko.
+ */
+
+/*
+ * Expose all the integer types defined in C99's <stdint.h> (and the integer
+ * limit and constant macros, if compiling C code or if compiling C++ code and
+ * the right __STDC_*_MACRO has been defined for each). These are all usable
+ * throughout mfbt code, and throughout Mozilla code more generally.
+ */
+#include "mozilla/StandardInteger.h"
+
+/* Also expose size_t. */
+#include <stddef.h>
+
+/* Implement compiler and linker macros needed for APIs. */
+
+/*
+ * MOZ_EXPORT is used to declare and define a symbol or type which is externally
+ * visible to users of the current library. It encapsulates various decorations
+ * needed to properly export the method's symbol.
+ *
+ * api.h:
+ * extern MOZ_EXPORT int MeaningOfLife(void);
+ * extern MOZ_EXPORT int LuggageCombination;
+ *
+ * api.c:
+ * int MeaningOfLife(void) { return 42; }
+ * int LuggageCombination = 12345;
+ *
+ * If you are merely sharing a method across files, just use plain |extern|.
+ * These macros are designed for use by library interfaces -- not for normal
+ * methods or data used cross-file.
+ */
+#if defined(WIN32) || defined(XP_OS2)
+# define MOZ_EXPORT __declspec(dllexport)
+#else /* Unix */
+# ifdef HAVE_VISIBILITY_ATTRIBUTE
+# define MOZ_EXPORT __attribute__((visibility("default")))
+# elif defined(__SUNPRO_C) || defined(__SUNPRO_CC)
+# define MOZ_EXPORT __global
+# else
+# define MOZ_EXPORT /* nothing */
+# endif
+#endif
+
+
+/*
+ * Whereas implementers use MOZ_EXPORT to declare and define library symbols,
+ * users use MOZ_IMPORT_API and MOZ_IMPORT_DATA to access them. Most often the
+ * implementer of the library will expose an API macro which expands to either
+ * the export or import version of the macro, depending upon the compilation
+ * mode.
+ */
+#ifdef _WIN32
+# if defined(__MWERKS__)
+# define MOZ_IMPORT_API /* nothing */
+# else
+# define MOZ_IMPORT_API __declspec(dllimport)
+# endif
+#elif defined(XP_OS2)
+# define MOZ_IMPORT_API __declspec(dllimport)
+#else
+# define MOZ_IMPORT_API MOZ_EXPORT
+#endif
+
+#if defined(_WIN32) && !defined(__MWERKS__)
+# define MOZ_IMPORT_DATA __declspec(dllimport)
+#elif defined(XP_OS2)
+# define MOZ_IMPORT_DATA __declspec(dllimport)
+#else
+# define MOZ_IMPORT_DATA MOZ_EXPORT
+#endif
+
+/*
+ * Consistent with the above comment, the MFBT_API and MFBT_DATA macros expose
+ * export mfbt declarations when building mfbt, and they expose import mfbt
+ * declarations when using mfbt.
+ */
+#if defined(IMPL_MFBT)
+# define MFBT_API MOZ_EXPORT
+# define MFBT_DATA MOZ_EXPORT
+#else
+ /*
+ * On linux mozglue is linked in the program and we link libxul.so with
+ * -z,defs. Normally that causes the linker to reject undefined references in
+ * libxul.so, but as a loophole it allows undefined references to weak
+ * symbols. We add the weak attribute to the import version of the MFBT API
+ * macros to exploit this.
+ */
+# if defined(MOZ_GLUE_IN_PROGRAM)
+# define MFBT_API __attribute__((weak)) MOZ_IMPORT_API
+# define MFBT_DATA __attribute__((weak)) MOZ_IMPORT_DATA
+# else
+# define MFBT_API MOZ_IMPORT_API
+# define MFBT_DATA MOZ_IMPORT_DATA
+# endif
+#endif
+
+/*
+ * C symbols in C++ code must be declared immediately within |extern "C"|
+ * blocks. However, in C code, they need not be declared specially. This
+ * difference is abstracted behind the MOZ_BEGIN_EXTERN_C and MOZ_END_EXTERN_C
+ * macros, so that the user need not know whether he is being used in C or C++
+ * code.
+ *
+ * MOZ_BEGIN_EXTERN_C
+ *
+ * extern MOZ_EXPORT int MostRandomNumber(void);
+ * ...other declarations...
+ *
+ * MOZ_END_EXTERN_C
+ *
+ * This said, it is preferable to just use |extern "C"| in C++ header files for
+ * its greater clarity.
+ */
+#ifdef __cplusplus
+# define MOZ_BEGIN_EXTERN_C extern "C" {
+# define MOZ_END_EXTERN_C }
+#else
+# define MOZ_BEGIN_EXTERN_C
+# define MOZ_END_EXTERN_C
+#endif
+
+/*
+ * GCC's typeof is available when decltype is not.
+ */
+#if defined(__GNUC__) && defined(__cplusplus) && \
+ !defined(__GXX_EXPERIMENTAL_CXX0X__) && __cplusplus < 201103L
+# define decltype __typeof__
+#endif
+
+#endif /* mozilla_Types_h_ */
diff --git a/mfbt/Util.h b/mfbt/Util.h
new file mode 100644
index 0000000..ab62a9b
--- /dev/null
+++ b/mfbt/Util.h
@@ -0,0 +1,335 @@
+/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+/*
+ * Miscellaneous uncategorized functionality. Please add new functionality to
+ * new headers, or to other appropriate existing headers, not here.
+ */
+
+#ifndef mozilla_Util_h_
+#define mozilla_Util_h_
+
+#include "mozilla/Assertions.h"
+#include "mozilla/Attributes.h"
+#include "mozilla/Types.h"
+
+#ifdef __cplusplus
+
+namespace mozilla {
+
+/*
+ * This class, and the corresponding macro MOZ_ALIGNOF, figure out how many
+ * bytes of alignment a given type needs.
+ */
+template<class T>
+class AlignmentFinder
+{
+ struct Aligner
+ {
+ char c;
+ T t;
+ };
+
+ public:
+ static const size_t alignment = sizeof(Aligner) - sizeof(T);
+};
+
+#define MOZ_ALIGNOF(T) mozilla::AlignmentFinder<T>::alignment
+
+/*
+ * Declare the MOZ_ALIGNED_DECL macro for declaring aligned types.
+ *
+ * For instance,
+ *
+ * MOZ_ALIGNED_DECL(char arr[2], 8);
+ *
+ * will declare a two-character array |arr| aligned to 8 bytes.
+ */
+
+#if defined(__GNUC__)
+# define MOZ_ALIGNED_DECL(_type, _align) \
+ _type __attribute__((aligned(_align)))
+#elif defined(_MSC_VER)
+# define MOZ_ALIGNED_DECL(_type, _align) \
+ __declspec(align(_align)) _type
+#else
+# warning "We don't know how to align variables on this compiler."
+# define MOZ_ALIGNED_DECL(_type, _align) _type
+#endif
+
+/*
+ * AlignedElem<N> is a structure whose alignment is guaranteed to be at least N
+ * bytes.
+ *
+ * We support 1, 2, 4, 8, and 16-bit alignment.
+ */
+template<size_t align>
+struct AlignedElem;
+
+/*
+ * We have to specialize this template because GCC doesn't like __attribute__((aligned(foo))) where
+ * foo is a template parameter.
+ */
+
+template<>
+struct AlignedElem<1>
+{
+ MOZ_ALIGNED_DECL(uint8_t elem, 1);
+};
+
+template<>
+struct AlignedElem<2>
+{
+ MOZ_ALIGNED_DECL(uint8_t elem, 2);
+};
+
+template<>
+struct AlignedElem<4>
+{
+ MOZ_ALIGNED_DECL(uint8_t elem, 4);
+};
+
+template<>
+struct AlignedElem<8>
+{
+ MOZ_ALIGNED_DECL(uint8_t elem, 8);
+};
+
+template<>
+struct AlignedElem<16>
+{
+ MOZ_ALIGNED_DECL(uint8_t elem, 16);
+};
+
+/*
+ * This utility pales in comparison to Boost's aligned_storage. The utility
+ * simply assumes that uint64_t is enough alignment for anyone. This may need
+ * to be extended one day...
+ *
+ * As an important side effect, pulling the storage into this template is
+ * enough obfuscation to confuse gcc's strict-aliasing analysis into not giving
+ * false negatives when we cast from the char buffer to whatever type we've
+ * constructed using the bytes.
+ */
+template<size_t nbytes>
+struct AlignedStorage
+{
+ union U {
+ char bytes[nbytes];
+ uint64_t _;
+ } u;
+
+ const void* addr() const { return u.bytes; }
+ void* addr() { return u.bytes; }
+};
+
+template<class T>
+struct AlignedStorage2
+{
+ union U {
+ char bytes[sizeof(T)];
+ uint64_t _;
+ } u;
+
+ const T* addr() const { return reinterpret_cast<const T*>(u.bytes); }
+ T* addr() { return static_cast<T*>(static_cast<void*>(u.bytes)); }
+};
+
+/*
+ * Small utility for lazily constructing objects without using dynamic storage.
+ * When a Maybe<T> is constructed, it is |empty()|, i.e., no value of T has
+ * been constructed and no T destructor will be called when the Maybe<T> is
+ * destroyed. Upon calling |construct|, a T object will be constructed with the
+ * given arguments and that object will be destroyed when the owning Maybe<T>
+ * is destroyed.
+ *
+ * N.B. GCC seems to miss some optimizations with Maybe and may generate extra
+ * branches/loads/stores. Use with caution on hot paths.
+ */
+template<class T>
+class Maybe
+{
+ AlignedStorage2<T> storage;
+ bool constructed;
+
+ T& asT() { return *storage.addr(); }
+
+ public:
+ Maybe() { constructed = false; }
+ ~Maybe() { if (constructed) asT().~T(); }
+
+ bool empty() const { return !constructed; }
+
+ void construct() {
+ MOZ_ASSERT(!constructed);
+ ::new (storage.addr()) T();
+ constructed = true;
+ }
+
+ template<class T1>
+ void construct(const T1& t1) {
+ MOZ_ASSERT(!constructed);
+ ::new (storage.addr()) T(t1);
+ constructed = true;
+ }
+
+ template<class T1, class T2>
+ void construct(const T1& t1, const T2& t2) {
+ MOZ_ASSERT(!constructed);
+ ::new (storage.addr()) T(t1, t2);
+ constructed = true;
+ }
+
+ template<class T1, class T2, class T3>
+ void construct(const T1& t1, const T2& t2, const T3& t3) {
+ MOZ_ASSERT(!constructed);
+ ::new (storage.addr()) T(t1, t2, t3);
+ constructed = true;
+ }
+
+ template<class T1, class T2, class T3, class T4>
+ void construct(const T1& t1, const T2& t2, const T3& t3, const T4& t4) {
+ MOZ_ASSERT(!constructed);
+ ::new (storage.addr()) T(t1, t2, t3, t4);
+ constructed = true;
+ }
+
+ template<class T1, class T2, class T3, class T4, class T5>
+ void construct(const T1& t1, const T2& t2, const T3& t3, const T4& t4, const T5& t5) {
+ MOZ_ASSERT(!constructed);
+ ::new (storage.addr()) T(t1, t2, t3, t4, t5);
+ constructed = true;
+ }
+
+ template<class T1, class T2, class T3, class T4, class T5,
+ class T6>
+ void construct(const T1& t1, const T2& t2, const T3& t3, const T4& t4, const T5& t5,
+ const T6& t6) {
+ MOZ_ASSERT(!constructed);
+ ::new (storage.addr()) T(t1, t2, t3, t4, t5, t6);
+ constructed = true;
+ }
+
+ template<class T1, class T2, class T3, class T4, class T5,
+ class T6, class T7>
+ void construct(const T1& t1, const T2& t2, const T3& t3, const T4& t4, const T5& t5,
+ const T6& t6, const T7& t7) {
+ MOZ_ASSERT(!constructed);
+ ::new (storage.addr()) T(t1, t2, t3, t4, t5, t6, t7);
+ constructed = true;
+ }
+
+ template<class T1, class T2, class T3, class T4, class T5,
+ class T6, class T7, class T8>
+ void construct(const T1& t1, const T2& t2, const T3& t3, const T4& t4, const T5& t5,
+ const T6& t6, const T7& t7, const T8& t8) {
+ MOZ_ASSERT(!constructed);
+ ::new (storage.addr()) T(t1, t2, t3, t4, t5, t6, t7, t8);
+ constructed = true;
+ }
+
+ template<class T1, class T2, class T3, class T4, class T5,
+ class T6, class T7, class T8, class T9>
+ void construct(const T1& t1, const T2& t2, const T3& t3, const T4& t4, const T5& t5,
+ const T6& t6, const T7& t7, const T8& t8, const T9& t9) {
+ MOZ_ASSERT(!constructed);
+ ::new (storage.addr()) T(t1, t2, t3, t4, t5, t6, t7, t8, t9);
+ constructed = true;
+ }
+
+ template<class T1, class T2, class T3, class T4, class T5,
+ class T6, class T7, class T8, class T9, class T10>
+ void construct(const T1& t1, const T2& t2, const T3& t3, const T4& t4, const T5& t5,
+ const T6& t6, const T7& t7, const T8& t8, const T9& t9, const T10& t10) {
+ MOZ_ASSERT(!constructed);
+ ::new (storage.addr()) T(t1, t2, t3, t4, t5, t6, t7, t8, t9, t10);
+ constructed = true;
+ }
+
+ T* addr() {
+ MOZ_ASSERT(constructed);
+ return &asT();
+ }
+
+ T& ref() {
+ MOZ_ASSERT(constructed);
+ return asT();
+ }
+
+ const T& ref() const {
+ MOZ_ASSERT(constructed);
+ return const_cast<Maybe*>(this)->asT();
+ }
+
+ void destroy() {
+ ref().~T();
+ constructed = false;
+ }
+
+ void destroyIfConstructed() {
+ if (!empty())
+ destroy();
+ }
+
+ private:
+ Maybe(const Maybe& other) MOZ_DELETE;
+ const Maybe& operator=(const Maybe& other) MOZ_DELETE;
+};
+
+/*
+ * Safely subtract two pointers when it is known that end >= begin. This avoids
+ * the common compiler bug that if (size_t(end) - size_t(begin)) has the MSB
+ * set, the unsigned subtraction followed by right shift will produce -1, or
+ * size_t(-1), instead of the real difference.
+ */
+template<class T>
+MOZ_ALWAYS_INLINE size_t
+PointerRangeSize(T* begin, T* end)
+{
+ MOZ_ASSERT(end >= begin);
+ return (size_t(end) - size_t(begin)) / sizeof(T);
+}
+
+/*
+ * Compute the length of an array with constant length. (Use of this method
+ * with a non-array pointer will not compile.)
+ *
+ * Beware of the implicit trailing '\0' when using this with string constants.
+ */
+template<typename T, size_t N>
+MOZ_CONSTEXPR size_t
+ArrayLength(T (&arr)[N])
+{
+ return N;
+}
+
+/*
+ * Compute the address one past the last element of a constant-length array.
+ *
+ * Beware of the implicit trailing '\0' when using this with string constants.
+ */
+template<typename T, size_t N>
+MOZ_CONSTEXPR T*
+ArrayEnd(T (&arr)[N])
+{
+ return arr + ArrayLength(arr);
+}
+
+} /* namespace mozilla */
+
+#endif /* __cplusplus */
+
+/*
+ * MOZ_ARRAY_LENGTH() is an alternative to mozilla::ArrayLength() for C files
+ * that can't use C++ template functions and for MOZ_STATIC_ASSERT() calls that
+ * can't call ArrayLength() when it is not a C++11 constexpr function.
+ */
+#ifdef MOZ_HAVE_CXX11_CONSTEXPR
+# define MOZ_ARRAY_LENGTH(array) mozilla::ArrayLength(array)
+#else
+# define MOZ_ARRAY_LENGTH(array) (sizeof(array)/sizeof((array)[0]))
+#endif
+
+#endif /* mozilla_Util_h_ */
diff --git a/mfbt/WeakPtr.h b/mfbt/WeakPtr.h
new file mode 100644
index 0000000..73fe924
--- /dev/null
+++ b/mfbt/WeakPtr.h
@@ -0,0 +1,190 @@
+/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+/* Weak pointer functionality, implemented as a mixin for use with any class. */
+
+/**
+ * SupportsWeakPtr lets you have a pointer to an object 'Foo' without affecting
+ * its lifetime. It works by creating a single shared reference counted object
+ * (WeakReference) that each WeakPtr will access 'Foo' through. This lets 'Foo'
+ * clear the pointer in the WeakReference without having to know about all of
+ * the WeakPtrs to it and allows the WeakReference to live beyond the lifetime
+ * of 'Foo'.
+ *
+ * AtomicSupportsWeakPtr can be used for a variant with an atomically updated
+ * reference counter.
+ *
+ * The overhead of WeakPtr is that accesses to 'Foo' becomes an additional
+ * dereference, and an additional heap allocated pointer sized object shared
+ * between all of the WeakPtrs.
+ *
+ * Example of usage:
+ *
+ * // To have a class C support weak pointers, inherit from SupportsWeakPtr<C>.
+ * class C : public SupportsWeakPtr<C>
+ * {
+ * public:
+ * int num;
+ * void act();
+ * };
+ *
+ * C* ptr = new C();
+ *
+ * // Get weak pointers to ptr. The first time asWeakPtr is called
+ * // a reference counted WeakReference object is created that
+ * // can live beyond the lifetime of 'ptr'. The WeakReference
+ * // object will be notified of 'ptr's destruction.
+ * WeakPtr<C> weak = ptr->asWeakPtr();
+ * WeakPtr<C> other = ptr->asWeakPtr();
+ *
+ * // Test a weak pointer for validity before using it.
+ * if (weak) {
+ * weak->num = 17;
+ * weak->act();
+ * }
+ *
+ * // Destroying the underlying object clears weak pointers to it.
+ * delete ptr;
+ *
+ * MOZ_ASSERT(!weak, "Deleting |ptr| clears weak pointers to it.");
+ * MOZ_ASSERT(!other, "Deleting |ptr| clears all weak pointers to it.");
+ *
+ * WeakPtr is typesafe and may be used with any class. It is not required that
+ * the class be reference-counted or allocated in any particular way.
+ *
+ * The API was loosely inspired by Chromium's weak_ptr.h:
+ * http://src.chromium.org/svn/trunk/src/base/memory/weak_ptr.h
+ */
+
+#ifndef mozilla_WeakPtr_h_
+#define mozilla_WeakPtr_h_
+
+#include "mozilla/Assertions.h"
+#include "mozilla/Atomics.h"
+#include "mozilla/NullPtr.h"
+#include "mozilla/RefPtr.h"
+#include "mozilla/TypeTraits.h"
+
+namespace mozilla {
+
+template <typename T, class WeakReference> class WeakPtrBase;
+template <typename T, class WeakReference> class SupportsWeakPtrBase;
+
+namespace detail {
+
+// This can live beyond the lifetime of the class derived from SupportsWeakPtrBase.
+template<class T, RefCountAtomicity Atomicity>
+class WeakReference : public RefCounted<WeakReference<T, Atomicity>, Atomicity>
+{
+ public:
+ explicit WeakReference(T* p) : ptr(p) {}
+ T* get() const {
+ return ptr;
+ }
+
+ private:
+ friend class WeakPtrBase<T, WeakReference>;
+ friend class SupportsWeakPtrBase<T, WeakReference>;
+ void detach() {
+ ptr = nullptr;
+ }
+ T* ptr;
+};
+
+} // namespace detail
+
+template <typename T, class WeakReference>
+class SupportsWeakPtrBase
+{
+ public:
+ WeakPtrBase<T, WeakReference> asWeakPtr() {
+ if (!weakRef)
+ weakRef = new WeakReference(static_cast<T*>(this));
+ return WeakPtrBase<T, WeakReference>(weakRef);
+ }
+
+ protected:
+ ~SupportsWeakPtrBase() {
+ MOZ_STATIC_ASSERT((IsBaseOf<SupportsWeakPtrBase<T, WeakReference>, T>::value),
+ "T must derive from SupportsWeakPtrBase<T, WeakReference>");
+ if (weakRef)
+ weakRef->detach();
+ }
+
+ private:
+ friend class WeakPtrBase<T, WeakReference>;
+
+ RefPtr<WeakReference> weakRef;
+};
+
+template <typename T>
+class SupportsWeakPtr
+ : public SupportsWeakPtrBase<T, detail::WeakReference<T, detail::NonAtomicRefCount> >
+{
+};
+
+template <typename T>
+class AtomicSupportsWeakPtr
+ : public SupportsWeakPtrBase<T, detail::WeakReference<T, detail::AtomicRefCount> >
+{
+};
+
+namespace detail {
+
+template <typename T>
+struct WeakReferenceCount
+{
+ static const RefCountAtomicity atomicity =
+ IsBaseOf<AtomicSupportsWeakPtr<T>, T>::value
+ ? AtomicRefCount
+ : NonAtomicRefCount;
+};
+
+}
+
+template <typename T, class WeakReference>
+class WeakPtrBase
+{
+ public:
+ WeakPtrBase(const WeakPtrBase<T, WeakReference>& o) : ref(o.ref) {}
+ // Ensure that ref is dereferenceable in the uninitialized state
+ WeakPtrBase() : ref(new WeakReference(nullptr)) {}
+
+ operator T*() const {
+ return ref->get();
+ }
+ T& operator*() const {
+ return *ref->get();
+ }
+
+ T* operator->() const {
+ return ref->get();
+ }
+
+ T* get() const {
+ return ref->get();
+ }
+
+ private:
+ friend class SupportsWeakPtrBase<T, WeakReference>;
+
+ explicit WeakPtrBase(const RefPtr<WeakReference> &o) : ref(o) {}
+
+ RefPtr<WeakReference> ref;
+};
+
+template <typename T>
+class WeakPtr : public WeakPtrBase<T, detail::WeakReference<T, detail::WeakReferenceCount<T>::atomicity> >
+{
+ typedef WeakPtrBase<T, detail::WeakReference<T, detail::WeakReferenceCount<T>::atomicity> > Base;
+ public:
+ WeakPtr(const WeakPtr<T>& o) : Base(o) {}
+ WeakPtr(const Base& o) : Base(o) {}
+ WeakPtr() {}
+};
+
+} // namespace mozilla
+
+#endif /* ifdef mozilla_WeakPtr_h_ */
diff --git a/mfbt/decimal/Decimal.cpp b/mfbt/decimal/Decimal.cpp
new file mode 100644
index 0000000..de10f83
--- /dev/null
+++ b/mfbt/decimal/Decimal.cpp
@@ -0,0 +1,1054 @@
+/*
+ * Copyright (C) 2012 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * 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.
+ * * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * 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.
+ */
+
+#include "Decimal.h"
+#include "moz-decimal-utils.h"
+
+#include <algorithm>
+#include <float.h>
+
+namespace WebCore {
+
+namespace DecimalPrivate {
+
+static int const ExponentMax = 1023;
+static int const ExponentMin = -1023;
+static int const Precision = 18;
+
+static const uint64_t MaxCoefficient = UINT64_C(0x16345785D89FFFF); // 999999999999999999 == 18 9's
+
+// This class handles Decimal special values.
+class SpecialValueHandler {
+ WTF_MAKE_NONCOPYABLE(SpecialValueHandler);
+public:
+ enum HandleResult {
+ BothFinite,
+ BothInfinity,
+ EitherNaN,
+ LHSIsInfinity,
+ RHSIsInfinity,
+ };
+
+ SpecialValueHandler(const Decimal& lhs, const Decimal& rhs);
+ HandleResult handle();
+ Decimal value() const;
+
+private:
+ enum Result {
+ ResultIsLHS,
+ ResultIsRHS,
+ ResultIsUnknown,
+ };
+
+ const Decimal& m_lhs;
+ const Decimal& m_rhs;
+ Result m_result;
+};
+
+SpecialValueHandler::SpecialValueHandler(const Decimal& lhs, const Decimal& rhs)
+ : m_lhs(lhs), m_rhs(rhs), m_result(ResultIsUnknown)
+{
+}
+
+SpecialValueHandler::HandleResult SpecialValueHandler::handle()
+{
+ if (m_lhs.isFinite() && m_rhs.isFinite())
+ return BothFinite;
+
+ const Decimal::EncodedData::FormatClass lhsClass = m_lhs.value().formatClass();
+ const Decimal::EncodedData::FormatClass rhsClass = m_rhs.value().formatClass();
+ if (lhsClass == Decimal::EncodedData::ClassNaN) {
+ m_result = ResultIsLHS;
+ return EitherNaN;
+ }
+
+ if (rhsClass == Decimal::EncodedData::ClassNaN) {
+ m_result = ResultIsRHS;
+ return EitherNaN;
+ }
+
+ if (lhsClass == Decimal::EncodedData::ClassInfinity)
+ return rhsClass == Decimal::EncodedData::ClassInfinity ? BothInfinity : LHSIsInfinity;
+
+ if (rhsClass == Decimal::EncodedData::ClassInfinity)
+ return RHSIsInfinity;
+
+ ASSERT_NOT_REACHED();
+ return BothFinite;
+}
+
+Decimal SpecialValueHandler::value() const
+{
+ switch (m_result) {
+ case ResultIsLHS:
+ return m_lhs;
+ case ResultIsRHS:
+ return m_rhs;
+ case ResultIsUnknown:
+ default:
+ ASSERT_NOT_REACHED();
+ return m_lhs;
+ }
+}
+
+// This class is used for 128 bit unsigned integer arithmetic.
+class UInt128 {
+public:
+ UInt128(uint64_t low, uint64_t high)
+ : m_high(high), m_low(low)
+ {
+ }
+
+ UInt128& operator/=(uint32_t);
+
+ uint64_t high() const { return m_high; }
+ uint64_t low() const { return m_low; }
+
+ static UInt128 multiply(uint64_t u, uint64_t v) { return UInt128(u * v, multiplyHigh(u, v)); }
+
+private:
+ static uint32_t highUInt32(uint64_t x) { return static_cast<uint32_t>(x >> 32); }
+ static uint32_t lowUInt32(uint64_t x) { return static_cast<uint32_t>(x & ((static_cast<uint64_t>(1) << 32) - 1)); }
+ bool isZero() const { return !m_low && !m_high; }
+ static uint64_t makeUInt64(uint32_t low, uint32_t high) { return low | (static_cast<uint64_t>(high) << 32); }
+
+ static uint64_t multiplyHigh(uint64_t, uint64_t);
+
+ uint64_t m_high;
+ uint64_t m_low;
+};
+
+UInt128& UInt128::operator/=(const uint32_t divisor)
+{
+ ASSERT(divisor);
+
+ if (!m_high) {
+ m_low /= divisor;
+ return *this;
+ }
+
+ uint32_t dividend[4];
+ dividend[0] = lowUInt32(m_low);
+ dividend[1] = highUInt32(m_low);
+ dividend[2] = lowUInt32(m_high);
+ dividend[3] = highUInt32(m_high);
+
+ uint32_t quotient[4];
+ uint32_t remainder = 0;
+ for (int i = 3; i >= 0; --i) {
+ const uint64_t work = makeUInt64(dividend[i], remainder);
+ remainder = static_cast<uint32_t>(work % divisor);
+ quotient[i] = static_cast<uint32_t>(work / divisor);
+ }
+ m_low = makeUInt64(quotient[0], quotient[1]);
+ m_high = makeUInt64(quotient[2], quotient[3]);
+ return *this;
+}
+
+// Returns high 64bit of 128bit product.
+uint64_t UInt128::multiplyHigh(uint64_t u, uint64_t v)
+{
+ const uint64_t uLow = lowUInt32(u);
+ const uint64_t uHigh = highUInt32(u);
+ const uint64_t vLow = lowUInt32(v);
+ const uint64_t vHigh = highUInt32(v);
+ const uint64_t partialProduct = uHigh * vLow + highUInt32(uLow * vLow);
+ return uHigh * vHigh + highUInt32(partialProduct) + highUInt32(uLow * vHigh + lowUInt32(partialProduct));
+}
+
+static int countDigits(uint64_t x)
+{
+ int numberOfDigits = 0;
+ for (uint64_t powerOfTen = 1; x >= powerOfTen; powerOfTen *= 10) {
+ ++numberOfDigits;
+ if (powerOfTen >= std::numeric_limits<uint64_t>::max() / 10)
+ break;
+ }
+ return numberOfDigits;
+}
+
+static uint64_t scaleDown(uint64_t x, int n)
+{
+ ASSERT(n >= 0);
+ while (n > 0 && x) {
+ x /= 10;
+ --n;
+ }
+ return x;
+}
+
+static uint64_t scaleUp(uint64_t x, int n)
+{
+ ASSERT(n >= 0);
+ ASSERT(n < Precision);
+
+ uint64_t y = 1;
+ uint64_t z = 10;
+ for (;;) {
+ if (n & 1)
+ y = y * z;
+
+ n >>= 1;
+ if (!n)
+ return x * y;
+
+ z = z * z;
+ }
+}
+
+} // namespace DecimalPrivate
+
+using namespace DecimalPrivate;
+
+Decimal::EncodedData::EncodedData(Sign sign, FormatClass formatClass)
+ : m_coefficient(0)
+ , m_exponent(0)
+ , m_formatClass(formatClass)
+ , m_sign(sign)
+{
+}
+
+Decimal::EncodedData::EncodedData(Sign sign, int exponent, uint64_t coefficient)
+ : m_formatClass(coefficient ? ClassNormal : ClassZero)
+ , m_sign(sign)
+{
+ if (exponent >= ExponentMin && exponent <= ExponentMax) {
+ while (coefficient > MaxCoefficient) {
+ coefficient /= 10;
+ ++exponent;
+ }
+ }
+
+ if (exponent > ExponentMax) {
+ m_coefficient = 0;
+ m_exponent = 0;
+ m_formatClass = ClassInfinity;
+ return;
+ }
+
+ if (exponent < ExponentMin) {
+ m_coefficient = 0;
+ m_exponent = 0;
+ m_formatClass = ClassZero;
+ return;
+ }
+
+ m_coefficient = coefficient;
+ m_exponent = static_cast<int16_t>(exponent);
+}
+
+bool Decimal::EncodedData::operator==(const EncodedData& another) const
+{
+ return m_sign == another.m_sign
+ && m_formatClass == another.m_formatClass
+ && m_exponent == another.m_exponent
+ && m_coefficient == another.m_coefficient;
+}
+
+Decimal::Decimal(int32_t i32)
+ : m_data(i32 < 0 ? Negative : Positive, 0, i32 < 0 ? static_cast<uint64_t>(-static_cast<int64_t>(i32)) : static_cast<uint64_t>(i32))
+{
+}
+
+Decimal::Decimal(Sign sign, int exponent, uint64_t coefficient)
+ : m_data(sign, coefficient ? exponent : 0, coefficient)
+{
+}
+
+Decimal::Decimal(const EncodedData& data)
+ : m_data(data)
+{
+}
+
+Decimal::Decimal(const Decimal& other)
+ : m_data(other.m_data)
+{
+}
+
+Decimal& Decimal::operator=(const Decimal& other)
+{
+ m_data = other.m_data;
+ return *this;
+}
+
+Decimal& Decimal::operator+=(const Decimal& other)
+{
+ m_data = (*this + other).m_data;
+ return *this;
+}
+
+Decimal& Decimal::operator-=(const Decimal& other)
+{
+ m_data = (*this - other).m_data;
+ return *this;
+}
+
+Decimal& Decimal::operator*=(const Decimal& other)
+{
+ m_data = (*this * other).m_data;
+ return *this;
+}
+
+Decimal& Decimal::operator/=(const Decimal& other)
+{
+ m_data = (*this / other).m_data;
+ return *this;
+}
+
+Decimal Decimal::operator-() const
+{
+ if (isNaN())
+ return *this;
+
+ Decimal result(*this);
+ result.m_data.setSign(invertSign(m_data.sign()));
+ return result;
+}
+
+Decimal Decimal::operator+(const Decimal& rhs) const
+{
+ const Decimal& lhs = *this;
+ const Sign lhsSign = lhs.sign();
+ const Sign rhsSign = rhs.sign();
+
+ SpecialValueHandler handler(lhs, rhs);
+ switch (handler.handle()) {
+ case SpecialValueHandler::BothFinite:
+ break;
+
+ case SpecialValueHandler::BothInfinity:
+ return lhsSign == rhsSign ? lhs : nan();
+
+ case SpecialValueHandler::EitherNaN:
+ return handler.value();
+
+ case SpecialValueHandler::LHSIsInfinity:
+ return lhs;
+
+ case SpecialValueHandler::RHSIsInfinity:
+ return rhs;
+ }
+
+ const AlignedOperands alignedOperands = alignOperands(lhs, rhs);
+
+ const uint64_t result = lhsSign == rhsSign
+ ? alignedOperands.lhsCoefficient + alignedOperands.rhsCoefficient
+ : alignedOperands.lhsCoefficient - alignedOperands.rhsCoefficient;
+
+ if (lhsSign == Negative && rhsSign == Positive && !result)
+ return Decimal(Positive, alignedOperands.exponent, 0);
+
+ return static_cast<int64_t>(result) >= 0
+ ? Decimal(lhsSign, alignedOperands.exponent, result)
+ : Decimal(invertSign(lhsSign), alignedOperands.exponent, -static_cast<int64_t>(result));
+}
+
+Decimal Decimal::operator-(const Decimal& rhs) const
+{
+ const Decimal& lhs = *this;
+ const Sign lhsSign = lhs.sign();
+ const Sign rhsSign = rhs.sign();
+
+ SpecialValueHandler handler(lhs, rhs);
+ switch (handler.handle()) {
+ case SpecialValueHandler::BothFinite:
+ break;
+
+ case SpecialValueHandler::BothInfinity:
+ return lhsSign == rhsSign ? nan() : lhs;
+
+ case SpecialValueHandler::EitherNaN:
+ return handler.value();
+
+ case SpecialValueHandler::LHSIsInfinity:
+ return lhs;
+
+ case SpecialValueHandler::RHSIsInfinity:
+ return infinity(invertSign(rhsSign));
+ }
+
+ const AlignedOperands alignedOperands = alignOperands(lhs, rhs);
+
+ const uint64_t result = lhsSign == rhsSign
+ ? alignedOperands.lhsCoefficient - alignedOperands.rhsCoefficient
+ : alignedOperands.lhsCoefficient + alignedOperands.rhsCoefficient;
+
+ if (lhsSign == Negative && rhsSign == Negative && !result)
+ return Decimal(Positive, alignedOperands.exponent, 0);
+
+ return static_cast<int64_t>(result) >= 0
+ ? Decimal(lhsSign, alignedOperands.exponent, result)
+ : Decimal(invertSign(lhsSign), alignedOperands.exponent, -static_cast<int64_t>(result));
+}
+
+Decimal Decimal::operator*(const Decimal& rhs) const
+{
+ const Decimal& lhs = *this;
+ const Sign lhsSign = lhs.sign();
+ const Sign rhsSign = rhs.sign();
+ const Sign resultSign = lhsSign == rhsSign ? Positive : Negative;
+
+ SpecialValueHandler handler(lhs, rhs);
+ switch (handler.handle()) {
+ case SpecialValueHandler::BothFinite: {
+ const uint64_t lhsCoefficient = lhs.m_data.coefficient();
+ const uint64_t rhsCoefficient = rhs.m_data.coefficient();
+ int resultExponent = lhs.exponent() + rhs.exponent();
+ UInt128 work(UInt128::multiply(lhsCoefficient, rhsCoefficient));
+ while (work.high()) {
+ work /= 10;
+ ++resultExponent;
+ }
+ return Decimal(resultSign, resultExponent, work.low());
+ }
+
+ case SpecialValueHandler::BothInfinity:
+ return infinity(resultSign);
+
+ case SpecialValueHandler::EitherNaN:
+ return handler.value();
+
+ case SpecialValueHandler::LHSIsInfinity:
+ return rhs.isZero() ? nan() : infinity(resultSign);
+
+ case SpecialValueHandler::RHSIsInfinity:
+ return lhs.isZero() ? nan() : infinity(resultSign);
+ }
+
+ ASSERT_NOT_REACHED();
+ return nan();
+}
+
+Decimal Decimal::operator/(const Decimal& rhs) const
+{
+ const Decimal& lhs = *this;
+ const Sign lhsSign = lhs.sign();
+ const Sign rhsSign = rhs.sign();
+ const Sign resultSign = lhsSign == rhsSign ? Positive : Negative;
+
+ SpecialValueHandler handler(lhs, rhs);
+ switch (handler.handle()) {
+ case SpecialValueHandler::BothFinite:
+ break;
+
+ case SpecialValueHandler::BothInfinity:
+ return nan();
+
+ case SpecialValueHandler::EitherNaN:
+ return handler.value();
+
+ case SpecialValueHandler::LHSIsInfinity:
+ return infinity(resultSign);
+
+ case SpecialValueHandler::RHSIsInfinity:
+ return zero(resultSign);
+ }
+
+ ASSERT(lhs.isFinite());
+ ASSERT(rhs.isFinite());
+
+ if (rhs.isZero())
+ return lhs.isZero() ? nan() : infinity(resultSign);
+
+ int resultExponent = lhs.exponent() - rhs.exponent();
+
+ if (lhs.isZero())
+ return Decimal(resultSign, resultExponent, 0);
+
+ uint64_t remainder = lhs.m_data.coefficient();
+ const uint64_t divisor = rhs.m_data.coefficient();
+ uint64_t result = 0;
+ while (result < MaxCoefficient / 100) {
+ while (remainder < divisor) {
+ remainder *= 10;
+ result *= 10;
+ --resultExponent;
+ }
+ result += remainder / divisor;
+ remainder %= divisor;
+ if (!remainder)
+ break;
+ }
+
+ if (remainder > divisor / 2)
+ ++result;
+
+ return Decimal(resultSign, resultExponent, result);
+}
+
+bool Decimal::operator==(const Decimal& rhs) const
+{
+ if (isNaN() || rhs.isNaN())
+ return false;
+ return m_data == rhs.m_data || compareTo(rhs).isZero();
+}
+
+bool Decimal::operator!=(const Decimal& rhs) const
+{
+ if (isNaN() || rhs.isNaN())
+ return true;
+ if (m_data == rhs.m_data)
+ return false;
+ const Decimal result = compareTo(rhs);
+ if (result.isNaN())
+ return false;
+ return !result.isZero();
+}
+
+bool Decimal::operator<(const Decimal& rhs) const
+{
+ const Decimal result = compareTo(rhs);
+ if (result.isNaN())
+ return false;
+ return !result.isZero() && result.isNegative();
+}
+
+bool Decimal::operator<=(const Decimal& rhs) const
+{
+ if (isNaN() || rhs.isNaN())
+ return false;
+ if (m_data == rhs.m_data)
+ return true;
+ const Decimal result = compareTo(rhs);
+ if (result.isNaN())
+ return false;
+ return result.isZero() || result.isNegative();
+}
+
+bool Decimal::operator>(const Decimal& rhs) const
+{
+ const Decimal result = compareTo(rhs);
+ if (result.isNaN())
+ return false;
+ return !result.isZero() && result.isPositive();
+}
+
+bool Decimal::operator>=(const Decimal& rhs) const
+{
+ if (isNaN() || rhs.isNaN())
+ return false;
+ if (m_data == rhs.m_data)
+ return true;
+ const Decimal result = compareTo(rhs);
+ if (result.isNaN())
+ return false;
+ return result.isZero() || !result.isNegative();
+}
+
+Decimal Decimal::abs() const
+{
+ Decimal result(*this);
+ result.m_data.setSign(Positive);
+ return result;
+}
+
+Decimal::AlignedOperands Decimal::alignOperands(const Decimal& lhs, const Decimal& rhs)
+{
+ ASSERT(lhs.isFinite());
+ ASSERT(rhs.isFinite());
+
+ const int lhsExponent = lhs.exponent();
+ const int rhsExponent = rhs.exponent();
+ int exponent = std::min(lhsExponent, rhsExponent);
+ uint64_t lhsCoefficient = lhs.m_data.coefficient();
+ uint64_t rhsCoefficient = rhs.m_data.coefficient();
+
+ if (lhsExponent > rhsExponent) {
+ const int numberOfLHSDigits = countDigits(lhsCoefficient);
+ if (numberOfLHSDigits) {
+ const int lhsShiftAmount = lhsExponent - rhsExponent;
+ const int overflow = numberOfLHSDigits + lhsShiftAmount - Precision;
+ if (overflow <= 0)
+ lhsCoefficient = scaleUp(lhsCoefficient, lhsShiftAmount);
+ else {
+ lhsCoefficient = scaleUp(lhsCoefficient, lhsShiftAmount - overflow);
+ rhsCoefficient = scaleDown(rhsCoefficient, overflow);
+ exponent += overflow;
+ }
+ }
+
+ } else if (lhsExponent < rhsExponent) {
+ const int numberOfRHSDigits = countDigits(rhsCoefficient);
+ if (numberOfRHSDigits) {
+ const int rhsShiftAmount = rhsExponent - lhsExponent;
+ const int overflow = numberOfRHSDigits + rhsShiftAmount - Precision;
+ if (overflow <= 0)
+ rhsCoefficient = scaleUp(rhsCoefficient, rhsShiftAmount);
+ else {
+ rhsCoefficient = scaleUp(rhsCoefficient, rhsShiftAmount - overflow);
+ lhsCoefficient = scaleDown(lhsCoefficient, overflow);
+ exponent += overflow;
+ }
+ }
+ }
+
+ AlignedOperands alignedOperands;
+ alignedOperands.exponent = exponent;
+ alignedOperands.lhsCoefficient = lhsCoefficient;
+ alignedOperands.rhsCoefficient = rhsCoefficient;
+ return alignedOperands;
+}
+
+// Round toward positive infinity.
+// Note: Mac ports defines ceil(x) as wtf_ceil(x), so we can't use name "ceil" here.
+Decimal Decimal::ceiling() const
+{
+ if (isSpecial())
+ return *this;
+
+ if (exponent() >= 0)
+ return *this;
+
+ uint64_t coefficient = m_data.coefficient();
+ const int numberOfDigits = countDigits(coefficient);
+ const int numberOfDropDigits = -exponent();
+ if (numberOfDigits < numberOfDropDigits)
+ return isPositive() ? Decimal(1) : zero(Positive);
+
+ uint64_t result = scaleDown(coefficient, numberOfDropDigits);
+ uint64_t droppedDigits = coefficient - scaleUp(result, numberOfDropDigits);
+ if (droppedDigits && isPositive())
+ result += 1;
+ return Decimal(sign(), 0, result);
+}
+
+Decimal Decimal::compareTo(const Decimal& rhs) const
+{
+ const Decimal result(*this - rhs);
+ switch (result.m_data.formatClass()) {
+ case EncodedData::ClassInfinity:
+ return result.isNegative() ? Decimal(-1) : Decimal(1);
+
+ case EncodedData::ClassNaN:
+ case EncodedData::ClassNormal:
+ return result;
+
+ case EncodedData::ClassZero:
+ return zero(Positive);
+
+ default:
+ ASSERT_NOT_REACHED();
+ return nan();
+ }
+}
+
+// Round toward negative infinity.
+Decimal Decimal::floor() const
+{
+ if (isSpecial())
+ return *this;
+
+ if (exponent() >= 0)
+ return *this;
+
+ uint64_t coefficient = m_data.coefficient();
+ const int numberOfDigits = countDigits(coefficient);
+ const int numberOfDropDigits = -exponent();
+ if (numberOfDigits < numberOfDropDigits)
+ return isPositive() ? zero(Positive) : Decimal(-1);
+
+ uint64_t result = scaleDown(coefficient, numberOfDropDigits);
+ uint64_t droppedDigits = coefficient - scaleUp(result, numberOfDropDigits);
+ if (droppedDigits && isNegative()) {
+ result += 1;
+ }
+ return Decimal(sign(), 0, result);
+}
+
+Decimal Decimal::fromDouble(double doubleValue)
+{
+ if (std::isfinite(doubleValue))
+ return fromString(mozToString(doubleValue));
+
+ if (std::isinf(doubleValue))
+ return infinity(doubleValue < 0 ? Negative : Positive);
+
+ return nan();
+}
+
+Decimal Decimal::fromString(const String& str)
+{
+ int exponent = 0;
+ Sign exponentSign = Positive;
+ int numberOfDigits = 0;
+ int numberOfDigitsAfterDot = 0;
+ int numberOfExtraDigits = 0;
+ Sign sign = Positive;
+
+ enum {
+ StateDigit,
+ StateDot,
+ StateDotDigit,
+ StateE,
+ StateEDigit,
+ StateESign,
+ StateSign,
+ StateStart,
+ StateZero,
+ } state = StateStart;
+
+#define HandleCharAndBreak(expected, nextState) \
+ if (ch == expected) { \
+ state = nextState; \
+ break; \
+ }
+
+#define HandleTwoCharsAndBreak(expected1, expected2, nextState) \
+ if (ch == expected1 || ch == expected2) { \
+ state = nextState; \
+ break; \
+ }
+
+ uint64_t accumulator = 0;
+ for (unsigned index = 0; index < str.length(); ++index) {
+ const int ch = str[index];
+ switch (state) {
+ case StateDigit:
+ if (ch >= '0' && ch <= '9') {
+ if (numberOfDigits < Precision) {
+ ++numberOfDigits;
+ accumulator *= 10;
+ accumulator += ch - '0';
+ } else
+ ++numberOfExtraDigits;
+ break;
+ }
+
+ HandleCharAndBreak('.', StateDot);
+ HandleTwoCharsAndBreak('E', 'e', StateE);
+ return nan();
+
+ case StateDot:
+ if (ch >= '0' && ch <= '9') {
+ if (numberOfDigits < Precision) {
+ ++numberOfDigits;
+ ++numberOfDigitsAfterDot;
+ accumulator *= 10;
+ accumulator += ch - '0';
+ }
+ state = StateDotDigit;
+ break;
+ }
+
+ case StateDotDigit:
+ if (ch >= '0' && ch <= '9') {
+ if (numberOfDigits < Precision) {
+ ++numberOfDigits;
+ ++numberOfDigitsAfterDot;
+ accumulator *= 10;
+ accumulator += ch - '0';
+ }
+ break;
+ }
+
+ HandleTwoCharsAndBreak('E', 'e', StateE);
+ return nan();
+
+ case StateE:
+ if (ch == '+') {
+ exponentSign = Positive;
+ state = StateESign;
+ break;
+ }
+
+ if (ch == '-') {
+ exponentSign = Negative;
+ state = StateESign;
+ break;
+ }
+
+ if (ch >= '0' && ch <= '9') {
+ exponent = ch - '0';
+ state = StateEDigit;
+ break;
+ }
+
+ return nan();
+
+ case StateEDigit:
+ if (ch >= '0' && ch <= '9') {
+ exponent *= 10;
+ exponent += ch - '0';
+ if (exponent > ExponentMax + Precision) {
+ if (accumulator)
+ return exponentSign == Negative ? zero(Positive) : infinity(sign);
+ return zero(sign);
+ }
+ state = StateEDigit;
+ break;
+ }
+
+ return nan();
+
+ case StateESign:
+ if (ch >= '0' && ch <= '9') {
+ exponent = ch - '0';
+ state = StateEDigit;
+ break;
+ }
+
+ return nan();
+
+ case StateSign:
+ if (ch >= '1' && ch <= '9') {
+ accumulator = ch - '0';
+ numberOfDigits = 1;
+ state = StateDigit;
+ break;
+ }
+
+ HandleCharAndBreak('0', StateZero);
+ return nan();
+
+ case StateStart:
+ if (ch >= '1' && ch <= '9') {
+ accumulator = ch - '0';
+ numberOfDigits = 1;
+ state = StateDigit;
+ break;
+ }
+
+ if (ch == '-') {
+ sign = Negative;
+ state = StateSign;
+ break;
+ }
+
+ if (ch == '+') {
+ sign = Positive;
+ state = StateSign;
+ break;
+ }
+
+ HandleCharAndBreak('0', StateZero);
+ HandleCharAndBreak('.', StateDot);
+ return nan();
+
+ case StateZero:
+ if (ch == '0')
+ break;
+
+ if (ch >= '1' && ch <= '9') {
+ accumulator = ch - '0';
+ numberOfDigits = 1;
+ state = StateDigit;
+ break;
+ }
+
+ HandleCharAndBreak('.', StateDot);
+ HandleTwoCharsAndBreak('E', 'e', StateE);
+ return nan();
+
+ default:
+ ASSERT_NOT_REACHED();
+ return nan();
+ }
+ }
+
+ if (state == StateZero)
+ return zero(sign);
+
+ if (state == StateDigit || state == StateEDigit || state == StateDotDigit) {
+ int resultExponent = exponent * (exponentSign == Negative ? -1 : 1) - numberOfDigitsAfterDot + numberOfExtraDigits;
+ if (resultExponent < ExponentMin)
+ return zero(Positive);
+
+ const int overflow = resultExponent - ExponentMax + 1;
+ if (overflow > 0) {
+ if (overflow + numberOfDigits - numberOfDigitsAfterDot > Precision)
+ return infinity(sign);
+ accumulator = scaleUp(accumulator, overflow);
+ resultExponent -= overflow;
+ }
+
+ return Decimal(sign, resultExponent, accumulator);
+ }
+
+ return nan();
+}
+
+Decimal Decimal::infinity(const Sign sign)
+{
+ return Decimal(EncodedData(sign, EncodedData::ClassInfinity));
+}
+
+Decimal Decimal::nan()
+{
+ return Decimal(EncodedData(Positive, EncodedData::ClassNaN));
+}
+
+Decimal Decimal::remainder(const Decimal& rhs) const
+{
+ const Decimal quotient = *this / rhs;
+ return quotient.isSpecial() ? quotient : *this - (quotient.isNegative() ? quotient.ceiling() : quotient.floor()) * rhs;
+}
+
+Decimal Decimal::round() const
+{
+ if (isSpecial())
+ return *this;
+
+ if (exponent() >= 0)
+ return *this;
+
+ uint64_t result = m_data.coefficient();
+ const int numberOfDigits = countDigits(result);
+ const int numberOfDropDigits = -exponent();
+ if (numberOfDigits < numberOfDropDigits)
+ return zero(Positive);
+
+ // We're implementing round-half-away-from-zero, so we only need the one
+ // (the most significant) fractional digit:
+ result = scaleDown(result, numberOfDropDigits - 1);
+ if (result % 10 >= 5)
+ result += 10;
+ result /= 10;
+ return Decimal(sign(), 0, result);
+}
+
+double Decimal::toDouble() const
+{
+ if (isFinite()) {
+ bool valid;
+ const double doubleValue = mozToDouble(toString(), &valid);
+ return valid ? doubleValue : std::numeric_limits<double>::quiet_NaN();
+ }
+
+ if (isInfinity())
+ return isNegative() ? -std::numeric_limits<double>::infinity() : std::numeric_limits<double>::infinity();
+
+ return std::numeric_limits<double>::quiet_NaN();
+}
+
+String Decimal::toString() const
+{
+ switch (m_data.formatClass()) {
+ case EncodedData::ClassInfinity:
+ return sign() ? "-Infinity" : "Infinity";
+
+ case EncodedData::ClassNaN:
+ return "NaN";
+
+ case EncodedData::ClassNormal:
+ case EncodedData::ClassZero:
+ break;
+
+ default:
+ ASSERT_NOT_REACHED();
+ return "";
+ }
+
+ StringBuilder builder;
+ if (sign())
+ builder.append('-');
+
+ int originalExponent = exponent();
+ uint64_t coefficient = m_data.coefficient();
+
+ if (originalExponent < 0) {
+ const int maxDigits = DBL_DIG;
+ uint64_t lastDigit = 0;
+ while (countDigits(coefficient) > maxDigits) {
+ lastDigit = coefficient % 10;
+ coefficient /= 10;
+ ++originalExponent;
+ }
+
+ if (lastDigit >= 5)
+ ++coefficient;
+
+ while (originalExponent < 0 && coefficient && !(coefficient % 10)) {
+ coefficient /= 10;
+ ++originalExponent;
+ }
+ }
+
+ const String digits = mozToString(coefficient);
+ int coefficientLength = static_cast<int>(digits.length());
+ const int adjustedExponent = originalExponent + coefficientLength - 1;
+ if (originalExponent <= 0 && adjustedExponent >= -6) {
+ if (!originalExponent) {
+ builder.append(digits);
+ return builder.toString();
+ }
+
+ if (adjustedExponent >= 0) {
+ for (int i = 0; i < coefficientLength; ++i) {
+ builder.append(digits[i]);
+ if (i == adjustedExponent)
+ builder.append('.');
+ }
+ return builder.toString();
+ }
+
+ builder.appendLiteral("0.");
+ for (int i = adjustedExponent + 1; i < 0; ++i)
+ builder.append('0');
+
+ builder.append(digits);
+
+ } else {
+ builder.append(digits[0]);
+ while (coefficientLength >= 2 && digits[coefficientLength - 1] == '0')
+ --coefficientLength;
+ if (coefficientLength >= 2) {
+ builder.append('.');
+ for (int i = 1; i < coefficientLength; ++i)
+ builder.append(digits[i]);
+ }
+
+ if (adjustedExponent) {
+ builder.append(adjustedExponent < 0 ? "e" : "e+");
+ builder.appendNumber(adjustedExponent);
+ }
+ }
+ return builder.toString();
+}
+
+bool Decimal::toString(char* strBuf, size_t bufLength) const
+{
+ ASSERT(bufLength > 0);
+ String str = toString();
+ size_t length = str.copy(strBuf, bufLength);
+ if (length < bufLength) {
+ strBuf[length] = '\0';
+ return true;
+ }
+ strBuf[bufLength - 1] = '\0';
+ return false;
+}
+
+Decimal Decimal::zero(Sign sign)
+{
+ return Decimal(EncodedData(sign, EncodedData::ClassZero));
+}
+
+} // namespace WebCore
+
diff --git a/mfbt/decimal/Decimal.h b/mfbt/decimal/Decimal.h
new file mode 100644
index 0000000..8032fd6
--- /dev/null
+++ b/mfbt/decimal/Decimal.h
@@ -0,0 +1,213 @@
+/*
+ * Copyright (C) 2012 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * 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.
+ * * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * 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.
+ */
+
+/**
+ * Imported from:
+ * http://src.chromium.org/viewvc/blink/trunk/Source/core/platform/Decimal.h
+ * Check hg log for the svn rev of the last update from Blink core.
+ */
+
+#ifndef Decimal_h
+#define Decimal_h
+
+#include "mozilla/Assertions.h"
+#include "mozilla/StandardInteger.h"
+#include "mozilla/Types.h"
+
+#include <string>
+
+#ifndef ASSERT
+#define DEFINED_ASSERT_FOR_DECIMAL_H 1
+#define ASSERT MOZ_ASSERT
+#endif
+
+// To use WTF_MAKE_FAST_ALLOCATED we'd need:
+// http://src.chromium.org/viewvc/blink/trunk/Source/wtf/FastMalloc.h
+// Since we don't allocate Decimal objects, no need.
+#define WTF_MAKE_FAST_ALLOCATED \
+ void ignore_this_dummy_method() MOZ_DELETE
+
+namespace WebCore {
+
+namespace DecimalPrivate {
+class SpecialValueHandler;
+}
+
+// This class represents decimal base floating point number.
+//
+// FIXME: Once all C++ compiler support decimal type, we should replace this
+// class to compiler supported one. See below URI for current status of decimal
+// type for C++: // http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2006/n1977.html
+class Decimal {
+ WTF_MAKE_FAST_ALLOCATED;
+public:
+ enum Sign {
+ Positive,
+ Negative,
+ };
+
+ // You should not use EncodedData other than unit testing.
+ class EncodedData {
+ // For accessing FormatClass.
+ friend class Decimal;
+ friend class DecimalPrivate::SpecialValueHandler;
+ public:
+ EncodedData(Sign, int exponent, uint64_t coefficient);
+
+ bool operator==(const EncodedData&) const;
+ bool operator!=(const EncodedData& another) const { return !operator==(another); }
+
+ uint64_t coefficient() const { return m_coefficient; }
+ int countDigits() const;
+ int exponent() const { return m_exponent; }
+ bool isFinite() const { return !isSpecial(); }
+ bool isInfinity() const { return m_formatClass == ClassInfinity; }
+ bool isNaN() const { return m_formatClass == ClassNaN; }
+ bool isSpecial() const { return m_formatClass == ClassInfinity || m_formatClass == ClassNaN; }
+ bool isZero() const { return m_formatClass == ClassZero; }
+ Sign sign() const { return m_sign; }
+ void setSign(Sign sign) { m_sign = sign; }
+
+ private:
+ enum FormatClass {
+ ClassInfinity,
+ ClassNormal,
+ ClassNaN,
+ ClassZero,
+ };
+
+ EncodedData(Sign, FormatClass);
+ FormatClass formatClass() const { return m_formatClass; }
+
+ uint64_t m_coefficient;
+ int16_t m_exponent;
+ FormatClass m_formatClass;
+ Sign m_sign;
+ };
+
+ MFBT_API Decimal(int32_t = 0);
+ MFBT_API Decimal(Sign, int exponent, uint64_t coefficient);
+ MFBT_API Decimal(const Decimal&);
+
+ MFBT_API Decimal& operator=(const Decimal&);
+ MFBT_API Decimal& operator+=(const Decimal&);
+ MFBT_API Decimal& operator-=(const Decimal&);
+ MFBT_API Decimal& operator*=(const Decimal&);
+ MFBT_API Decimal& operator/=(const Decimal&);
+
+ MFBT_API Decimal operator-() const;
+
+ MFBT_API bool operator==(const Decimal&) const;
+ MFBT_API bool operator!=(const Decimal&) const;
+ MFBT_API bool operator<(const Decimal&) const;
+ MFBT_API bool operator<=(const Decimal&) const;
+ MFBT_API bool operator>(const Decimal&) const;
+ MFBT_API bool operator>=(const Decimal&) const;
+
+ MFBT_API Decimal operator+(const Decimal&) const;
+ MFBT_API Decimal operator-(const Decimal&) const;
+ MFBT_API Decimal operator*(const Decimal&) const;
+ MFBT_API Decimal operator/(const Decimal&) const;
+
+ int exponent() const
+ {
+ ASSERT(isFinite());
+ return m_data.exponent();
+ }
+
+ bool isFinite() const { return m_data.isFinite(); }
+ bool isInfinity() const { return m_data.isInfinity(); }
+ bool isNaN() const { return m_data.isNaN(); }
+ bool isNegative() const { return sign() == Negative; }
+ bool isPositive() const { return sign() == Positive; }
+ bool isSpecial() const { return m_data.isSpecial(); }
+ bool isZero() const { return m_data.isZero(); }
+
+ MFBT_API Decimal abs() const;
+ MFBT_API Decimal ceiling() const;
+ MFBT_API Decimal floor() const;
+ MFBT_API Decimal remainder(const Decimal&) const;
+ MFBT_API Decimal round() const;
+
+ MFBT_API double toDouble() const;
+ // Note: toString method supports infinity and nan but fromString not.
+ MFBT_API std::string toString() const;
+ MFBT_API bool toString(char* strBuf, size_t bufLength) const;
+
+ static MFBT_API Decimal fromDouble(double);
+ // fromString supports following syntax EBNF:
+ // number ::= sign? digit+ ('.' digit*) (exponent-marker sign? digit+)?
+ // | sign? '.' digit+ (exponent-marker sign? digit+)?
+ // sign ::= '+' | '-'
+ // exponent-marker ::= 'e' | 'E'
+ // digit ::= '0' | '1' | ... | '9'
+ // Note: fromString doesn't support "infinity" and "nan".
+ static MFBT_API Decimal fromString(const std::string& aValue);
+ static MFBT_API Decimal infinity(Sign);
+ static MFBT_API Decimal nan();
+ static MFBT_API Decimal zero(Sign);
+
+ // You should not use below methods. We expose them for unit testing.
+ MFBT_API explicit Decimal(const EncodedData&);
+ const EncodedData& value() const { return m_data; }
+
+private:
+ struct AlignedOperands {
+ uint64_t lhsCoefficient;
+ uint64_t rhsCoefficient;
+ int exponent;
+ };
+
+ MFBT_API Decimal(double);
+ MFBT_API Decimal compareTo(const Decimal&) const;
+
+ static MFBT_API AlignedOperands alignOperands(const Decimal& lhs, const Decimal& rhs);
+ static inline Sign invertSign(Sign sign) { return sign == Negative ? Positive : Negative; }
+
+ Sign sign() const { return m_data.sign(); }
+
+ EncodedData m_data;
+};
+
+} // namespace WebCore
+
+namespace mozilla {
+ typedef WebCore::Decimal Decimal;
+}
+
+#undef WTF_MAKE_FAST_ALLOCATED
+
+#ifdef DEFINED_ASSERT_FOR_DECIMAL_H
+#undef DEFINED_ASSERT_FOR_DECIMAL_H
+#undef ASSERT
+#endif
+
+#endif // Decimal_h
+
diff --git a/mfbt/decimal/LICENSE-APPLE b/mfbt/decimal/LICENSE-APPLE
new file mode 100644
index 0000000..f29b41c
--- /dev/null
+++ b/mfbt/decimal/LICENSE-APPLE
@@ -0,0 +1,21 @@
+Copyright (C) 2005, 2006, 2007, 2008, 2009 Apple Inc. 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 APPLE INC. AND ITS 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 APPLE INC. OR ITS 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.
diff --git a/mfbt/decimal/LICENSE-LGPL-2 b/mfbt/decimal/LICENSE-LGPL-2
new file mode 100644
index 0000000..0e1187b
--- /dev/null
+++ b/mfbt/decimal/LICENSE-LGPL-2
@@ -0,0 +1,481 @@
+ GNU LIBRARY GENERAL PUBLIC LICENSE
+ Version 2, June 1991
+
+ Copyright (C) 1991 Free Software Foundation, Inc.
+ 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+[This is the first released version of the library GPL. It is
+ numbered 2 because it goes with version 2 of the ordinary GPL.]
+
+ Preamble
+
+ The licenses for most software are designed to take away your
+freedom to share and change it. By contrast, the GNU General Public
+Licenses are intended to guarantee your freedom to share and change
+free software--to make sure the software is free for all its users.
+
+ This license, the Library General Public License, applies to some
+specially designated Free Software Foundation software, and to any
+other libraries whose authors decide to use it. You can use it for
+your libraries, too.
+
+ When we speak of free software, we are referring to freedom, not
+price. Our General Public Licenses are designed to make sure that you
+have the freedom to distribute copies of free software (and charge for
+this service if you wish), that you receive source code or can get it
+if you want it, that you can change the software or use pieces of it
+in new free programs; and that you know you can do these things.
+
+ To protect your rights, we need to make restrictions that forbid
+anyone to deny you these rights or to ask you to surrender the rights.
+These restrictions translate to certain responsibilities for you if
+you distribute copies of the library, or if you modify it.
+
+ For example, if you distribute copies of the library, whether gratis
+or for a fee, you must give the recipients all the rights that we gave
+you. You must make sure that they, too, receive or can get the source
+code. If you link a program with the library, you must provide
+complete object files to the recipients so that they can relink them
+with the library, after making changes to the library and recompiling
+it. And you must show them these terms so they know their rights.
+
+ Our method of protecting your rights has two steps: (1) copyright
+the library, and (2) offer you this license which gives you legal
+permission to copy, distribute and/or modify the library.
+
+ Also, for each distributor's protection, we want to make certain
+that everyone understands that there is no warranty for this free
+library. If the library is modified by someone else and passed on, we
+want its recipients to know that what they have is not the original
+version, so that any problems introduced by others will not reflect on
+the original authors' reputations.
+
+ Finally, any free program is threatened constantly by software
+patents. We wish to avoid the danger that companies distributing free
+software will individually obtain patent licenses, thus in effect
+transforming the program into proprietary software. To prevent this,
+we have made it clear that any patent must be licensed for everyone's
+free use or not licensed at all.
+
+ Most GNU software, including some libraries, is covered by the ordinary
+GNU General Public License, which was designed for utility programs. This
+license, the GNU Library General Public License, applies to certain
+designated libraries. This license is quite different from the ordinary
+one; be sure to read it in full, and don't assume that anything in it is
+the same as in the ordinary license.
+
+ The reason we have a separate public license for some libraries is that
+they blur the distinction we usually make between modifying or adding to a
+program and simply using it. Linking a program with a library, without
+changing the library, is in some sense simply using the library, and is
+analogous to running a utility program or application program. However, in
+a textual and legal sense, the linked executable is a combined work, a
+derivative of the original library, and the ordinary General Public License
+treats it as such.
+
+ Because of this blurred distinction, using the ordinary General
+Public License for libraries did not effectively promote software
+sharing, because most developers did not use the libraries. We
+concluded that weaker conditions might promote sharing better.
+
+ However, unrestricted linking of non-free programs would deprive the
+users of those programs of all benefit from the free status of the
+libraries themselves. This Library General Public License is intended to
+permit developers of non-free programs to use free libraries, while
+preserving your freedom as a user of such programs to change the free
+libraries that are incorporated in them. (We have not seen how to achieve
+this as regards changes in header files, but we have achieved it as regards
+changes in the actual functions of the Library.) The hope is that this
+will lead to faster development of free libraries.
+
+ The precise terms and conditions for copying, distribution and
+modification follow. Pay close attention to the difference between a
+"work based on the library" and a "work that uses the library". The
+former contains code derived from the library, while the latter only
+works together with the library.
+
+ Note that it is possible for a library to be covered by the ordinary
+General Public License rather than by this special one.
+
+ GNU LIBRARY GENERAL PUBLIC LICENSE
+ TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
+
+ 0. This License Agreement applies to any software library which
+contains a notice placed by the copyright holder or other authorized
+party saying it may be distributed under the terms of this Library
+General Public License (also called "this License"). Each licensee is
+addressed as "you".
+
+ A "library" means a collection of software functions and/or data
+prepared so as to be conveniently linked with application programs
+(which use some of those functions and data) to form executables.
+
+ The "Library", below, refers to any such software library or work
+which has been distributed under these terms. A "work based on the
+Library" means either the Library or any derivative work under
+copyright law: that is to say, a work containing the Library or a
+portion of it, either verbatim or with modifications and/or translated
+straightforwardly into another language. (Hereinafter, translation is
+included without limitation in the term "modification".)
+
+ "Source code" for a work means the preferred form of the work for
+making modifications to it. For a library, complete source code means
+all the source code for all modules it contains, plus any associated
+interface definition files, plus the scripts used to control compilation
+and installation of the library.
+
+ Activities other than copying, distribution and modification are not
+covered by this License; they are outside its scope. The act of
+running a program using the Library is not restricted, and output from
+such a program is covered only if its contents constitute a work based
+on the Library (independent of the use of the Library in a tool for
+writing it). Whether that is true depends on what the Library does
+and what the program that uses the Library does.
+
+ 1. You may copy and distribute verbatim copies of the Library's
+complete source code as you receive it, in any medium, provided that
+you conspicuously and appropriately publish on each copy an
+appropriate copyright notice and disclaimer of warranty; keep intact
+all the notices that refer to this License and to the absence of any
+warranty; and distribute a copy of this License along with the
+Library.
+
+ You may charge a fee for the physical act of transferring a copy,
+and you may at your option offer warranty protection in exchange for a
+fee.
+
+ 2. You may modify your copy or copies of the Library or any portion
+of it, thus forming a work based on the Library, and copy and
+distribute such modifications or work under the terms of Section 1
+above, provided that you also meet all of these conditions:
+
+ a) The modified work must itself be a software library.
+
+ b) You must cause the files modified to carry prominent notices
+ stating that you changed the files and the date of any change.
+
+ c) You must cause the whole of the work to be licensed at no
+ charge to all third parties under the terms of this License.
+
+ d) If a facility in the modified Library refers to a function or a
+ table of data to be supplied by an application program that uses
+ the facility, other than as an argument passed when the facility
+ is invoked, then you must make a good faith effort to ensure that,
+ in the event an application does not supply such function or
+ table, the facility still operates, and performs whatever part of
+ its purpose remains meaningful.
+
+ (For example, a function in a library to compute square roots has
+ a purpose that is entirely well-defined independent of the
+ application. Therefore, Subsection 2d requires that any
+ application-supplied function or table used by this function must
+ be optional: if the application does not supply it, the square
+ root function must still compute square roots.)
+
+These requirements apply to the modified work as a whole. If
+identifiable sections of that work are not derived from the Library,
+and can be reasonably considered independent and separate works in
+themselves, then this License, and its terms, do not apply to those
+sections when you distribute them as separate works. But when you
+distribute the same sections as part of a whole which is a work based
+on the Library, the distribution of the whole must be on the terms of
+this License, whose permissions for other licensees extend to the
+entire whole, and thus to each and every part regardless of who wrote
+it.
+
+Thus, it is not the intent of this section to claim rights or contest
+your rights to work written entirely by you; rather, the intent is to
+exercise the right to control the distribution of derivative or
+collective works based on the Library.
+
+In addition, mere aggregation of another work not based on the Library
+with the Library (or with a work based on the Library) on a volume of
+a storage or distribution medium does not bring the other work under
+the scope of this License.
+
+ 3. You may opt to apply the terms of the ordinary GNU General Public
+License instead of this License to a given copy of the Library. To do
+this, you must alter all the notices that refer to this License, so
+that they refer to the ordinary GNU General Public License, version 2,
+instead of to this License. (If a newer version than version 2 of the
+ordinary GNU General Public License has appeared, then you can specify
+that version instead if you wish.) Do not make any other change in
+these notices.
+
+ Once this change is made in a given copy, it is irreversible for
+that copy, so the ordinary GNU General Public License applies to all
+subsequent copies and derivative works made from that copy.
+
+ This option is useful when you wish to copy part of the code of
+the Library into a program that is not a library.
+
+ 4. You may copy and distribute the Library (or a portion or
+derivative of it, under Section 2) in object code or executable form
+under the terms of Sections 1 and 2 above provided that you accompany
+it with the complete corresponding machine-readable source code, which
+must be distributed under the terms of Sections 1 and 2 above on a
+medium customarily used for software interchange.
+
+ If distribution of object code is made by offering access to copy
+from a designated place, then offering equivalent access to copy the
+source code from the same place satisfies the requirement to
+distribute the source code, even though third parties are not
+compelled to copy the source along with the object code.
+
+ 5. A program that contains no derivative of any portion of the
+Library, but is designed to work with the Library by being compiled or
+linked with it, is called a "work that uses the Library". Such a
+work, in isolation, is not a derivative work of the Library, and
+therefore falls outside the scope of this License.
+
+ However, linking a "work that uses the Library" with the Library
+creates an executable that is a derivative of the Library (because it
+contains portions of the Library), rather than a "work that uses the
+library". The executable is therefore covered by this License.
+Section 6 states terms for distribution of such executables.
+
+ When a "work that uses the Library" uses material from a header file
+that is part of the Library, the object code for the work may be a
+derivative work of the Library even though the source code is not.
+Whether this is true is especially significant if the work can be
+linked without the Library, or if the work is itself a library. The
+threshold for this to be true is not precisely defined by law.
+
+ If such an object file uses only numerical parameters, data
+structure layouts and accessors, and small macros and small inline
+functions (ten lines or less in length), then the use of the object
+file is unrestricted, regardless of whether it is legally a derivative
+work. (Executables containing this object code plus portions of the
+Library will still fall under Section 6.)
+
+ Otherwise, if the work is a derivative of the Library, you may
+distribute the object code for the work under the terms of Section 6.
+Any executables containing that work also fall under Section 6,
+whether or not they are linked directly with the Library itself.
+
+ 6. As an exception to the Sections above, you may also compile or
+link a "work that uses the Library" with the Library to produce a
+work containing portions of the Library, and distribute that work
+under terms of your choice, provided that the terms permit
+modification of the work for the customer's own use and reverse
+engineering for debugging such modifications.
+
+ You must give prominent notice with each copy of the work that the
+Library is used in it and that the Library and its use are covered by
+this License. You must supply a copy of this License. If the work
+during execution displays copyright notices, you must include the
+copyright notice for the Library among them, as well as a reference
+directing the user to the copy of this License. Also, you must do one
+of these things:
+
+ a) Accompany the work with the complete corresponding
+ machine-readable source code for the Library including whatever
+ changes were used in the work (which must be distributed under
+ Sections 1 and 2 above); and, if the work is an executable linked
+ with the Library, with the complete machine-readable "work that
+ uses the Library", as object code and/or source code, so that the
+ user can modify the Library and then relink to produce a modified
+ executable containing the modified Library. (It is understood
+ that the user who changes the contents of definitions files in the
+ Library will not necessarily be able to recompile the application
+ to use the modified definitions.)
+
+ b) Accompany the work with a written offer, valid for at
+ least three years, to give the same user the materials
+ specified in Subsection 6a, above, for a charge no more
+ than the cost of performing this distribution.
+
+ c) If distribution of the work is made by offering access to copy
+ from a designated place, offer equivalent access to copy the above
+ specified materials from the same place.
+
+ d) Verify that the user has already received a copy of these
+ materials or that you have already sent this user a copy.
+
+ For an executable, the required form of the "work that uses the
+Library" must include any data and utility programs needed for
+reproducing the executable from it. However, as a special exception,
+the source code distributed need not include anything that is normally
+distributed (in either source or binary form) with the major
+components (compiler, kernel, and so on) of the operating system on
+which the executable runs, unless that component itself accompanies
+the executable.
+
+ It may happen that this requirement contradicts the license
+restrictions of other proprietary libraries that do not normally
+accompany the operating system. Such a contradiction means you cannot
+use both them and the Library together in an executable that you
+distribute.
+
+ 7. You may place library facilities that are a work based on the
+Library side-by-side in a single library together with other library
+facilities not covered by this License, and distribute such a combined
+library, provided that the separate distribution of the work based on
+the Library and of the other library facilities is otherwise
+permitted, and provided that you do these two things:
+
+ a) Accompany the combined library with a copy of the same work
+ based on the Library, uncombined with any other library
+ facilities. This must be distributed under the terms of the
+ Sections above.
+
+ b) Give prominent notice with the combined library of the fact
+ that part of it is a work based on the Library, and explaining
+ where to find the accompanying uncombined form of the same work.
+
+ 8. You may not copy, modify, sublicense, link with, or distribute
+the Library except as expressly provided under this License. Any
+attempt otherwise to copy, modify, sublicense, link with, or
+distribute the Library is void, and will automatically terminate your
+rights under this License. However, parties who have received copies,
+or rights, from you under this License will not have their licenses
+terminated so long as such parties remain in full compliance.
+
+ 9. You are not required to accept this License, since you have not
+signed it. However, nothing else grants you permission to modify or
+distribute the Library or its derivative works. These actions are
+prohibited by law if you do not accept this License. Therefore, by
+modifying or distributing the Library (or any work based on the
+Library), you indicate your acceptance of this License to do so, and
+all its terms and conditions for copying, distributing or modifying
+the Library or works based on it.
+
+ 10. Each time you redistribute the Library (or any work based on the
+Library), the recipient automatically receives a license from the
+original licensor to copy, distribute, link with or modify the Library
+subject to these terms and conditions. You may not impose any further
+restrictions on the recipients' exercise of the rights granted herein.
+You are not responsible for enforcing compliance by third parties to
+this License.
+
+ 11. If, as a consequence of a court judgment or allegation of patent
+infringement or for any other reason (not limited to patent issues),
+conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License. If you cannot
+distribute so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you
+may not distribute the Library at all. For example, if a patent
+license would not permit royalty-free redistribution of the Library by
+all those who receive copies directly or indirectly through you, then
+the only way you could satisfy both it and this License would be to
+refrain entirely from distribution of the Library.
+
+If any portion of this section is held invalid or unenforceable under any
+particular circumstance, the balance of the section is intended to apply,
+and the section as a whole is intended to apply in other circumstances.
+
+It is not the purpose of this section to induce you to infringe any
+patents or other property right claims or to contest validity of any
+such claims; this section has the sole purpose of protecting the
+integrity of the free software distribution system which is
+implemented by public license practices. Many people have made
+generous contributions to the wide range of software distributed
+through that system in reliance on consistent application of that
+system; it is up to the author/donor to decide if he or she is willing
+to distribute software through any other system and a licensee cannot
+impose that choice.
+
+This section is intended to make thoroughly clear what is believed to
+be a consequence of the rest of this License.
+
+ 12. If the distribution and/or use of the Library is restricted in
+certain countries either by patents or by copyrighted interfaces, the
+original copyright holder who places the Library under this License may add
+an explicit geographical distribution limitation excluding those countries,
+so that distribution is permitted only in or among countries not thus
+excluded. In such case, this License incorporates the limitation as if
+written in the body of this License.
+
+ 13. The Free Software Foundation may publish revised and/or new
+versions of the Library General Public License from time to time.
+Such new versions will be similar in spirit to the present version,
+but may differ in detail to address new problems or concerns.
+
+Each version is given a distinguishing version number. If the Library
+specifies a version number of this License which applies to it and
+"any later version", you have the option of following the terms and
+conditions either of that version or of any later version published by
+the Free Software Foundation. If the Library does not specify a
+license version number, you may choose any version ever published by
+the Free Software Foundation.
+
+ 14. If you wish to incorporate parts of the Library into other free
+programs whose distribution conditions are incompatible with these,
+write to the author to ask for permission. For software which is
+copyrighted by the Free Software Foundation, write to the Free
+Software Foundation; we sometimes make exceptions for this. Our
+decision will be guided by the two goals of preserving the free status
+of all derivatives of our free software and of promoting the sharing
+and reuse of software generally.
+
+ NO WARRANTY
+
+ 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO
+WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW.
+EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR
+OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY
+KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE
+IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE
+LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME
+THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
+
+ 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN
+WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY
+AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU
+FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR
+CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE
+LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING
+RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A
+FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF
+SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
+DAMAGES.
+
+ END OF TERMS AND CONDITIONS
+
+ How to Apply These Terms to Your New Libraries
+
+ If you develop a new library, and you want it to be of the greatest
+possible use to the public, we recommend making it free software that
+everyone can redistribute and change. You can do so by permitting
+redistribution under these terms (or, alternatively, under the terms of the
+ordinary General Public License).
+
+ To apply these terms, attach the following notices to the library. It is
+safest to attach them to the start of each source file to most effectively
+convey the exclusion of warranty; and each file should have at least the
+"copyright" line and a pointer to where the full notice is found.
+
+ <one line to give the library's name and a brief idea of what it does.>
+ Copyright (C) <year> <name of author>
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Library General Public
+ License as published by the Free Software Foundation; either
+ version 2 of the License, or (at your option) any later version.
+
+ This library is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Library General Public License for more details.
+
+ You should have received a copy of the GNU Library General Public
+ License along with this library; if not, write to the Free
+ Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+
+Also add information on how to contact you by electronic and paper mail.
+
+You should also get your employer (if you work as a programmer) or your
+school, if any, to sign a "copyright disclaimer" for the library, if
+necessary. Here is a sample; alter the names:
+
+ Yoyodyne, Inc., hereby disclaims all copyright interest in the
+ library `Frob' (a library for tweaking knobs) written by James Random Hacker.
+
+ <signature of Ty Coon>, 1 April 1990
+ Ty Coon, President of Vice
+
+That's all there is to it!
diff --git a/mfbt/decimal/LICENSE-LGPL-2.1 b/mfbt/decimal/LICENSE-LGPL-2.1
new file mode 100644
index 0000000..b2787a6
--- /dev/null
+++ b/mfbt/decimal/LICENSE-LGPL-2.1
@@ -0,0 +1,502 @@
+ GNU LESSER GENERAL PUBLIC LICENSE
+ Version 2.1, February 1999
+
+ Copyright (C) 1991, 1999 Free Software Foundation, Inc.
+ 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+[This is the first released version of the Lesser GPL. It also counts
+ as the successor of the GNU Library Public License, version 2, hence
+ the version number 2.1.]
+
+ Preamble
+
+ The licenses for most software are designed to take away your
+freedom to share and change it. By contrast, the GNU General Public
+Licenses are intended to guarantee your freedom to share and change
+free software--to make sure the software is free for all its users.
+
+ This license, the Lesser General Public License, applies to some
+specially designated software packages--typically libraries--of the
+Free Software Foundation and other authors who decide to use it. You
+can use it too, but we suggest you first think carefully about whether
+this license or the ordinary General Public License is the better
+strategy to use in any particular case, based on the explanations below.
+
+ When we speak of free software, we are referring to freedom of use,
+not price. Our General Public Licenses are designed to make sure that
+you have the freedom to distribute copies of free software (and charge
+for this service if you wish); that you receive source code or can get
+it if you want it; that you can change the software and use pieces of
+it in new free programs; and that you are informed that you can do
+these things.
+
+ To protect your rights, we need to make restrictions that forbid
+distributors to deny you these rights or to ask you to surrender these
+rights. These restrictions translate to certain responsibilities for
+you if you distribute copies of the library or if you modify it.
+
+ For example, if you distribute copies of the library, whether gratis
+or for a fee, you must give the recipients all the rights that we gave
+you. You must make sure that they, too, receive or can get the source
+code. If you link other code with the library, you must provide
+complete object files to the recipients, so that they can relink them
+with the library after making changes to the library and recompiling
+it. And you must show them these terms so they know their rights.
+
+ We protect your rights with a two-step method: (1) we copyright the
+library, and (2) we offer you this license, which gives you legal
+permission to copy, distribute and/or modify the library.
+
+ To protect each distributor, we want to make it very clear that
+there is no warranty for the free library. Also, if the library is
+modified by someone else and passed on, the recipients should know
+that what they have is not the original version, so that the original
+author's reputation will not be affected by problems that might be
+introduced by others.
+
+ Finally, software patents pose a constant threat to the existence of
+any free program. We wish to make sure that a company cannot
+effectively restrict the users of a free program by obtaining a
+restrictive license from a patent holder. Therefore, we insist that
+any patent license obtained for a version of the library must be
+consistent with the full freedom of use specified in this license.
+
+ Most GNU software, including some libraries, is covered by the
+ordinary GNU General Public License. This license, the GNU Lesser
+General Public License, applies to certain designated libraries, and
+is quite different from the ordinary General Public License. We use
+this license for certain libraries in order to permit linking those
+libraries into non-free programs.
+
+ When a program is linked with a library, whether statically or using
+a shared library, the combination of the two is legally speaking a
+combined work, a derivative of the original library. The ordinary
+General Public License therefore permits such linking only if the
+entire combination fits its criteria of freedom. The Lesser General
+Public License permits more lax criteria for linking other code with
+the library.
+
+ We call this license the "Lesser" General Public License because it
+does Less to protect the user's freedom than the ordinary General
+Public License. It also provides other free software developers Less
+of an advantage over competing non-free programs. These disadvantages
+are the reason we use the ordinary General Public License for many
+libraries. However, the Lesser license provides advantages in certain
+special circumstances.
+
+ For example, on rare occasions, there may be a special need to
+encourage the widest possible use of a certain library, so that it becomes
+a de-facto standard. To achieve this, non-free programs must be
+allowed to use the library. A more frequent case is that a free
+library does the same job as widely used non-free libraries. In this
+case, there is little to gain by limiting the free library to free
+software only, so we use the Lesser General Public License.
+
+ In other cases, permission to use a particular library in non-free
+programs enables a greater number of people to use a large body of
+free software. For example, permission to use the GNU C Library in
+non-free programs enables many more people to use the whole GNU
+operating system, as well as its variant, the GNU/Linux operating
+system.
+
+ Although the Lesser General Public License is Less protective of the
+users' freedom, it does ensure that the user of a program that is
+linked with the Library has the freedom and the wherewithal to run
+that program using a modified version of the Library.
+
+ The precise terms and conditions for copying, distribution and
+modification follow. Pay close attention to the difference between a
+"work based on the library" and a "work that uses the library". The
+former contains code derived from the library, whereas the latter must
+be combined with the library in order to run.
+
+ GNU LESSER GENERAL PUBLIC LICENSE
+ TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
+
+ 0. This License Agreement applies to any software library or other
+program which contains a notice placed by the copyright holder or
+other authorized party saying it may be distributed under the terms of
+this Lesser General Public License (also called "this License").
+Each licensee is addressed as "you".
+
+ A "library" means a collection of software functions and/or data
+prepared so as to be conveniently linked with application programs
+(which use some of those functions and data) to form executables.
+
+ The "Library", below, refers to any such software library or work
+which has been distributed under these terms. A "work based on the
+Library" means either the Library or any derivative work under
+copyright law: that is to say, a work containing the Library or a
+portion of it, either verbatim or with modifications and/or translated
+straightforwardly into another language. (Hereinafter, translation is
+included without limitation in the term "modification".)
+
+ "Source code" for a work means the preferred form of the work for
+making modifications to it. For a library, complete source code means
+all the source code for all modules it contains, plus any associated
+interface definition files, plus the scripts used to control compilation
+and installation of the library.
+
+ Activities other than copying, distribution and modification are not
+covered by this License; they are outside its scope. The act of
+running a program using the Library is not restricted, and output from
+such a program is covered only if its contents constitute a work based
+on the Library (independent of the use of the Library in a tool for
+writing it). Whether that is true depends on what the Library does
+and what the program that uses the Library does.
+
+ 1. You may copy and distribute verbatim copies of the Library's
+complete source code as you receive it, in any medium, provided that
+you conspicuously and appropriately publish on each copy an
+appropriate copyright notice and disclaimer of warranty; keep intact
+all the notices that refer to this License and to the absence of any
+warranty; and distribute a copy of this License along with the
+Library.
+
+ You may charge a fee for the physical act of transferring a copy,
+and you may at your option offer warranty protection in exchange for a
+fee.
+
+ 2. You may modify your copy or copies of the Library or any portion
+of it, thus forming a work based on the Library, and copy and
+distribute such modifications or work under the terms of Section 1
+above, provided that you also meet all of these conditions:
+
+ a) The modified work must itself be a software library.
+
+ b) You must cause the files modified to carry prominent notices
+ stating that you changed the files and the date of any change.
+
+ c) You must cause the whole of the work to be licensed at no
+ charge to all third parties under the terms of this License.
+
+ d) If a facility in the modified Library refers to a function or a
+ table of data to be supplied by an application program that uses
+ the facility, other than as an argument passed when the facility
+ is invoked, then you must make a good faith effort to ensure that,
+ in the event an application does not supply such function or
+ table, the facility still operates, and performs whatever part of
+ its purpose remains meaningful.
+
+ (For example, a function in a library to compute square roots has
+ a purpose that is entirely well-defined independent of the
+ application. Therefore, Subsection 2d requires that any
+ application-supplied function or table used by this function must
+ be optional: if the application does not supply it, the square
+ root function must still compute square roots.)
+
+These requirements apply to the modified work as a whole. If
+identifiable sections of that work are not derived from the Library,
+and can be reasonably considered independent and separate works in
+themselves, then this License, and its terms, do not apply to those
+sections when you distribute them as separate works. But when you
+distribute the same sections as part of a whole which is a work based
+on the Library, the distribution of the whole must be on the terms of
+this License, whose permissions for other licensees extend to the
+entire whole, and thus to each and every part regardless of who wrote
+it.
+
+Thus, it is not the intent of this section to claim rights or contest
+your rights to work written entirely by you; rather, the intent is to
+exercise the right to control the distribution of derivative or
+collective works based on the Library.
+
+In addition, mere aggregation of another work not based on the Library
+with the Library (or with a work based on the Library) on a volume of
+a storage or distribution medium does not bring the other work under
+the scope of this License.
+
+ 3. You may opt to apply the terms of the ordinary GNU General Public
+License instead of this License to a given copy of the Library. To do
+this, you must alter all the notices that refer to this License, so
+that they refer to the ordinary GNU General Public License, version 2,
+instead of to this License. (If a newer version than version 2 of the
+ordinary GNU General Public License has appeared, then you can specify
+that version instead if you wish.) Do not make any other change in
+these notices.
+
+ Once this change is made in a given copy, it is irreversible for
+that copy, so the ordinary GNU General Public License applies to all
+subsequent copies and derivative works made from that copy.
+
+ This option is useful when you wish to copy part of the code of
+the Library into a program that is not a library.
+
+ 4. You may copy and distribute the Library (or a portion or
+derivative of it, under Section 2) in object code or executable form
+under the terms of Sections 1 and 2 above provided that you accompany
+it with the complete corresponding machine-readable source code, which
+must be distributed under the terms of Sections 1 and 2 above on a
+medium customarily used for software interchange.
+
+ If distribution of object code is made by offering access to copy
+from a designated place, then offering equivalent access to copy the
+source code from the same place satisfies the requirement to
+distribute the source code, even though third parties are not
+compelled to copy the source along with the object code.
+
+ 5. A program that contains no derivative of any portion of the
+Library, but is designed to work with the Library by being compiled or
+linked with it, is called a "work that uses the Library". Such a
+work, in isolation, is not a derivative work of the Library, and
+therefore falls outside the scope of this License.
+
+ However, linking a "work that uses the Library" with the Library
+creates an executable that is a derivative of the Library (because it
+contains portions of the Library), rather than a "work that uses the
+library". The executable is therefore covered by this License.
+Section 6 states terms for distribution of such executables.
+
+ When a "work that uses the Library" uses material from a header file
+that is part of the Library, the object code for the work may be a
+derivative work of the Library even though the source code is not.
+Whether this is true is especially significant if the work can be
+linked without the Library, or if the work is itself a library. The
+threshold for this to be true is not precisely defined by law.
+
+ If such an object file uses only numerical parameters, data
+structure layouts and accessors, and small macros and small inline
+functions (ten lines or less in length), then the use of the object
+file is unrestricted, regardless of whether it is legally a derivative
+work. (Executables containing this object code plus portions of the
+Library will still fall under Section 6.)
+
+ Otherwise, if the work is a derivative of the Library, you may
+distribute the object code for the work under the terms of Section 6.
+Any executables containing that work also fall under Section 6,
+whether or not they are linked directly with the Library itself.
+
+ 6. As an exception to the Sections above, you may also combine or
+link a "work that uses the Library" with the Library to produce a
+work containing portions of the Library, and distribute that work
+under terms of your choice, provided that the terms permit
+modification of the work for the customer's own use and reverse
+engineering for debugging such modifications.
+
+ You must give prominent notice with each copy of the work that the
+Library is used in it and that the Library and its use are covered by
+this License. You must supply a copy of this License. If the work
+during execution displays copyright notices, you must include the
+copyright notice for the Library among them, as well as a reference
+directing the user to the copy of this License. Also, you must do one
+of these things:
+
+ a) Accompany the work with the complete corresponding
+ machine-readable source code for the Library including whatever
+ changes were used in the work (which must be distributed under
+ Sections 1 and 2 above); and, if the work is an executable linked
+ with the Library, with the complete machine-readable "work that
+ uses the Library", as object code and/or source code, so that the
+ user can modify the Library and then relink to produce a modified
+ executable containing the modified Library. (It is understood
+ that the user who changes the contents of definitions files in the
+ Library will not necessarily be able to recompile the application
+ to use the modified definitions.)
+
+ b) Use a suitable shared library mechanism for linking with the
+ Library. A suitable mechanism is one that (1) uses at run time a
+ copy of the library already present on the user's computer system,
+ rather than copying library functions into the executable, and (2)
+ will operate properly with a modified version of the library, if
+ the user installs one, as long as the modified version is
+ interface-compatible with the version that the work was made with.
+
+ c) Accompany the work with a written offer, valid for at
+ least three years, to give the same user the materials
+ specified in Subsection 6a, above, for a charge no more
+ than the cost of performing this distribution.
+
+ d) If distribution of the work is made by offering access to copy
+ from a designated place, offer equivalent access to copy the above
+ specified materials from the same place.
+
+ e) Verify that the user has already received a copy of these
+ materials or that you have already sent this user a copy.
+
+ For an executable, the required form of the "work that uses the
+Library" must include any data and utility programs needed for
+reproducing the executable from it. However, as a special exception,
+the materials to be distributed need not include anything that is
+normally distributed (in either source or binary form) with the major
+components (compiler, kernel, and so on) of the operating system on
+which the executable runs, unless that component itself accompanies
+the executable.
+
+ It may happen that this requirement contradicts the license
+restrictions of other proprietary libraries that do not normally
+accompany the operating system. Such a contradiction means you cannot
+use both them and the Library together in an executable that you
+distribute.
+
+ 7. You may place library facilities that are a work based on the
+Library side-by-side in a single library together with other library
+facilities not covered by this License, and distribute such a combined
+library, provided that the separate distribution of the work based on
+the Library and of the other library facilities is otherwise
+permitted, and provided that you do these two things:
+
+ a) Accompany the combined library with a copy of the same work
+ based on the Library, uncombined with any other library
+ facilities. This must be distributed under the terms of the
+ Sections above.
+
+ b) Give prominent notice with the combined library of the fact
+ that part of it is a work based on the Library, and explaining
+ where to find the accompanying uncombined form of the same work.
+
+ 8. You may not copy, modify, sublicense, link with, or distribute
+the Library except as expressly provided under this License. Any
+attempt otherwise to copy, modify, sublicense, link with, or
+distribute the Library is void, and will automatically terminate your
+rights under this License. However, parties who have received copies,
+or rights, from you under this License will not have their licenses
+terminated so long as such parties remain in full compliance.
+
+ 9. You are not required to accept this License, since you have not
+signed it. However, nothing else grants you permission to modify or
+distribute the Library or its derivative works. These actions are
+prohibited by law if you do not accept this License. Therefore, by
+modifying or distributing the Library (or any work based on the
+Library), you indicate your acceptance of this License to do so, and
+all its terms and conditions for copying, distributing or modifying
+the Library or works based on it.
+
+ 10. Each time you redistribute the Library (or any work based on the
+Library), the recipient automatically receives a license from the
+original licensor to copy, distribute, link with or modify the Library
+subject to these terms and conditions. You may not impose any further
+restrictions on the recipients' exercise of the rights granted herein.
+You are not responsible for enforcing compliance by third parties with
+this License.
+
+ 11. If, as a consequence of a court judgment or allegation of patent
+infringement or for any other reason (not limited to patent issues),
+conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License. If you cannot
+distribute so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you
+may not distribute the Library at all. For example, if a patent
+license would not permit royalty-free redistribution of the Library by
+all those who receive copies directly or indirectly through you, then
+the only way you could satisfy both it and this License would be to
+refrain entirely from distribution of the Library.
+
+If any portion of this section is held invalid or unenforceable under any
+particular circumstance, the balance of the section is intended to apply,
+and the section as a whole is intended to apply in other circumstances.
+
+It is not the purpose of this section to induce you to infringe any
+patents or other property right claims or to contest validity of any
+such claims; this section has the sole purpose of protecting the
+integrity of the free software distribution system which is
+implemented by public license practices. Many people have made
+generous contributions to the wide range of software distributed
+through that system in reliance on consistent application of that
+system; it is up to the author/donor to decide if he or she is willing
+to distribute software through any other system and a licensee cannot
+impose that choice.
+
+This section is intended to make thoroughly clear what is believed to
+be a consequence of the rest of this License.
+
+ 12. If the distribution and/or use of the Library is restricted in
+certain countries either by patents or by copyrighted interfaces, the
+original copyright holder who places the Library under this License may add
+an explicit geographical distribution limitation excluding those countries,
+so that distribution is permitted only in or among countries not thus
+excluded. In such case, this License incorporates the limitation as if
+written in the body of this License.
+
+ 13. The Free Software Foundation may publish revised and/or new
+versions of the Lesser General Public License from time to time.
+Such new versions will be similar in spirit to the present version,
+but may differ in detail to address new problems or concerns.
+
+Each version is given a distinguishing version number. If the Library
+specifies a version number of this License which applies to it and
+"any later version", you have the option of following the terms and
+conditions either of that version or of any later version published by
+the Free Software Foundation. If the Library does not specify a
+license version number, you may choose any version ever published by
+the Free Software Foundation.
+
+ 14. If you wish to incorporate parts of the Library into other free
+programs whose distribution conditions are incompatible with these,
+write to the author to ask for permission. For software which is
+copyrighted by the Free Software Foundation, write to the Free
+Software Foundation; we sometimes make exceptions for this. Our
+decision will be guided by the two goals of preserving the free status
+of all derivatives of our free software and of promoting the sharing
+and reuse of software generally.
+
+ NO WARRANTY
+
+ 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO
+WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW.
+EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR
+OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY
+KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE
+IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE
+LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME
+THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
+
+ 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN
+WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY
+AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU
+FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR
+CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE
+LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING
+RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A
+FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF
+SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
+DAMAGES.
+
+ END OF TERMS AND CONDITIONS
+
+ How to Apply These Terms to Your New Libraries
+
+ If you develop a new library, and you want it to be of the greatest
+possible use to the public, we recommend making it free software that
+everyone can redistribute and change. You can do so by permitting
+redistribution under these terms (or, alternatively, under the terms of the
+ordinary General Public License).
+
+ To apply these terms, attach the following notices to the library. It is
+safest to attach them to the start of each source file to most effectively
+convey the exclusion of warranty; and each file should have at least the
+"copyright" line and a pointer to where the full notice is found.
+
+ <one line to give the library's name and a brief idea of what it does.>
+ Copyright (C) <year> <name of author>
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Lesser General Public
+ License as published by the Free Software Foundation; either
+ version 2.1 of the License, or (at your option) any later version.
+
+ This library is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public
+ License along with this library; if not, write to the Free Software
+ Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+
+Also add information on how to contact you by electronic and paper mail.
+
+You should also get your employer (if you work as a programmer) or your
+school, if any, to sign a "copyright disclaimer" for the library, if
+necessary. Here is a sample; alter the names:
+
+ Yoyodyne, Inc., hereby disclaims all copyright interest in the
+ library `Frob' (a library for tweaking knobs) written by James Random Hacker.
+
+ <signature of Ty Coon>, 1 April 1990
+ Ty Coon, President of Vice
+
+That's all there is to it!
diff --git a/mfbt/decimal/comparison-with-nan.patch b/mfbt/decimal/comparison-with-nan.patch
new file mode 100644
index 0000000..72afc9a
--- /dev/null
+++ b/mfbt/decimal/comparison-with-nan.patch
@@ -0,0 +1,67 @@
+diff --git a/mfbt/decimal/Decimal.cpp b/mfbt/decimal/Decimal.cpp
+--- a/mfbt/decimal/Decimal.cpp
++++ b/mfbt/decimal/Decimal.cpp
+@@ -505,21 +505,25 @@ Decimal Decimal::operator/(const Decimal
+ if (remainder > divisor / 2)
+ ++result;
+
+ return Decimal(resultSign, resultExponent, result);
+ }
+
+ bool Decimal::operator==(const Decimal& rhs) const
+ {
++ if (isNaN() || rhs.isNaN())
++ return false;
+ return m_data == rhs.m_data || compareTo(rhs).isZero();
+ }
+
+ bool Decimal::operator!=(const Decimal& rhs) const
+ {
++ if (isNaN() || rhs.isNaN())
++ return true;
+ if (m_data == rhs.m_data)
+ return false;
+ const Decimal result = compareTo(rhs);
+ if (result.isNaN())
+ return false;
+ return !result.isZero();
+ }
+
+@@ -528,16 +532,18 @@ bool Decimal::operator<(const Decimal& r
+ const Decimal result = compareTo(rhs);
+ if (result.isNaN())
+ return false;
+ return !result.isZero() && result.isNegative();
+ }
+
+ bool Decimal::operator<=(const Decimal& rhs) const
+ {
++ if (isNaN() || rhs.isNaN())
++ return false;
+ if (m_data == rhs.m_data)
+ return true;
+ const Decimal result = compareTo(rhs);
+ if (result.isNaN())
+ return false;
+ return result.isZero() || result.isNegative();
+ }
+
+@@ -546,16 +552,18 @@ bool Decimal::operator>(const Decimal& r
+ const Decimal result = compareTo(rhs);
+ if (result.isNaN())
+ return false;
+ return !result.isZero() && result.isPositive();
+ }
+
+ bool Decimal::operator>=(const Decimal& rhs) const
+ {
++ if (isNaN() || rhs.isNaN())
++ return false;
+ if (m_data == rhs.m_data)
+ return true;
+ const Decimal result = compareTo(rhs);
+ if (result.isNaN())
+ return false;
+ return result.isZero() || !result.isNegative();
+ }
+
diff --git a/mfbt/decimal/floor-ceiling.patch b/mfbt/decimal/floor-ceiling.patch
new file mode 100644
index 0000000..9e26787
--- /dev/null
+++ b/mfbt/decimal/floor-ceiling.patch
@@ -0,0 +1,89 @@
+diff --git a/mfbt/decimal/Decimal.cpp b/mfbt/decimal/Decimal.cpp
+--- a/mfbt/decimal/Decimal.cpp
++++ b/mfbt/decimal/Decimal.cpp
+@@ -618,26 +618,26 @@ Decimal::AlignedOperands Decimal::alignO
+ Decimal Decimal::ceiling() const
+ {
+ if (isSpecial())
+ return *this;
+
+ if (exponent() >= 0)
+ return *this;
+
+- uint64_t result = m_data.coefficient();
+- const int numberOfDigits = countDigits(result);
++ uint64_t coefficient = m_data.coefficient();
++ const int numberOfDigits = countDigits(coefficient);
+ const int numberOfDropDigits = -exponent();
+ if (numberOfDigits < numberOfDropDigits)
+ return isPositive() ? Decimal(1) : zero(Positive);
+
+- result = scaleDown(result, numberOfDropDigits - 1);
+- if (sign() == Positive && result % 10 > 0)
+- result += 10;
+- result /= 10;
++ uint64_t result = scaleDown(coefficient, numberOfDropDigits);
++ uint64_t droppedDigits = coefficient - scaleUp(result, numberOfDropDigits);
++ if (droppedDigits && isPositive())
++ result += 1;
+ return Decimal(sign(), 0, result);
+ }
+
+ Decimal Decimal::compareTo(const Decimal& rhs) const
+ {
+ const Decimal result(*this - rhs);
+ switch (result.m_data.formatClass()) {
+ case EncodedData::ClassInfinity:
+@@ -660,26 +660,27 @@ Decimal Decimal::compareTo(const Decimal
+ Decimal Decimal::floor() const
+ {
+ if (isSpecial())
+ return *this;
+
+ if (exponent() >= 0)
+ return *this;
+
+- uint64_t result = m_data.coefficient();
+- const int numberOfDigits = countDigits(result);
++ uint64_t coefficient = m_data.coefficient();
++ const int numberOfDigits = countDigits(coefficient);
+ const int numberOfDropDigits = -exponent();
+ if (numberOfDigits < numberOfDropDigits)
+ return isPositive() ? zero(Positive) : Decimal(-1);
+
+- result = scaleDown(result, numberOfDropDigits - 1);
+- if (isNegative() && result % 10 > 0)
+- result += 10;
+- result /= 10;
++ uint64_t result = scaleDown(coefficient, numberOfDropDigits);
++ uint64_t droppedDigits = coefficient - scaleUp(result, numberOfDropDigits);
++ if (droppedDigits && isNegative()) {
++ result += 1;
++ }
+ return Decimal(sign(), 0, result);
+ }
+
+ Decimal Decimal::fromDouble(double doubleValue)
+ {
+ if (std::isfinite(doubleValue))
+ return fromString(String::numberToStringECMAScript(doubleValue));
+
+@@ -915,16 +916,18 @@ Decimal Decimal::round() const
+ return *this;
+
+ uint64_t result = m_data.coefficient();
+ const int numberOfDigits = countDigits(result);
+ const int numberOfDropDigits = -exponent();
+ if (numberOfDigits < numberOfDropDigits)
+ return zero(Positive);
+
++ // We're implementing round-half-away-from-zero, so we only need the one
++ // (the most significant) fractional digit:
+ result = scaleDown(result, numberOfDropDigits - 1);
+ if (result % 10 >= 5)
+ result += 10;
+ result /= 10;
+ return Decimal(sign(), 0, result);
+ }
+
+ double Decimal::toDouble() const
diff --git a/mfbt/decimal/mfbt-abi-markers.patch b/mfbt/decimal/mfbt-abi-markers.patch
new file mode 100644
index 0000000..834ee4b
--- /dev/null
+++ b/mfbt/decimal/mfbt-abi-markers.patch
@@ -0,0 +1,150 @@
+diff --git a/mfbt/decimal/Decimal.h b/mfbt/decimal/Decimal.h
+--- a/mfbt/decimal/Decimal.h
++++ b/mfbt/decimal/Decimal.h
+@@ -26,16 +26,18 @@
+ * 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.
+ */
+
+ #ifndef Decimal_h
+ #define Decimal_h
+
++#include "mozilla/Types.h"
++
+ #include <stdint.h>
+ #include <wtf/Assertions.h>
+ #include <wtf/text/WTFString.h>
+
+ namespace WebCore {
+
+ namespace DecimalPrivate {
+ class SpecialValueHandler;
+@@ -88,92 +90,92 @@ public:
+ FormatClass formatClass() const { return m_formatClass; }
+
+ uint64_t m_coefficient;
+ int16_t m_exponent;
+ FormatClass m_formatClass;
+ Sign m_sign;
+ };
+
+- Decimal(int32_t = 0);
+- Decimal(Sign, int exponent, uint64_t coefficient);
+- Decimal(const Decimal&);
++ MFBT_API Decimal(int32_t = 0);
++ MFBT_API Decimal(Sign, int exponent, uint64_t coefficient);
++ MFBT_API Decimal(const Decimal&);
+
+- Decimal& operator=(const Decimal&);
+- Decimal& operator+=(const Decimal&);
+- Decimal& operator-=(const Decimal&);
+- Decimal& operator*=(const Decimal&);
+- Decimal& operator/=(const Decimal&);
++ MFBT_API Decimal& operator=(const Decimal&);
++ MFBT_API Decimal& operator+=(const Decimal&);
++ MFBT_API Decimal& operator-=(const Decimal&);
++ MFBT_API Decimal& operator*=(const Decimal&);
++ MFBT_API Decimal& operator/=(const Decimal&);
+
+- Decimal operator-() const;
++ MFBT_API Decimal operator-() const;
+
+- bool operator==(const Decimal&) const;
+- bool operator!=(const Decimal&) const;
+- bool operator<(const Decimal&) const;
+- bool operator<=(const Decimal&) const;
+- bool operator>(const Decimal&) const;
+- bool operator>=(const Decimal&) const;
++ MFBT_API bool operator==(const Decimal&) const;
++ MFBT_API bool operator!=(const Decimal&) const;
++ MFBT_API bool operator<(const Decimal&) const;
++ MFBT_API bool operator<=(const Decimal&) const;
++ MFBT_API bool operator>(const Decimal&) const;
++ MFBT_API bool operator>=(const Decimal&) const;
+
+- Decimal operator+(const Decimal&) const;
+- Decimal operator-(const Decimal&) const;
+- Decimal operator*(const Decimal&) const;
+- Decimal operator/(const Decimal&) const;
++ MFBT_API Decimal operator+(const Decimal&) const;
++ MFBT_API Decimal operator-(const Decimal&) const;
++ MFBT_API Decimal operator*(const Decimal&) const;
++ MFBT_API Decimal operator/(const Decimal&) const;
+
+ int exponent() const
+ {
+ ASSERT(isFinite());
+ return m_data.exponent();
+ }
+
+ bool isFinite() const { return m_data.isFinite(); }
+ bool isInfinity() const { return m_data.isInfinity(); }
+ bool isNaN() const { return m_data.isNaN(); }
+ bool isNegative() const { return sign() == Negative; }
+ bool isPositive() const { return sign() == Positive; }
+ bool isSpecial() const { return m_data.isSpecial(); }
+ bool isZero() const { return m_data.isZero(); }
+
+- Decimal abs() const;
+- Decimal ceiling() const;
+- Decimal floor() const;
+- Decimal remainder(const Decimal&) const;
+- Decimal round() const;
++ MFBT_API Decimal abs() const;
++ MFBT_API Decimal ceiling() const;
++ MFBT_API Decimal floor() const;
++ MFBT_API Decimal remainder(const Decimal&) const;
++ MFBT_API Decimal round() const;
+
+- double toDouble() const;
++ MFBT_API double toDouble() const;
+ // Note: toString method supports infinity and nan but fromString not.
+- String toString() const;
++ MFBT_API String toString() const;
+
+- static Decimal fromDouble(double);
++ static MFBT_API Decimal fromDouble(double);
+ // fromString supports following syntax EBNF:
+ // number ::= sign? digit+ ('.' digit*) (exponent-marker sign? digit+)?
+ // | sign? '.' digit+ (exponent-marker sign? digit+)?
+ // sign ::= '+' | '-'
+ // exponent-marker ::= 'e' | 'E'
+ // digit ::= '0' | '1' | ... | '9'
+ // Note: fromString doesn't support "infinity" and "nan".
+- static Decimal fromString(const String&);
+- static Decimal infinity(Sign);
+- static Decimal nan();
+- static Decimal zero(Sign);
++ static MFBT_API Decimal fromString(const String&);
++ static MFBT_API Decimal infinity(Sign);
++ static MFBT_API Decimal nan();
++ static MFBT_API Decimal zero(Sign);
+
+ // You should not use below methods. We expose them for unit testing.
+- explicit Decimal(const EncodedData&);
++ MFBT_API explicit Decimal(const EncodedData&);
+ const EncodedData& value() const { return m_data; }
+
+ private:
+ struct AlignedOperands {
+ uint64_t lhsCoefficient;
+ uint64_t rhsCoefficient;
+ int exponent;
+ };
+
+- Decimal(double);
+- Decimal compareTo(const Decimal&) const;
++ MFBT_API Decimal(double);
++ MFBT_API Decimal compareTo(const Decimal&) const;
+
+- static AlignedOperands alignOperands(const Decimal& lhs, const Decimal& rhs);
++ static MFBT_API AlignedOperands alignOperands(const Decimal& lhs, const Decimal& rhs);
+ static inline Sign invertSign(Sign sign) { return sign == Negative ? Positive : Negative; }
+
+ Sign sign() const { return m_data.sign(); }
+
+ EncodedData m_data;
+ };
+
+ } // namespace WebCore
diff --git a/mfbt/decimal/moz-decimal-utils.h b/mfbt/decimal/moz-decimal-utils.h
new file mode 100644
index 0000000..7f96d30
--- /dev/null
+++ b/mfbt/decimal/moz-decimal-utils.h
@@ -0,0 +1,109 @@
+/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#ifndef MOZ_DECIMAL_UTILS_H
+#define MOZ_DECIMAL_UTILS_H
+
+// This file contains extra includes, defines and typedefs to allow compilation
+// of Decimal.cpp under the Mozilla source without blink core dependencies. Do
+// not include it into any file other than Decimal.cpp.
+
+#include "../double-conversion/double-conversion.h"
+#include "mozilla/Util.h"
+#include "mozilla/Casting.h"
+#include "mozilla/FloatingPoint.h"
+#include "mozilla/NullPtr.h"
+
+#include <cmath>
+#include <cstring>
+#include <iomanip>
+#include <limits>
+#include <sstream>
+
+#ifndef UINT64_C
+// For Android toolchain
+#define UINT64_C(c) (c ## ULL)
+#endif
+
+#ifdef ASSERT
+#undef ASSERT
+#endif
+#define ASSERT MOZ_ASSERT
+
+#define ASSERT_NOT_REACHED() MOZ_NOT_REACHED("")
+
+#define WTF_MAKE_NONCOPYABLE(ClassName) \
+ private: \
+ ClassName(const ClassName&) MOZ_DELETE; \
+ void operator=(const ClassName&) MOZ_DELETE;
+
+#if defined(_MSC_VER) && (_MSC_VER <= 1700)
+namespace std {
+ inline bool isinf(double num) { return mozilla::IsInfinite(num); }
+ inline bool isnan(double num) { return mozilla::IsNaN(num); }
+ inline bool isfinite(double num) { return mozilla::IsFinite(num); }
+}
+#endif
+
+typedef std::string String;
+
+double mozToDouble(const String &aStr, bool *valid) {
+ double_conversion::StringToDoubleConverter converter(
+ double_conversion::StringToDoubleConverter::NO_FLAGS,
+ mozilla::UnspecifiedNaN(), mozilla::UnspecifiedNaN(), nullptr, nullptr);
+ const char* str = aStr.c_str();
+ int length = mozilla::SafeCast<int>(strlen(str));
+ int processed_char_count; // unused - NO_FLAGS requires the whole string to parse
+ double result = converter.StringToDouble(str, length, &processed_char_count);
+ *valid = mozilla::IsFinite(result);
+ return result;
+}
+
+String mozToString(double aNum) {
+ char buffer[64];
+ int buffer_length = mozilla::ArrayLength(buffer);
+ const double_conversion::DoubleToStringConverter& converter =
+ double_conversion::DoubleToStringConverter::EcmaScriptConverter();
+ double_conversion::StringBuilder builder(buffer, buffer_length);
+ converter.ToShortest(aNum, &builder);
+ return String(builder.Finalize());
+}
+
+String mozToString(int64_t aNum) {
+ std::ostringstream o;
+ o << std::setprecision(std::numeric_limits<int64_t>::digits10) << aNum;
+ return o.str();
+}
+
+String mozToString(uint64_t aNum) {
+ std::ostringstream o;
+ o << std::setprecision(std::numeric_limits<uint64_t>::digits10) << aNum;
+ return o.str();
+}
+
+class StringBuilder
+{
+public:
+ void append(char c) {
+ mStr += c;
+ }
+ void appendLiteral(const char *aStr) {
+ mStr += aStr;
+ }
+ void appendNumber(int aNum) {
+ mStr += mozToString(int64_t(aNum));
+ }
+ void append(const String& aStr) {
+ mStr += aStr;
+ }
+ std::string toString() const {
+ return mStr;
+ }
+private:
+ std::string mStr;
+};
+
+#endif
+
diff --git a/mfbt/decimal/to-moz-dependencies.patch b/mfbt/decimal/to-moz-dependencies.patch
new file mode 100644
index 0000000..824f65c
--- /dev/null
+++ b/mfbt/decimal/to-moz-dependencies.patch
@@ -0,0 +1,333 @@
+diff --git a/mfbt/decimal/Decimal.cpp b/mfbt/decimal/Decimal.cpp
+--- a/mfbt/decimal/Decimal.cpp
++++ b/mfbt/decimal/Decimal.cpp
+@@ -23,27 +23,22 @@
+ * 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.
+ */
+
+-#include "config.h"
+ #include "Decimal.h"
++#include "moz-decimal-utils.h"
+
+ #include <algorithm>
+ #include <float.h>
+
+-#include <wtf/Assertions.h>
+-#include <wtf/MathExtras.h>
+-#include <wtf/Noncopyable.h>
+-#include <wtf/text/StringBuilder.h>
+-
+ namespace WebCore {
+
+ namespace DecimalPrivate {
+
+ static int const ExponentMax = 1023;
+ static int const ExponentMin = -1023;
+ static int const Precision = 18;
+
+@@ -685,17 +680,17 @@ Decimal Decimal::floor() const
+ result += 1;
+ }
+ return Decimal(sign(), 0, result);
+ }
+
+ Decimal Decimal::fromDouble(double doubleValue)
+ {
+ if (std::isfinite(doubleValue))
+- return fromString(String::numberToStringECMAScript(doubleValue));
++ return fromString(mozToString(doubleValue));
+
+ if (std::isinf(doubleValue))
+ return infinity(doubleValue < 0 ? Negative : Positive);
+
+ return nan();
+ }
+
+ Decimal Decimal::fromString(const String& str)
+@@ -937,17 +932,17 @@ Decimal Decimal::round() const
+ result /= 10;
+ return Decimal(sign(), 0, result);
+ }
+
+ double Decimal::toDouble() const
+ {
+ if (isFinite()) {
+ bool valid;
+- const double doubleValue = toString().toDouble(&valid);
++ const double doubleValue = mozToDouble(toString(), &valid);
+ return valid ? doubleValue : std::numeric_limits<double>::quiet_NaN();
+ }
+
+ if (isInfinity())
+ return isNegative() ? -std::numeric_limits<double>::infinity() : std::numeric_limits<double>::infinity();
+
+ return std::numeric_limits<double>::quiet_NaN();
+ }
+@@ -990,17 +985,17 @@ String Decimal::toString() const
+ ++coefficient;
+
+ while (originalExponent < 0 && coefficient && !(coefficient % 10)) {
+ coefficient /= 10;
+ ++originalExponent;
+ }
+ }
+
+- const String digits = String::number(coefficient);
++ const String digits = mozToString(coefficient);
+ int coefficientLength = static_cast<int>(digits.length());
+ const int adjustedExponent = originalExponent + coefficientLength - 1;
+ if (originalExponent <= 0 && adjustedExponent >= -6) {
+ if (!originalExponent) {
+ builder.append(digits);
+ return builder.toString();
+ }
+
+@@ -1032,15 +1027,28 @@ String Decimal::toString() const
+ if (adjustedExponent) {
+ builder.append(adjustedExponent < 0 ? "e" : "e+");
+ builder.appendNumber(adjustedExponent);
+ }
+ }
+ return builder.toString();
+ }
+
++bool Decimal::toString(char* strBuf, size_t bufLength) const
++{
++ ASSERT(bufLength > 0);
++ String str = toString();
++ size_t length = str.copy(strBuf, bufLength);
++ if (length < bufLength) {
++ strBuf[length] = '\0';
++ return true;
++ }
++ strBuf[bufLength - 1] = '\0';
++ return false;
++}
++
+ Decimal Decimal::zero(Sign sign)
+ {
+ return Decimal(EncodedData(sign, EncodedData::ClassZero));
+ }
+
+ } // namespace WebCore
+
+diff --git a/mfbt/decimal/Decimal.h b/mfbt/decimal/Decimal.h
+--- a/mfbt/decimal/Decimal.h
++++ b/mfbt/decimal/Decimal.h
+@@ -23,24 +23,41 @@
+ * 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.
+ */
+
++/**
++ * Imported from:
++ * http://src.chromium.org/viewvc/blink/trunk/Source/core/platform/Decimal.h
++ * Check hg log for the svn rev of the last update from Blink core.
++ */
++
+ #ifndef Decimal_h
+ #define Decimal_h
+
++#include "mozilla/Assertions.h"
++#include "mozilla/StandardInteger.h"
+ #include "mozilla/Types.h"
+
+-#include <stdint.h>
+-#include <wtf/Assertions.h>
+-#include <wtf/text/WTFString.h>
++#include <string>
++
++#ifndef ASSERT
++#define DEFINED_ASSERT_FOR_DECIMAL_H 1
++#define ASSERT MOZ_ASSERT
++#endif
++
++// To use WTF_MAKE_FAST_ALLOCATED we'd need:
++// http://src.chromium.org/viewvc/blink/trunk/Source/wtf/FastMalloc.h
++// Since we don't allocate Decimal objects, no need.
++#define WTF_MAKE_FAST_ALLOCATED \
++ void ignore_this_dummy_method() MOZ_DELETE
+
+ namespace WebCore {
+
+ namespace DecimalPrivate {
+ class SpecialValueHandler;
+ }
+
+ // This class represents decimal base floating point number.
+@@ -136,27 +153,28 @@ public:
+ MFBT_API Decimal abs() const;
+ MFBT_API Decimal ceiling() const;
+ MFBT_API Decimal floor() const;
+ MFBT_API Decimal remainder(const Decimal&) const;
+ MFBT_API Decimal round() const;
+
+ MFBT_API double toDouble() const;
+ // Note: toString method supports infinity and nan but fromString not.
+- MFBT_API String toString() const;
++ MFBT_API std::string toString() const;
++ MFBT_API bool toString(char* strBuf, size_t bufLength) const;
+
+ static MFBT_API Decimal fromDouble(double);
+ // fromString supports following syntax EBNF:
+ // number ::= sign? digit+ ('.' digit*) (exponent-marker sign? digit+)?
+ // | sign? '.' digit+ (exponent-marker sign? digit+)?
+ // sign ::= '+' | '-'
+ // exponent-marker ::= 'e' | 'E'
+ // digit ::= '0' | '1' | ... | '9'
+ // Note: fromString doesn't support "infinity" and "nan".
+- static MFBT_API Decimal fromString(const String&);
++ static MFBT_API Decimal fromString(const std::string& aValue);
+ static MFBT_API Decimal infinity(Sign);
+ static MFBT_API Decimal nan();
+ static MFBT_API Decimal zero(Sign);
+
+ // You should not use below methods. We expose them for unit testing.
+ MFBT_API explicit Decimal(const EncodedData&);
+ const EncodedData& value() const { return m_data; }
+
+@@ -175,10 +193,21 @@ private:
+
+ Sign sign() const { return m_data.sign(); }
+
+ EncodedData m_data;
+ };
+
+ } // namespace WebCore
+
++namespace mozilla {
++ typedef WebCore::Decimal Decimal;
++}
++
++#undef WTF_MAKE_FAST_ALLOCATED
++
++#ifdef DEFINED_ASSERT_FOR_DECIMAL_H
++#undef DEFINED_ASSERT_FOR_DECIMAL_H
++#undef ASSERT
++#endif
++
+ #endif // Decimal_h
+
+diff --git a/mfbt/decimal/moz-decimal-utils.h b/mfbt/decimal/moz-decimal-utils.h
+new file mode 100644
+--- /dev/null
++++ b/mfbt/decimal/moz-decimal-utils.h
+@@ -0,0 +1,109 @@
++/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
++/* This Source Code Form is subject to the terms of the Mozilla Public
++ * License, v. 2.0. If a copy of the MPL was not distributed with this
++ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
++
++#ifndef MOZ_DECIMAL_UTILS_H
++#define MOZ_DECIMAL_UTILS_H
++
++// This file contains extra includes, defines and typedefs to allow compilation
++// of Decimal.cpp under the Mozilla source without blink core dependencies. Do
++// not include it into any file other than Decimal.cpp.
++
++#include "../double-conversion/double-conversion.h"
++#include "mozilla/Util.h"
++#include "mozilla/Casting.h"
++#include "mozilla/FloatingPoint.h"
++#include "mozilla/NullPtr.h"
++
++#include <cmath>
++#include <cstring>
++#include <iomanip>
++#include <limits>
++#include <sstream>
++
++#ifndef UINT64_C
++// For Android toolchain
++#define UINT64_C(c) (c ## ULL)
++#endif
++
++#ifdef ASSERT
++#undef ASSERT
++#endif
++#define ASSERT MOZ_ASSERT
++
++#define ASSERT_NOT_REACHED() MOZ_NOT_REACHED("")
++
++#define WTF_MAKE_NONCOPYABLE(ClassName) \
++ private: \
++ ClassName(const ClassName&) MOZ_DELETE; \
++ void operator=(const ClassName&) MOZ_DELETE;
++
++#if defined(_MSC_VER) && (_MSC_VER <= 1700)
++namespace std {
++ inline bool isinf(double num) { return MOZ_DOUBLE_IS_INFINITE(num); }
++ inline bool isnan(double num) { return MOZ_DOUBLE_IS_NaN(num); }
++ inline bool isfinite(double num) { return MOZ_DOUBLE_IS_FINITE(num); }
++}
++#endif
++
++typedef std::string String;
++
++double mozToDouble(const String &aStr, bool *valid) {
++ double_conversion::StringToDoubleConverter converter(
++ double_conversion::StringToDoubleConverter::NO_FLAGS,
++ MOZ_DOUBLE_NaN(), MOZ_DOUBLE_NaN(), nullptr, nullptr);
++ const char* str = aStr.c_str();
++ int length = mozilla::SafeCast<int>(strlen(str));
++ int processed_char_count; // unused - NO_FLAGS requires the whole string to parse
++ double result = converter.StringToDouble(str, length, &processed_char_count);
++ *valid = MOZ_DOUBLE_IS_FINITE(result);
++ return result;
++}
++
++String mozToString(double aNum) {
++ char buffer[64];
++ int buffer_length = mozilla::ArrayLength(buffer);
++ const double_conversion::DoubleToStringConverter& converter =
++ double_conversion::DoubleToStringConverter::EcmaScriptConverter();
++ double_conversion::StringBuilder builder(buffer, buffer_length);
++ converter.ToShortest(aNum, &builder);
++ return String(builder.Finalize());
++}
++
++String mozToString(int64_t aNum) {
++ std::ostringstream o;
++ o << std::setprecision(std::numeric_limits<int64_t>::digits10) << aNum;
++ return o.str();
++}
++
++String mozToString(uint64_t aNum) {
++ std::ostringstream o;
++ o << std::setprecision(std::numeric_limits<uint64_t>::digits10) << aNum;
++ return o.str();
++}
++
++class StringBuilder
++{
++public:
++ void append(char c) {
++ mStr += c;
++ }
++ void appendLiteral(const char *aStr) {
++ mStr += aStr;
++ }
++ void appendNumber(int aNum) {
++ mStr += mozToString(int64_t(aNum));
++ }
++ void append(const String& aStr) {
++ mStr += aStr;
++ }
++ std::string toString() const {
++ return mStr;
++ }
++private:
++ std::string mStr;
++};
++
++#endif
++
diff --git a/mfbt/decimal/update.sh b/mfbt/decimal/update.sh
new file mode 100755
index 0000000..5422b5c
--- /dev/null
+++ b/mfbt/decimal/update.sh
@@ -0,0 +1,66 @@
+# Usage: ./update.sh [blink-core-source-directory]
+#
+# Copies the needed files from a directory containing the original
+# Decimal.h and Decimal.cpp source that we need.
+# If [blink-core-source-directory] is not specified, this script will
+# attempt to download the latest versions using svn.
+
+# This was last updated with svn r148833
+
+set -e
+
+FILES=(
+ "LICENSE-APPLE"
+ "LICENSE-LGPL-2"
+ "LICENSE-LGPL-2.1"
+ "platform/Decimal.h"
+ "platform/Decimal.cpp"
+)
+
+OWN_NAME=`basename $0`
+
+if [ $# -gt 1 ]; then
+ echo "$OWN_NAME: Too many arguments">&2
+ exit 1
+fi
+
+if [ $# -eq 1 ]; then
+ BLINK_CORE_DIR="$1"
+ for F in "${FILES[@]}"
+ do
+ P="$BLINK_CORE_DIR/$F"
+ if [ ! -f "$P" ]; then
+ echo "$OWN_NAME: Couldn't find file: $P">&2
+ exit 1
+ fi
+ done
+ for F in "${FILES[@]}"
+ do
+ P="$BLINK_CORE_DIR/$F"
+ cp "$P" .
+ done
+else
+ SVN="svn --non-interactive --trust-server-cert"
+ REPO_PATH="https://src.chromium.org/blink/trunk/Source/core"
+ #REPO_PATH="https://svn.webkit.org/repository/webkit/trunk/Source/WebCore"
+
+ printf "Looking up latest Blink revision number..."
+ LATEST_REV=`$SVN info $REPO_PATH | grep '^Revision: ' | cut -c11-`
+ echo done.
+
+ for F in "${FILES[@]}"
+ do
+ printf "Exporting r$LATEST_REV of `basename $F`..."
+ $SVN export -r $LATEST_REV $REPO_PATH/$F 2>/dev/null 1>&2
+ echo done.
+ done
+fi
+
+# Apply patches:
+
+patch -p3 < floor-ceiling.patch
+patch -p3 < zero-serialization.patch
+patch -p3 < comparison-with-nan.patch
+patch -p3 < mfbt-abi-markers.patch
+patch -p3 < to-moz-dependencies.patch
+
diff --git a/mfbt/decimal/zero-serialization.patch b/mfbt/decimal/zero-serialization.patch
new file mode 100644
index 0000000..b058e09
--- /dev/null
+++ b/mfbt/decimal/zero-serialization.patch
@@ -0,0 +1,22 @@
+diff --git a/mfbt/decimal/Decimal.cpp b/mfbt/decimal/Decimal.cpp
+--- a/mfbt/decimal/Decimal.cpp
++++ b/mfbt/decimal/Decimal.cpp
+@@ -278,17 +278,17 @@ bool Decimal::EncodedData::operator==(co
+ }
+
+ Decimal::Decimal(int32_t i32)
+ : m_data(i32 < 0 ? Negative : Positive, 0, i32 < 0 ? static_cast<uint64_t>(-static_cast<int64_t>(i32)) : static_cast<uint64_t>(i32))
+ {
+ }
+
+ Decimal::Decimal(Sign sign, int exponent, uint64_t coefficient)
+- : m_data(sign, exponent, coefficient)
++ : m_data(sign, coefficient ? exponent : 0, coefficient)
+ {
+ }
+
+ Decimal::Decimal(const EncodedData& data)
+ : m_data(data)
+ {
+ }
+
diff --git a/mfbt/double-conversion/LICENSE b/mfbt/double-conversion/LICENSE
new file mode 100644
index 0000000..933718a
--- /dev/null
+++ b/mfbt/double-conversion/LICENSE
@@ -0,0 +1,26 @@
+Copyright 2006-2011, the V8 project authors. All rights reserved.
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions are
+met:
+
+ * Redistributions of source code must retain the above copyright
+ notice, this list of conditions and the following disclaimer.
+ * 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.
+ * Neither the name of Google Inc. nor the names of its
+ contributors may be used to endorse or promote products derived
+ from this software without specific prior written permission.
+
+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.
diff --git a/mfbt/double-conversion/README b/mfbt/double-conversion/README
new file mode 100644
index 0000000..f186b42
--- /dev/null
+++ b/mfbt/double-conversion/README
@@ -0,0 +1,11 @@
+http://code.google.com/p/double-conversion
+
+This project (double-conversion) provides binary-decimal and decimal-binary
+routines for IEEE doubles.
+
+The library consists of efficient conversion routines that have been extracted
+from the V8 JavaScript engine. The code has been refactored and improved so that
+it can be used more easily in other projects.
+
+There is extensive documentation in src/double-conversion.h. Other examples can
+be found in test/cctest/test-conversions.cc.
diff --git a/mfbt/double-conversion/add-mfbt-api-markers.patch b/mfbt/double-conversion/add-mfbt-api-markers.patch
new file mode 100644
index 0000000..bbb50f6
--- /dev/null
+++ b/mfbt/double-conversion/add-mfbt-api-markers.patch
@@ -0,0 +1,94 @@
+diff --git a/mfbt/double-conversion/double-conversion.h b/mfbt/double-conversion/double-conversion.h
+index f98edae..c62b16b 100644
+--- a/mfbt/double-conversion/double-conversion.h
++++ b/mfbt/double-conversion/double-conversion.h
+@@ -28,6 +28,7 @@
+ #ifndef DOUBLE_CONVERSION_DOUBLE_CONVERSION_H_
+ #define DOUBLE_CONVERSION_DOUBLE_CONVERSION_H_
+
++#include "mozilla/Types.h"
+ #include "utils.h"
+
+ namespace double_conversion {
+@@ -129,7 +130,7 @@ class DoubleToStringConverter {
+ }
+
+ // Returns a converter following the EcmaScript specification.
+- static const DoubleToStringConverter& EcmaScriptConverter();
++ static MFBT_API const DoubleToStringConverter& EcmaScriptConverter();
+
+ // Computes the shortest string of digits that correctly represent the input
+ // number. Depending on decimal_in_shortest_low and decimal_in_shortest_high
+@@ -197,7 +198,7 @@ class DoubleToStringConverter {
+ // The last two conditions imply that the result will never contain more than
+ // 1 + kMaxFixedDigitsBeforePoint + 1 + kMaxFixedDigitsAfterPoint characters
+ // (one additional character for the sign, and one for the decimal point).
+- bool ToFixed(double value,
++ MFBT_API bool ToFixed(double value,
+ int requested_digits,
+ StringBuilder* result_builder) const;
+
+@@ -229,7 +230,7 @@ class DoubleToStringConverter {
+ // kMaxExponentialDigits + 8 characters (the sign, the digit before the
+ // decimal point, the decimal point, the exponent character, the
+ // exponent's sign, and at most 3 exponent digits).
+- bool ToExponential(double value,
++ MFBT_API bool ToExponential(double value,
+ int requested_digits,
+ StringBuilder* result_builder) const;
+
+@@ -267,7 +268,7 @@ class DoubleToStringConverter {
+ // The last condition implies that the result will never contain more than
+ // kMaxPrecisionDigits + 7 characters (the sign, the decimal point, the
+ // exponent character, the exponent's sign, and at most 3 exponent digits).
+- bool ToPrecision(double value,
++ MFBT_API bool ToPrecision(double value,
+ int precision,
+ StringBuilder* result_builder) const;
+
+@@ -292,7 +293,7 @@ class DoubleToStringConverter {
+ // kBase10MaximalLength.
+ // Note that DoubleToAscii null-terminates its input. So the given buffer
+ // should be at least kBase10MaximalLength + 1 characters long.
+- static const int kBase10MaximalLength = 17;
++ static const MFBT_DATA int kBase10MaximalLength = 17;
+
+ // Converts the given double 'v' to ascii. 'v' must not be NaN, +Infinity, or
+ // -Infinity. In SHORTEST_SINGLE-mode this restriction also applies to 'v'
+@@ -332,7 +333,7 @@ class DoubleToStringConverter {
+ // terminating null-character when computing the maximal output size.
+ // The given length is only used in debug mode to ensure the buffer is big
+ // enough.
+- static void DoubleToAscii(double v,
++ static MFBT_API void DoubleToAscii(double v,
+ DtoaMode mode,
+ int requested_digits,
+ char* buffer,
+@@ -343,7 +344,7 @@ class DoubleToStringConverter {
+
+ private:
+ // Implementation for ToShortest and ToShortestSingle.
+- bool ToShortestIeeeNumber(double value,
++ MFBT_API bool ToShortestIeeeNumber(double value,
+ StringBuilder* result_builder,
+ DtoaMode mode) const;
+
+@@ -351,15 +352,15 @@ class DoubleToStringConverter {
+ // corresponding string using the configured infinity/nan-symbol.
+ // If either of them is NULL or the value is not special then the
+ // function returns false.
+- bool HandleSpecialValues(double value, StringBuilder* result_builder) const;
++ MFBT_API bool HandleSpecialValues(double value, StringBuilder* result_builder) const;
+ // Constructs an exponential representation (i.e. 1.234e56).
+ // The given exponent assumes a decimal point after the first decimal digit.
+- void CreateExponentialRepresentation(const char* decimal_digits,
++ MFBT_API void CreateExponentialRepresentation(const char* decimal_digits,
+ int length,
+ int exponent,
+ StringBuilder* result_builder) const;
+ // Creates a decimal representation (i.e 1234.5678).
+- void CreateDecimalRepresentation(const char* decimal_digits,
++ MFBT_API void CreateDecimalRepresentation(const char* decimal_digits,
+ int length,
+ int decimal_point,
+ int digits_after_point,
diff --git a/mfbt/double-conversion/bignum-dtoa.cc b/mfbt/double-conversion/bignum-dtoa.cc
new file mode 100644
index 0000000..b6c2e85
--- /dev/null
+++ b/mfbt/double-conversion/bignum-dtoa.cc
@@ -0,0 +1,640 @@
+// Copyright 2010 the V8 project authors. All rights reserved.
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+// * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+// * 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.
+// * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived
+// from this software without specific prior written permission.
+//
+// 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.
+
+#include <math.h>
+
+#include "bignum-dtoa.h"
+
+#include "bignum.h"
+#include "ieee.h"
+
+namespace double_conversion {
+
+static int NormalizedExponent(uint64_t significand, int exponent) {
+ ASSERT(significand != 0);
+ while ((significand & Double::kHiddenBit) == 0) {
+ significand = significand << 1;
+ exponent = exponent - 1;
+ }
+ return exponent;
+}
+
+
+// Forward declarations:
+// Returns an estimation of k such that 10^(k-1) <= v < 10^k.
+static int EstimatePower(int exponent);
+// Computes v / 10^estimated_power exactly, as a ratio of two bignums, numerator
+// and denominator.
+static void InitialScaledStartValues(uint64_t significand,
+ int exponent,
+ bool lower_boundary_is_closer,
+ int estimated_power,
+ bool need_boundary_deltas,
+ Bignum* numerator,
+ Bignum* denominator,
+ Bignum* delta_minus,
+ Bignum* delta_plus);
+// Multiplies numerator/denominator so that its values lies in the range 1-10.
+// Returns decimal_point s.t.
+// v = numerator'/denominator' * 10^(decimal_point-1)
+// where numerator' and denominator' are the values of numerator and
+// denominator after the call to this function.
+static void FixupMultiply10(int estimated_power, bool is_even,
+ int* decimal_point,
+ Bignum* numerator, Bignum* denominator,
+ Bignum* delta_minus, Bignum* delta_plus);
+// Generates digits from the left to the right and stops when the generated
+// digits yield the shortest decimal representation of v.
+static void GenerateShortestDigits(Bignum* numerator, Bignum* denominator,
+ Bignum* delta_minus, Bignum* delta_plus,
+ bool is_even,
+ Vector<char> buffer, int* length);
+// Generates 'requested_digits' after the decimal point.
+static void BignumToFixed(int requested_digits, int* decimal_point,
+ Bignum* numerator, Bignum* denominator,
+ Vector<char>(buffer), int* length);
+// Generates 'count' digits of numerator/denominator.
+// Once 'count' digits have been produced rounds the result depending on the
+// remainder (remainders of exactly .5 round upwards). Might update the
+// decimal_point when rounding up (for example for 0.9999).
+static void GenerateCountedDigits(int count, int* decimal_point,
+ Bignum* numerator, Bignum* denominator,
+ Vector<char>(buffer), int* length);
+
+
+void BignumDtoa(double v, BignumDtoaMode mode, int requested_digits,
+ Vector<char> buffer, int* length, int* decimal_point) {
+ ASSERT(v > 0);
+ ASSERT(!Double(v).IsSpecial());
+ uint64_t significand;
+ int exponent;
+ bool lower_boundary_is_closer;
+ if (mode == BIGNUM_DTOA_SHORTEST_SINGLE) {
+ float f = static_cast<float>(v);
+ ASSERT(f == v);
+ significand = Single(f).Significand();
+ exponent = Single(f).Exponent();
+ lower_boundary_is_closer = Single(f).LowerBoundaryIsCloser();
+ } else {
+ significand = Double(v).Significand();
+ exponent = Double(v).Exponent();
+ lower_boundary_is_closer = Double(v).LowerBoundaryIsCloser();
+ }
+ bool need_boundary_deltas =
+ (mode == BIGNUM_DTOA_SHORTEST || mode == BIGNUM_DTOA_SHORTEST_SINGLE);
+
+ bool is_even = (significand & 1) == 0;
+ int normalized_exponent = NormalizedExponent(significand, exponent);
+ // estimated_power might be too low by 1.
+ int estimated_power = EstimatePower(normalized_exponent);
+
+ // Shortcut for Fixed.
+ // The requested digits correspond to the digits after the point. If the
+ // number is much too small, then there is no need in trying to get any
+ // digits.
+ if (mode == BIGNUM_DTOA_FIXED && -estimated_power - 1 > requested_digits) {
+ buffer[0] = '\0';
+ *length = 0;
+ // Set decimal-point to -requested_digits. This is what Gay does.
+ // Note that it should not have any effect anyways since the string is
+ // empty.
+ *decimal_point = -requested_digits;
+ return;
+ }
+
+ Bignum numerator;
+ Bignum denominator;
+ Bignum delta_minus;
+ Bignum delta_plus;
+ // Make sure the bignum can grow large enough. The smallest double equals
+ // 4e-324. In this case the denominator needs fewer than 324*4 binary digits.
+ // The maximum double is 1.7976931348623157e308 which needs fewer than
+ // 308*4 binary digits.
+ ASSERT(Bignum::kMaxSignificantBits >= 324*4);
+ InitialScaledStartValues(significand, exponent, lower_boundary_is_closer,
+ estimated_power, need_boundary_deltas,
+ &numerator, &denominator,
+ &delta_minus, &delta_plus);
+ // We now have v = (numerator / denominator) * 10^estimated_power.
+ FixupMultiply10(estimated_power, is_even, decimal_point,
+ &numerator, &denominator,
+ &delta_minus, &delta_plus);
+ // We now have v = (numerator / denominator) * 10^(decimal_point-1), and
+ // 1 <= (numerator + delta_plus) / denominator < 10
+ switch (mode) {
+ case BIGNUM_DTOA_SHORTEST:
+ case BIGNUM_DTOA_SHORTEST_SINGLE:
+ GenerateShortestDigits(&numerator, &denominator,
+ &delta_minus, &delta_plus,
+ is_even, buffer, length);
+ break;
+ case BIGNUM_DTOA_FIXED:
+ BignumToFixed(requested_digits, decimal_point,
+ &numerator, &denominator,
+ buffer, length);
+ break;
+ case BIGNUM_DTOA_PRECISION:
+ GenerateCountedDigits(requested_digits, decimal_point,
+ &numerator, &denominator,
+ buffer, length);
+ break;
+ default:
+ UNREACHABLE();
+ }
+ buffer[*length] = '\0';
+}
+
+
+// The procedure starts generating digits from the left to the right and stops
+// when the generated digits yield the shortest decimal representation of v. A
+// decimal representation of v is a number lying closer to v than to any other
+// double, so it converts to v when read.
+//
+// This is true if d, the decimal representation, is between m- and m+, the
+// upper and lower boundaries. d must be strictly between them if !is_even.
+// m- := (numerator - delta_minus) / denominator
+// m+ := (numerator + delta_plus) / denominator
+//
+// Precondition: 0 <= (numerator+delta_plus) / denominator < 10.
+// If 1 <= (numerator+delta_plus) / denominator < 10 then no leading 0 digit
+// will be produced. This should be the standard precondition.
+static void GenerateShortestDigits(Bignum* numerator, Bignum* denominator,
+ Bignum* delta_minus, Bignum* delta_plus,
+ bool is_even,
+ Vector<char> buffer, int* length) {
+ // Small optimization: if delta_minus and delta_plus are the same just reuse
+ // one of the two bignums.
+ if (Bignum::Equal(*delta_minus, *delta_plus)) {
+ delta_plus = delta_minus;
+ }
+ *length = 0;
+ while (true) {
+ uint16_t digit;
+ digit = numerator->DivideModuloIntBignum(*denominator);
+ ASSERT(digit <= 9); // digit is a uint16_t and therefore always positive.
+ // digit = numerator / denominator (integer division).
+ // numerator = numerator % denominator.
+ buffer[(*length)++] = digit + '0';
+
+ // Can we stop already?
+ // If the remainder of the division is less than the distance to the lower
+ // boundary we can stop. In this case we simply round down (discarding the
+ // remainder).
+ // Similarly we test if we can round up (using the upper boundary).
+ bool in_delta_room_minus;
+ bool in_delta_room_plus;
+ if (is_even) {
+ in_delta_room_minus = Bignum::LessEqual(*numerator, *delta_minus);
+ } else {
+ in_delta_room_minus = Bignum::Less(*numerator, *delta_minus);
+ }
+ if (is_even) {
+ in_delta_room_plus =
+ Bignum::PlusCompare(*numerator, *delta_plus, *denominator) >= 0;
+ } else {
+ in_delta_room_plus =
+ Bignum::PlusCompare(*numerator, *delta_plus, *denominator) > 0;
+ }
+ if (!in_delta_room_minus && !in_delta_room_plus) {
+ // Prepare for next iteration.
+ numerator->Times10();
+ delta_minus->Times10();
+ // We optimized delta_plus to be equal to delta_minus (if they share the
+ // same value). So don't multiply delta_plus if they point to the same
+ // object.
+ if (delta_minus != delta_plus) {
+ delta_plus->Times10();
+ }
+ } else if (in_delta_room_minus && in_delta_room_plus) {
+ // Let's see if 2*numerator < denominator.
+ // If yes, then the next digit would be < 5 and we can round down.
+ int compare = Bignum::PlusCompare(*numerator, *numerator, *denominator);
+ if (compare < 0) {
+ // Remaining digits are less than .5. -> Round down (== do nothing).
+ } else if (compare > 0) {
+ // Remaining digits are more than .5 of denominator. -> Round up.
+ // Note that the last digit could not be a '9' as otherwise the whole
+ // loop would have stopped earlier.
+ // We still have an assert here in case the preconditions were not
+ // satisfied.
+ ASSERT(buffer[(*length) - 1] != '9');
+ buffer[(*length) - 1]++;
+ } else {
+ // Halfway case.
+ // TODO(floitsch): need a way to solve half-way cases.
+ // For now let's round towards even (since this is what Gay seems to
+ // do).
+
+ if ((buffer[(*length) - 1] - '0') % 2 == 0) {
+ // Round down => Do nothing.
+ } else {
+ ASSERT(buffer[(*length) - 1] != '9');
+ buffer[(*length) - 1]++;
+ }
+ }
+ return;
+ } else if (in_delta_room_minus) {
+ // Round down (== do nothing).
+ return;
+ } else { // in_delta_room_plus
+ // Round up.
+ // Note again that the last digit could not be '9' since this would have
+ // stopped the loop earlier.
+ // We still have an ASSERT here, in case the preconditions were not
+ // satisfied.
+ ASSERT(buffer[(*length) -1] != '9');
+ buffer[(*length) - 1]++;
+ return;
+ }
+ }
+}
+
+
+// Let v = numerator / denominator < 10.
+// Then we generate 'count' digits of d = x.xxxxx... (without the decimal point)
+// from left to right. Once 'count' digits have been produced we decide wether
+// to round up or down. Remainders of exactly .5 round upwards. Numbers such
+// as 9.999999 propagate a carry all the way, and change the
+// exponent (decimal_point), when rounding upwards.
+static void GenerateCountedDigits(int count, int* decimal_point,
+ Bignum* numerator, Bignum* denominator,
+ Vector<char>(buffer), int* length) {
+ ASSERT(count >= 0);
+ for (int i = 0; i < count - 1; ++i) {
+ uint16_t digit;
+ digit = numerator->DivideModuloIntBignum(*denominator);
+ ASSERT(digit <= 9); // digit is a uint16_t and therefore always positive.
+ // digit = numerator / denominator (integer division).
+ // numerator = numerator % denominator.
+ buffer[i] = digit + '0';
+ // Prepare for next iteration.
+ numerator->Times10();
+ }
+ // Generate the last digit.
+ uint16_t digit;
+ digit = numerator->DivideModuloIntBignum(*denominator);
+ if (Bignum::PlusCompare(*numerator, *numerator, *denominator) >= 0) {
+ digit++;
+ }
+ buffer[count - 1] = digit + '0';
+ // Correct bad digits (in case we had a sequence of '9's). Propagate the
+ // carry until we hat a non-'9' or til we reach the first digit.
+ for (int i = count - 1; i > 0; --i) {
+ if (buffer[i] != '0' + 10) break;
+ buffer[i] = '0';
+ buffer[i - 1]++;
+ }
+ if (buffer[0] == '0' + 10) {
+ // Propagate a carry past the top place.
+ buffer[0] = '1';
+ (*decimal_point)++;
+ }
+ *length = count;
+}
+
+
+// Generates 'requested_digits' after the decimal point. It might omit
+// trailing '0's. If the input number is too small then no digits at all are
+// generated (ex.: 2 fixed digits for 0.00001).
+//
+// Input verifies: 1 <= (numerator + delta) / denominator < 10.
+static void BignumToFixed(int requested_digits, int* decimal_point,
+ Bignum* numerator, Bignum* denominator,
+ Vector<char>(buffer), int* length) {
+ // Note that we have to look at more than just the requested_digits, since
+ // a number could be rounded up. Example: v=0.5 with requested_digits=0.
+ // Even though the power of v equals 0 we can't just stop here.
+ if (-(*decimal_point) > requested_digits) {
+ // The number is definitively too small.
+ // Ex: 0.001 with requested_digits == 1.
+ // Set decimal-point to -requested_digits. This is what Gay does.
+ // Note that it should not have any effect anyways since the string is
+ // empty.
+ *decimal_point = -requested_digits;
+ *length = 0;
+ return;
+ } else if (-(*decimal_point) == requested_digits) {
+ // We only need to verify if the number rounds down or up.
+ // Ex: 0.04 and 0.06 with requested_digits == 1.
+ ASSERT(*decimal_point == -requested_digits);
+ // Initially the fraction lies in range (1, 10]. Multiply the denominator
+ // by 10 so that we can compare more easily.
+ denominator->Times10();
+ if (Bignum::PlusCompare(*numerator, *numerator, *denominator) >= 0) {
+ // If the fraction is >= 0.5 then we have to include the rounded
+ // digit.
+ buffer[0] = '1';
+ *length = 1;
+ (*decimal_point)++;
+ } else {
+ // Note that we caught most of similar cases earlier.
+ *length = 0;
+ }
+ return;
+ } else {
+ // The requested digits correspond to the digits after the point.
+ // The variable 'needed_digits' includes the digits before the point.
+ int needed_digits = (*decimal_point) + requested_digits;
+ GenerateCountedDigits(needed_digits, decimal_point,
+ numerator, denominator,
+ buffer, length);
+ }
+}
+
+
+// Returns an estimation of k such that 10^(k-1) <= v < 10^k where
+// v = f * 2^exponent and 2^52 <= f < 2^53.
+// v is hence a normalized double with the given exponent. The output is an
+// approximation for the exponent of the decimal approimation .digits * 10^k.
+//
+// The result might undershoot by 1 in which case 10^k <= v < 10^k+1.
+// Note: this property holds for v's upper boundary m+ too.
+// 10^k <= m+ < 10^k+1.
+// (see explanation below).
+//
+// Examples:
+// EstimatePower(0) => 16
+// EstimatePower(-52) => 0
+//
+// Note: e >= 0 => EstimatedPower(e) > 0. No similar claim can be made for e<0.
+static int EstimatePower(int exponent) {
+ // This function estimates log10 of v where v = f*2^e (with e == exponent).
+ // Note that 10^floor(log10(v)) <= v, but v <= 10^ceil(log10(v)).
+ // Note that f is bounded by its container size. Let p = 53 (the double's
+ // significand size). Then 2^(p-1) <= f < 2^p.
+ //
+ // Given that log10(v) == log2(v)/log2(10) and e+(len(f)-1) is quite close
+ // to log2(v) the function is simplified to (e+(len(f)-1)/log2(10)).
+ // The computed number undershoots by less than 0.631 (when we compute log3
+ // and not log10).
+ //
+ // Optimization: since we only need an approximated result this computation
+ // can be performed on 64 bit integers. On x86/x64 architecture the speedup is
+ // not really measurable, though.
+ //
+ // Since we want to avoid overshooting we decrement by 1e10 so that
+ // floating-point imprecisions don't affect us.
+ //
+ // Explanation for v's boundary m+: the computation takes advantage of
+ // the fact that 2^(p-1) <= f < 2^p. Boundaries still satisfy this requirement
+ // (even for denormals where the delta can be much more important).
+
+ const double k1Log10 = 0.30102999566398114; // 1/lg(10)
+
+ // For doubles len(f) == 53 (don't forget the hidden bit).
+ const int kSignificandSize = Double::kSignificandSize;
+ double estimate = ceil((exponent + kSignificandSize - 1) * k1Log10 - 1e-10);
+ return static_cast<int>(estimate);
+}
+
+
+// See comments for InitialScaledStartValues.
+static void InitialScaledStartValuesPositiveExponent(
+ uint64_t significand, int exponent,
+ int estimated_power, bool need_boundary_deltas,
+ Bignum* numerator, Bignum* denominator,
+ Bignum* delta_minus, Bignum* delta_plus) {
+ // A positive exponent implies a positive power.
+ ASSERT(estimated_power >= 0);
+ // Since the estimated_power is positive we simply multiply the denominator
+ // by 10^estimated_power.
+
+ // numerator = v.
+ numerator->AssignUInt64(significand);
+ numerator->ShiftLeft(exponent);
+ // denominator = 10^estimated_power.
+ denominator->AssignPowerUInt16(10, estimated_power);
+
+ if (need_boundary_deltas) {
+ // Introduce a common denominator so that the deltas to the boundaries are
+ // integers.
+ denominator->ShiftLeft(1);
+ numerator->ShiftLeft(1);
+ // Let v = f * 2^e, then m+ - v = 1/2 * 2^e; With the common
+ // denominator (of 2) delta_plus equals 2^e.
+ delta_plus->AssignUInt16(1);
+ delta_plus->ShiftLeft(exponent);
+ // Same for delta_minus. The adjustments if f == 2^p-1 are done later.
+ delta_minus->AssignUInt16(1);
+ delta_minus->ShiftLeft(exponent);
+ }
+}
+
+
+// See comments for InitialScaledStartValues
+static void InitialScaledStartValuesNegativeExponentPositivePower(
+ uint64_t significand, int exponent,
+ int estimated_power, bool need_boundary_deltas,
+ Bignum* numerator, Bignum* denominator,
+ Bignum* delta_minus, Bignum* delta_plus) {
+ // v = f * 2^e with e < 0, and with estimated_power >= 0.
+ // This means that e is close to 0 (have a look at how estimated_power is
+ // computed).
+
+ // numerator = significand
+ // since v = significand * 2^exponent this is equivalent to
+ // numerator = v * / 2^-exponent
+ numerator->AssignUInt64(significand);
+ // denominator = 10^estimated_power * 2^-exponent (with exponent < 0)
+ denominator->AssignPowerUInt16(10, estimated_power);
+ denominator->ShiftLeft(-exponent);
+
+ if (need_boundary_deltas) {
+ // Introduce a common denominator so that the deltas to the boundaries are
+ // integers.
+ denominator->ShiftLeft(1);
+ numerator->ShiftLeft(1);
+ // Let v = f * 2^e, then m+ - v = 1/2 * 2^e; With the common
+ // denominator (of 2) delta_plus equals 2^e.
+ // Given that the denominator already includes v's exponent the distance
+ // to the boundaries is simply 1.
+ delta_plus->AssignUInt16(1);
+ // Same for delta_minus. The adjustments if f == 2^p-1 are done later.
+ delta_minus->AssignUInt16(1);
+ }
+}
+
+
+// See comments for InitialScaledStartValues
+static void InitialScaledStartValuesNegativeExponentNegativePower(
+ uint64_t significand, int exponent,
+ int estimated_power, bool need_boundary_deltas,
+ Bignum* numerator, Bignum* denominator,
+ Bignum* delta_minus, Bignum* delta_plus) {
+ // Instead of multiplying the denominator with 10^estimated_power we
+ // multiply all values (numerator and deltas) by 10^-estimated_power.
+
+ // Use numerator as temporary container for power_ten.
+ Bignum* power_ten = numerator;
+ power_ten->AssignPowerUInt16(10, -estimated_power);
+
+ if (need_boundary_deltas) {
+ // Since power_ten == numerator we must make a copy of 10^estimated_power
+ // before we complete the computation of the numerator.
+ // delta_plus = delta_minus = 10^estimated_power
+ delta_plus->AssignBignum(*power_ten);
+ delta_minus->AssignBignum(*power_ten);
+ }
+
+ // numerator = significand * 2 * 10^-estimated_power
+ // since v = significand * 2^exponent this is equivalent to
+ // numerator = v * 10^-estimated_power * 2 * 2^-exponent.
+ // Remember: numerator has been abused as power_ten. So no need to assign it
+ // to itself.
+ ASSERT(numerator == power_ten);
+ numerator->MultiplyByUInt64(significand);
+
+ // denominator = 2 * 2^-exponent with exponent < 0.
+ denominator->AssignUInt16(1);
+ denominator->ShiftLeft(-exponent);
+
+ if (need_boundary_deltas) {
+ // Introduce a common denominator so that the deltas to the boundaries are
+ // integers.
+ numerator->ShiftLeft(1);
+ denominator->ShiftLeft(1);
+ // With this shift the boundaries have their correct value, since
+ // delta_plus = 10^-estimated_power, and
+ // delta_minus = 10^-estimated_power.
+ // These assignments have been done earlier.
+ // The adjustments if f == 2^p-1 (lower boundary is closer) are done later.
+ }
+}
+
+
+// Let v = significand * 2^exponent.
+// Computes v / 10^estimated_power exactly, as a ratio of two bignums, numerator
+// and denominator. The functions GenerateShortestDigits and
+// GenerateCountedDigits will then convert this ratio to its decimal
+// representation d, with the required accuracy.
+// Then d * 10^estimated_power is the representation of v.
+// (Note: the fraction and the estimated_power might get adjusted before
+// generating the decimal representation.)
+//
+// The initial start values consist of:
+// - a scaled numerator: s.t. numerator/denominator == v / 10^estimated_power.
+// - a scaled (common) denominator.
+// optionally (used by GenerateShortestDigits to decide if it has the shortest
+// decimal converting back to v):
+// - v - m-: the distance to the lower boundary.
+// - m+ - v: the distance to the upper boundary.
+//
+// v, m+, m-, and therefore v - m- and m+ - v all share the same denominator.
+//
+// Let ep == estimated_power, then the returned values will satisfy:
+// v / 10^ep = numerator / denominator.
+// v's boundarys m- and m+:
+// m- / 10^ep == v / 10^ep - delta_minus / denominator
+// m+ / 10^ep == v / 10^ep + delta_plus / denominator
+// Or in other words:
+// m- == v - delta_minus * 10^ep / denominator;
+// m+ == v + delta_plus * 10^ep / denominator;
+//
+// Since 10^(k-1) <= v < 10^k (with k == estimated_power)
+// or 10^k <= v < 10^(k+1)
+// we then have 0.1 <= numerator/denominator < 1
+// or 1 <= numerator/denominator < 10
+//
+// It is then easy to kickstart the digit-generation routine.
+//
+// The boundary-deltas are only filled if the mode equals BIGNUM_DTOA_SHORTEST
+// or BIGNUM_DTOA_SHORTEST_SINGLE.
+
+static void InitialScaledStartValues(uint64_t significand,
+ int exponent,
+ bool lower_boundary_is_closer,
+ int estimated_power,
+ bool need_boundary_deltas,
+ Bignum* numerator,
+ Bignum* denominator,
+ Bignum* delta_minus,
+ Bignum* delta_plus) {
+ if (exponent >= 0) {
+ InitialScaledStartValuesPositiveExponent(
+ significand, exponent, estimated_power, need_boundary_deltas,
+ numerator, denominator, delta_minus, delta_plus);
+ } else if (estimated_power >= 0) {
+ InitialScaledStartValuesNegativeExponentPositivePower(
+ significand, exponent, estimated_power, need_boundary_deltas,
+ numerator, denominator, delta_minus, delta_plus);
+ } else {
+ InitialScaledStartValuesNegativeExponentNegativePower(
+ significand, exponent, estimated_power, need_boundary_deltas,
+ numerator, denominator, delta_minus, delta_plus);
+ }
+
+ if (need_boundary_deltas && lower_boundary_is_closer) {
+ // The lower boundary is closer at half the distance of "normal" numbers.
+ // Increase the common denominator and adapt all but the delta_minus.
+ denominator->ShiftLeft(1); // *2
+ numerator->ShiftLeft(1); // *2
+ delta_plus->ShiftLeft(1); // *2
+ }
+}
+
+
+// This routine multiplies numerator/denominator so that its values lies in the
+// range 1-10. That is after a call to this function we have:
+// 1 <= (numerator + delta_plus) /denominator < 10.
+// Let numerator the input before modification and numerator' the argument
+// after modification, then the output-parameter decimal_point is such that
+// numerator / denominator * 10^estimated_power ==
+// numerator' / denominator' * 10^(decimal_point - 1)
+// In some cases estimated_power was too low, and this is already the case. We
+// then simply adjust the power so that 10^(k-1) <= v < 10^k (with k ==
+// estimated_power) but do not touch the numerator or denominator.
+// Otherwise the routine multiplies the numerator and the deltas by 10.
+static void FixupMultiply10(int estimated_power, bool is_even,
+ int* decimal_point,
+ Bignum* numerator, Bignum* denominator,
+ Bignum* delta_minus, Bignum* delta_plus) {
+ bool in_range;
+ if (is_even) {
+ // For IEEE doubles half-way cases (in decimal system numbers ending with 5)
+ // are rounded to the closest floating-point number with even significand.
+ in_range = Bignum::PlusCompare(*numerator, *delta_plus, *denominator) >= 0;
+ } else {
+ in_range = Bignum::PlusCompare(*numerator, *delta_plus, *denominator) > 0;
+ }
+ if (in_range) {
+ // Since numerator + delta_plus >= denominator we already have
+ // 1 <= numerator/denominator < 10. Simply update the estimated_power.
+ *decimal_point = estimated_power + 1;
+ } else {
+ *decimal_point = estimated_power;
+ numerator->Times10();
+ if (Bignum::Equal(*delta_minus, *delta_plus)) {
+ delta_minus->Times10();
+ delta_plus->AssignBignum(*delta_minus);
+ } else {
+ delta_minus->Times10();
+ delta_plus->Times10();
+ }
+ }
+}
+
+} // namespace double_conversion
diff --git a/mfbt/double-conversion/bignum-dtoa.h b/mfbt/double-conversion/bignum-dtoa.h
new file mode 100644
index 0000000..34b9619
--- /dev/null
+++ b/mfbt/double-conversion/bignum-dtoa.h
@@ -0,0 +1,84 @@
+// Copyright 2010 the V8 project authors. All rights reserved.
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+// * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+// * 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.
+// * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived
+// from this software without specific prior written permission.
+//
+// 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.
+
+#ifndef DOUBLE_CONVERSION_BIGNUM_DTOA_H_
+#define DOUBLE_CONVERSION_BIGNUM_DTOA_H_
+
+#include "utils.h"
+
+namespace double_conversion {
+
+enum BignumDtoaMode {
+ // Return the shortest correct representation.
+ // For example the output of 0.299999999999999988897 is (the less accurate but
+ // correct) 0.3.
+ BIGNUM_DTOA_SHORTEST,
+ // Same as BIGNUM_DTOA_SHORTEST but for single-precision floats.
+ BIGNUM_DTOA_SHORTEST_SINGLE,
+ // Return a fixed number of digits after the decimal point.
+ // For instance fixed(0.1, 4) becomes 0.1000
+ // If the input number is big, the output will be big.
+ BIGNUM_DTOA_FIXED,
+ // Return a fixed number of digits, no matter what the exponent is.
+ BIGNUM_DTOA_PRECISION
+};
+
+// Converts the given double 'v' to ascii.
+// The result should be interpreted as buffer * 10^(point-length).
+// The buffer will be null-terminated.
+//
+// The input v must be > 0 and different from NaN, and Infinity.
+//
+// The output depends on the given mode:
+// - SHORTEST: produce the least amount of digits for which the internal
+// identity requirement is still satisfied. If the digits are printed
+// (together with the correct exponent) then reading this number will give
+// 'v' again. The buffer will choose the representation that is closest to
+// 'v'. If there are two at the same distance, than the number is round up.
+// In this mode the 'requested_digits' parameter is ignored.
+// - FIXED: produces digits necessary to print a given number with
+// 'requested_digits' digits after the decimal point. The produced digits
+// might be too short in which case the caller has to fill the gaps with '0's.
+// Example: toFixed(0.001, 5) is allowed to return buffer="1", point=-2.
+// Halfway cases are rounded up. The call toFixed(0.15, 2) thus returns
+// buffer="2", point=0.
+// Note: the length of the returned buffer has no meaning wrt the significance
+// of its digits. That is, just because it contains '0's does not mean that
+// any other digit would not satisfy the internal identity requirement.
+// - PRECISION: produces 'requested_digits' where the first digit is not '0'.
+// Even though the length of produced digits usually equals
+// 'requested_digits', the function is allowed to return fewer digits, in
+// which case the caller has to fill the missing digits with '0's.
+// Halfway cases are again rounded up.
+// 'BignumDtoa' expects the given buffer to be big enough to hold all digits
+// and a terminating null-character.
+void BignumDtoa(double v, BignumDtoaMode mode, int requested_digits,
+ Vector<char> buffer, int* length, int* point);
+
+} // namespace double_conversion
+
+#endif // DOUBLE_CONVERSION_BIGNUM_DTOA_H_
diff --git a/mfbt/double-conversion/bignum.cc b/mfbt/double-conversion/bignum.cc
new file mode 100644
index 0000000..747491a
--- /dev/null
+++ b/mfbt/double-conversion/bignum.cc
@@ -0,0 +1,764 @@
+// Copyright 2010 the V8 project authors. All rights reserved.
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+// * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+// * 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.
+// * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived
+// from this software without specific prior written permission.
+//
+// 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.
+
+#include "bignum.h"
+#include "utils.h"
+
+namespace double_conversion {
+
+Bignum::Bignum()
+ : bigits_(bigits_buffer_, kBigitCapacity), used_digits_(0), exponent_(0) {
+ for (int i = 0; i < kBigitCapacity; ++i) {
+ bigits_[i] = 0;
+ }
+}
+
+
+template<typename S>
+static int BitSize(S value) {
+ return 8 * sizeof(value);
+}
+
+// Guaranteed to lie in one Bigit.
+void Bignum::AssignUInt16(uint16_t value) {
+ ASSERT(kBigitSize >= BitSize(value));
+ Zero();
+ if (value == 0) return;
+
+ EnsureCapacity(1);
+ bigits_[0] = value;
+ used_digits_ = 1;
+}
+
+
+void Bignum::AssignUInt64(uint64_t value) {
+ const int kUInt64Size = 64;
+
+ Zero();
+ if (value == 0) return;
+
+ int needed_bigits = kUInt64Size / kBigitSize + 1;
+ EnsureCapacity(needed_bigits);
+ for (int i = 0; i < needed_bigits; ++i) {
+ bigits_[i] = value & kBigitMask;
+ value = value >> kBigitSize;
+ }
+ used_digits_ = needed_bigits;
+ Clamp();
+}
+
+
+void Bignum::AssignBignum(const Bignum& other) {
+ exponent_ = other.exponent_;
+ for (int i = 0; i < other.used_digits_; ++i) {
+ bigits_[i] = other.bigits_[i];
+ }
+ // Clear the excess digits (if there were any).
+ for (int i = other.used_digits_; i < used_digits_; ++i) {
+ bigits_[i] = 0;
+ }
+ used_digits_ = other.used_digits_;
+}
+
+
+static uint64_t ReadUInt64(Vector<const char> buffer,
+ int from,
+ int digits_to_read) {
+ uint64_t result = 0;
+ for (int i = from; i < from + digits_to_read; ++i) {
+ int digit = buffer[i] - '0';
+ ASSERT(0 <= digit && digit <= 9);
+ result = result * 10 + digit;
+ }
+ return result;
+}
+
+
+void Bignum::AssignDecimalString(Vector<const char> value) {
+ // 2^64 = 18446744073709551616 > 10^19
+ const int kMaxUint64DecimalDigits = 19;
+ Zero();
+ int length = value.length();
+ int pos = 0;
+ // Let's just say that each digit needs 4 bits.
+ while (length >= kMaxUint64DecimalDigits) {
+ uint64_t digits = ReadUInt64(value, pos, kMaxUint64DecimalDigits);
+ pos += kMaxUint64DecimalDigits;
+ length -= kMaxUint64DecimalDigits;
+ MultiplyByPowerOfTen(kMaxUint64DecimalDigits);
+ AddUInt64(digits);
+ }
+ uint64_t digits = ReadUInt64(value, pos, length);
+ MultiplyByPowerOfTen(length);
+ AddUInt64(digits);
+ Clamp();
+}
+
+
+static int HexCharValue(char c) {
+ if ('0' <= c && c <= '9') return c - '0';
+ if ('a' <= c && c <= 'f') return 10 + c - 'a';
+ if ('A' <= c && c <= 'F') return 10 + c - 'A';
+ UNREACHABLE();
+ return 0; // To make compiler happy.
+}
+
+
+void Bignum::AssignHexString(Vector<const char> value) {
+ Zero();
+ int length = value.length();
+
+ int needed_bigits = length * 4 / kBigitSize + 1;
+ EnsureCapacity(needed_bigits);
+ int string_index = length - 1;
+ for (int i = 0; i < needed_bigits - 1; ++i) {
+ // These bigits are guaranteed to be "full".
+ Chunk current_bigit = 0;
+ for (int j = 0; j < kBigitSize / 4; j++) {
+ current_bigit += HexCharValue(value[string_index--]) << (j * 4);
+ }
+ bigits_[i] = current_bigit;
+ }
+ used_digits_ = needed_bigits - 1;
+
+ Chunk most_significant_bigit = 0; // Could be = 0;
+ for (int j = 0; j <= string_index; ++j) {
+ most_significant_bigit <<= 4;
+ most_significant_bigit += HexCharValue(value[j]);
+ }
+ if (most_significant_bigit != 0) {
+ bigits_[used_digits_] = most_significant_bigit;
+ used_digits_++;
+ }
+ Clamp();
+}
+
+
+void Bignum::AddUInt64(uint64_t operand) {
+ if (operand == 0) return;
+ Bignum other;
+ other.AssignUInt64(operand);
+ AddBignum(other);
+}
+
+
+void Bignum::AddBignum(const Bignum& other) {
+ ASSERT(IsClamped());
+ ASSERT(other.IsClamped());
+
+ // If this has a greater exponent than other append zero-bigits to this.
+ // After this call exponent_ <= other.exponent_.
+ Align(other);
+
+ // There are two possibilities:
+ // aaaaaaaaaaa 0000 (where the 0s represent a's exponent)
+ // bbbbb 00000000
+ // ----------------
+ // ccccccccccc 0000
+ // or
+ // aaaaaaaaaa 0000
+ // bbbbbbbbb 0000000
+ // -----------------
+ // cccccccccccc 0000
+ // In both cases we might need a carry bigit.
+
+ EnsureCapacity(1 + Max(BigitLength(), other.BigitLength()) - exponent_);
+ Chunk carry = 0;
+ int bigit_pos = other.exponent_ - exponent_;
+ ASSERT(bigit_pos >= 0);
+ for (int i = 0; i < other.used_digits_; ++i) {
+ Chunk sum = bigits_[bigit_pos] + other.bigits_[i] + carry;
+ bigits_[bigit_pos] = sum & kBigitMask;
+ carry = sum >> kBigitSize;
+ bigit_pos++;
+ }
+
+ while (carry != 0) {
+ Chunk sum = bigits_[bigit_pos] + carry;
+ bigits_[bigit_pos] = sum & kBigitMask;
+ carry = sum >> kBigitSize;
+ bigit_pos++;
+ }
+ used_digits_ = Max(bigit_pos, used_digits_);
+ ASSERT(IsClamped());
+}
+
+
+void Bignum::SubtractBignum(const Bignum& other) {
+ ASSERT(IsClamped());
+ ASSERT(other.IsClamped());
+ // We require this to be bigger than other.
+ ASSERT(LessEqual(other, *this));
+
+ Align(other);
+
+ int offset = other.exponent_ - exponent_;
+ Chunk borrow = 0;
+ int i;
+ for (i = 0; i < other.used_digits_; ++i) {
+ ASSERT((borrow == 0) || (borrow == 1));
+ Chunk difference = bigits_[i + offset] - other.bigits_[i] - borrow;
+ bigits_[i + offset] = difference & kBigitMask;
+ borrow = difference >> (kChunkSize - 1);
+ }
+ while (borrow != 0) {
+ Chunk difference = bigits_[i + offset] - borrow;
+ bigits_[i + offset] = difference & kBigitMask;
+ borrow = difference >> (kChunkSize - 1);
+ ++i;
+ }
+ Clamp();
+}
+
+
+void Bignum::ShiftLeft(int shift_amount) {
+ if (used_digits_ == 0) return;
+ exponent_ += shift_amount / kBigitSize;
+ int local_shift = shift_amount % kBigitSize;
+ EnsureCapacity(used_digits_ + 1);
+ BigitsShiftLeft(local_shift);
+}
+
+
+void Bignum::MultiplyByUInt32(uint32_t factor) {
+ if (factor == 1) return;
+ if (factor == 0) {
+ Zero();
+ return;
+ }
+ if (used_digits_ == 0) return;
+
+ // The product of a bigit with the factor is of size kBigitSize + 32.
+ // Assert that this number + 1 (for the carry) fits into double chunk.
+ ASSERT(kDoubleChunkSize >= kBigitSize + 32 + 1);
+ DoubleChunk carry = 0;
+ for (int i = 0; i < used_digits_; ++i) {
+ DoubleChunk product = static_cast<DoubleChunk>(factor) * bigits_[i] + carry;
+ bigits_[i] = static_cast<Chunk>(product & kBigitMask);
+ carry = (product >> kBigitSize);
+ }
+ while (carry != 0) {
+ EnsureCapacity(used_digits_ + 1);
+ bigits_[used_digits_] = carry & kBigitMask;
+ used_digits_++;
+ carry >>= kBigitSize;
+ }
+}
+
+
+void Bignum::MultiplyByUInt64(uint64_t factor) {
+ if (factor == 1) return;
+ if (factor == 0) {
+ Zero();
+ return;
+ }
+ ASSERT(kBigitSize < 32);
+ uint64_t carry = 0;
+ uint64_t low = factor & 0xFFFFFFFF;
+ uint64_t high = factor >> 32;
+ for (int i = 0; i < used_digits_; ++i) {
+ uint64_t product_low = low * bigits_[i];
+ uint64_t product_high = high * bigits_[i];
+ uint64_t tmp = (carry & kBigitMask) + product_low;
+ bigits_[i] = tmp & kBigitMask;
+ carry = (carry >> kBigitSize) + (tmp >> kBigitSize) +
+ (product_high << (32 - kBigitSize));
+ }
+ while (carry != 0) {
+ EnsureCapacity(used_digits_ + 1);
+ bigits_[used_digits_] = carry & kBigitMask;
+ used_digits_++;
+ carry >>= kBigitSize;
+ }
+}
+
+
+void Bignum::MultiplyByPowerOfTen(int exponent) {
+ const uint64_t kFive27 = UINT64_2PART_C(0x6765c793, fa10079d);
+ const uint16_t kFive1 = 5;
+ const uint16_t kFive2 = kFive1 * 5;
+ const uint16_t kFive3 = kFive2 * 5;
+ const uint16_t kFive4 = kFive3 * 5;
+ const uint16_t kFive5 = kFive4 * 5;
+ const uint16_t kFive6 = kFive5 * 5;
+ const uint32_t kFive7 = kFive6 * 5;
+ const uint32_t kFive8 = kFive7 * 5;
+ const uint32_t kFive9 = kFive8 * 5;
+ const uint32_t kFive10 = kFive9 * 5;
+ const uint32_t kFive11 = kFive10 * 5;
+ const uint32_t kFive12 = kFive11 * 5;
+ const uint32_t kFive13 = kFive12 * 5;
+ const uint32_t kFive1_to_12[] =
+ { kFive1, kFive2, kFive3, kFive4, kFive5, kFive6,
+ kFive7, kFive8, kFive9, kFive10, kFive11, kFive12 };
+
+ ASSERT(exponent >= 0);
+ if (exponent == 0) return;
+ if (used_digits_ == 0) return;
+
+ // We shift by exponent at the end just before returning.
+ int remaining_exponent = exponent;
+ while (remaining_exponent >= 27) {
+ MultiplyByUInt64(kFive27);
+ remaining_exponent -= 27;
+ }
+ while (remaining_exponent >= 13) {
+ MultiplyByUInt32(kFive13);
+ remaining_exponent -= 13;
+ }
+ if (remaining_exponent > 0) {
+ MultiplyByUInt32(kFive1_to_12[remaining_exponent - 1]);
+ }
+ ShiftLeft(exponent);
+}
+
+
+void Bignum::Square() {
+ ASSERT(IsClamped());
+ int product_length = 2 * used_digits_;
+ EnsureCapacity(product_length);
+
+ // Comba multiplication: compute each column separately.
+ // Example: r = a2a1a0 * b2b1b0.
+ // r = 1 * a0b0 +
+ // 10 * (a1b0 + a0b1) +
+ // 100 * (a2b0 + a1b1 + a0b2) +
+ // 1000 * (a2b1 + a1b2) +
+ // 10000 * a2b2
+ //
+ // In the worst case we have to accumulate nb-digits products of digit*digit.
+ //
+ // Assert that the additional number of bits in a DoubleChunk are enough to
+ // sum up used_digits of Bigit*Bigit.
+ if ((1 << (2 * (kChunkSize - kBigitSize))) <= used_digits_) {
+ UNIMPLEMENTED();
+ }
+ DoubleChunk accumulator = 0;
+ // First shift the digits so we don't overwrite them.
+ int copy_offset = used_digits_;
+ for (int i = 0; i < used_digits_; ++i) {
+ bigits_[copy_offset + i] = bigits_[i];
+ }
+ // We have two loops to avoid some 'if's in the loop.
+ for (int i = 0; i < used_digits_; ++i) {
+ // Process temporary digit i with power i.
+ // The sum of the two indices must be equal to i.
+ int bigit_index1 = i;
+ int bigit_index2 = 0;
+ // Sum all of the sub-products.
+ while (bigit_index1 >= 0) {
+ Chunk chunk1 = bigits_[copy_offset + bigit_index1];
+ Chunk chunk2 = bigits_[copy_offset + bigit_index2];
+ accumulator += static_cast<DoubleChunk>(chunk1) * chunk2;
+ bigit_index1--;
+ bigit_index2++;
+ }
+ bigits_[i] = static_cast<Chunk>(accumulator) & kBigitMask;
+ accumulator >>= kBigitSize;
+ }
+ for (int i = used_digits_; i < product_length; ++i) {
+ int bigit_index1 = used_digits_ - 1;
+ int bigit_index2 = i - bigit_index1;
+ // Invariant: sum of both indices is again equal to i.
+ // Inner loop runs 0 times on last iteration, emptying accumulator.
+ while (bigit_index2 < used_digits_) {
+ Chunk chunk1 = bigits_[copy_offset + bigit_index1];
+ Chunk chunk2 = bigits_[copy_offset + bigit_index2];
+ accumulator += static_cast<DoubleChunk>(chunk1) * chunk2;
+ bigit_index1--;
+ bigit_index2++;
+ }
+ // The overwritten bigits_[i] will never be read in further loop iterations,
+ // because bigit_index1 and bigit_index2 are always greater
+ // than i - used_digits_.
+ bigits_[i] = static_cast<Chunk>(accumulator) & kBigitMask;
+ accumulator >>= kBigitSize;
+ }
+ // Since the result was guaranteed to lie inside the number the
+ // accumulator must be 0 now.
+ ASSERT(accumulator == 0);
+
+ // Don't forget to update the used_digits and the exponent.
+ used_digits_ = product_length;
+ exponent_ *= 2;
+ Clamp();
+}
+
+
+void Bignum::AssignPowerUInt16(uint16_t base, int power_exponent) {
+ ASSERT(base != 0);
+ ASSERT(power_exponent >= 0);
+ if (power_exponent == 0) {
+ AssignUInt16(1);
+ return;
+ }
+ Zero();
+ int shifts = 0;
+ // We expect base to be in range 2-32, and most often to be 10.
+ // It does not make much sense to implement different algorithms for counting
+ // the bits.
+ while ((base & 1) == 0) {
+ base >>= 1;
+ shifts++;
+ }
+ int bit_size = 0;
+ int tmp_base = base;
+ while (tmp_base != 0) {
+ tmp_base >>= 1;
+ bit_size++;
+ }
+ int final_size = bit_size * power_exponent;
+ // 1 extra bigit for the shifting, and one for rounded final_size.
+ EnsureCapacity(final_size / kBigitSize + 2);
+
+ // Left to Right exponentiation.
+ int mask = 1;
+ while (power_exponent >= mask) mask <<= 1;
+
+ // The mask is now pointing to the bit above the most significant 1-bit of
+ // power_exponent.
+ // Get rid of first 1-bit;
+ mask >>= 2;
+ uint64_t this_value = base;
+
+ bool delayed_multipliciation = false;
+ const uint64_t max_32bits = 0xFFFFFFFF;
+ while (mask != 0 && this_value <= max_32bits) {
+ this_value = this_value * this_value;
+ // Verify that there is enough space in this_value to perform the
+ // multiplication. The first bit_size bits must be 0.
+ if ((power_exponent & mask) != 0) {
+ uint64_t base_bits_mask =
+ ~((static_cast<uint64_t>(1) << (64 - bit_size)) - 1);
+ bool high_bits_zero = (this_value & base_bits_mask) == 0;
+ if (high_bits_zero) {
+ this_value *= base;
+ } else {
+ delayed_multipliciation = true;
+ }
+ }
+ mask >>= 1;
+ }
+ AssignUInt64(this_value);
+ if (delayed_multipliciation) {
+ MultiplyByUInt32(base);
+ }
+
+ // Now do the same thing as a bignum.
+ while (mask != 0) {
+ Square();
+ if ((power_exponent & mask) != 0) {
+ MultiplyByUInt32(base);
+ }
+ mask >>= 1;
+ }
+
+ // And finally add the saved shifts.
+ ShiftLeft(shifts * power_exponent);
+}
+
+
+// Precondition: this/other < 16bit.
+uint16_t Bignum::DivideModuloIntBignum(const Bignum& other) {
+ ASSERT(IsClamped());
+ ASSERT(other.IsClamped());
+ ASSERT(other.used_digits_ > 0);
+
+ // Easy case: if we have less digits than the divisor than the result is 0.
+ // Note: this handles the case where this == 0, too.
+ if (BigitLength() < other.BigitLength()) {
+ return 0;
+ }
+
+ Align(other);
+
+ uint16_t result = 0;
+
+ // Start by removing multiples of 'other' until both numbers have the same
+ // number of digits.
+ while (BigitLength() > other.BigitLength()) {
+ // This naive approach is extremely inefficient if the this divided other
+ // might be big. This function is implemented for doubleToString where
+ // the result should be small (less than 10).
+ ASSERT(other.bigits_[other.used_digits_ - 1] >= ((1 << kBigitSize) / 16));
+ // Remove the multiples of the first digit.
+ // Example this = 23 and other equals 9. -> Remove 2 multiples.
+ result += bigits_[used_digits_ - 1];
+ SubtractTimes(other, bigits_[used_digits_ - 1]);
+ }
+
+ ASSERT(BigitLength() == other.BigitLength());
+
+ // Both bignums are at the same length now.
+ // Since other has more than 0 digits we know that the access to
+ // bigits_[used_digits_ - 1] is safe.
+ Chunk this_bigit = bigits_[used_digits_ - 1];
+ Chunk other_bigit = other.bigits_[other.used_digits_ - 1];
+
+ if (other.used_digits_ == 1) {
+ // Shortcut for easy (and common) case.
+ int quotient = this_bigit / other_bigit;
+ bigits_[used_digits_ - 1] = this_bigit - other_bigit * quotient;
+ result += quotient;
+ Clamp();
+ return result;
+ }
+
+ int division_estimate = this_bigit / (other_bigit + 1);
+ result += division_estimate;
+ SubtractTimes(other, division_estimate);
+
+ if (other_bigit * (division_estimate + 1) > this_bigit) {
+ // No need to even try to subtract. Even if other's remaining digits were 0
+ // another subtraction would be too much.
+ return result;
+ }
+
+ while (LessEqual(other, *this)) {
+ SubtractBignum(other);
+ result++;
+ }
+ return result;
+}
+
+
+template<typename S>
+static int SizeInHexChars(S number) {
+ ASSERT(number > 0);
+ int result = 0;
+ while (number != 0) {
+ number >>= 4;
+ result++;
+ }
+ return result;
+}
+
+
+static char HexCharOfValue(int value) {
+ ASSERT(0 <= value && value <= 16);
+ if (value < 10) return value + '0';
+ return value - 10 + 'A';
+}
+
+
+bool Bignum::ToHexString(char* buffer, int buffer_size) const {
+ ASSERT(IsClamped());
+ // Each bigit must be printable as separate hex-character.
+ ASSERT(kBigitSize % 4 == 0);
+ const int kHexCharsPerBigit = kBigitSize / 4;
+
+ if (used_digits_ == 0) {
+ if (buffer_size < 2) return false;
+ buffer[0] = '0';
+ buffer[1] = '\0';
+ return true;
+ }
+ // We add 1 for the terminating '\0' character.
+ int needed_chars = (BigitLength() - 1) * kHexCharsPerBigit +
+ SizeInHexChars(bigits_[used_digits_ - 1]) + 1;
+ if (needed_chars > buffer_size) return false;
+ int string_index = needed_chars - 1;
+ buffer[string_index--] = '\0';
+ for (int i = 0; i < exponent_; ++i) {
+ for (int j = 0; j < kHexCharsPerBigit; ++j) {
+ buffer[string_index--] = '0';
+ }
+ }
+ for (int i = 0; i < used_digits_ - 1; ++i) {
+ Chunk current_bigit = bigits_[i];
+ for (int j = 0; j < kHexCharsPerBigit; ++j) {
+ buffer[string_index--] = HexCharOfValue(current_bigit & 0xF);
+ current_bigit >>= 4;
+ }
+ }
+ // And finally the last bigit.
+ Chunk most_significant_bigit = bigits_[used_digits_ - 1];
+ while (most_significant_bigit != 0) {
+ buffer[string_index--] = HexCharOfValue(most_significant_bigit & 0xF);
+ most_significant_bigit >>= 4;
+ }
+ return true;
+}
+
+
+Bignum::Chunk Bignum::BigitAt(int index) const {
+ if (index >= BigitLength()) return 0;
+ if (index < exponent_) return 0;
+ return bigits_[index - exponent_];
+}
+
+
+int Bignum::Compare(const Bignum& a, const Bignum& b) {
+ ASSERT(a.IsClamped());
+ ASSERT(b.IsClamped());
+ int bigit_length_a = a.BigitLength();
+ int bigit_length_b = b.BigitLength();
+ if (bigit_length_a < bigit_length_b) return -1;
+ if (bigit_length_a > bigit_length_b) return +1;
+ for (int i = bigit_length_a - 1; i >= Min(a.exponent_, b.exponent_); --i) {
+ Chunk bigit_a = a.BigitAt(i);
+ Chunk bigit_b = b.BigitAt(i);
+ if (bigit_a < bigit_b) return -1;
+ if (bigit_a > bigit_b) return +1;
+ // Otherwise they are equal up to this digit. Try the next digit.
+ }
+ return 0;
+}
+
+
+int Bignum::PlusCompare(const Bignum& a, const Bignum& b, const Bignum& c) {
+ ASSERT(a.IsClamped());
+ ASSERT(b.IsClamped());
+ ASSERT(c.IsClamped());
+ if (a.BigitLength() < b.BigitLength()) {
+ return PlusCompare(b, a, c);
+ }
+ if (a.BigitLength() + 1 < c.BigitLength()) return -1;
+ if (a.BigitLength() > c.BigitLength()) return +1;
+ // The exponent encodes 0-bigits. So if there are more 0-digits in 'a' than
+ // 'b' has digits, then the bigit-length of 'a'+'b' must be equal to the one
+ // of 'a'.
+ if (a.exponent_ >= b.BigitLength() && a.BigitLength() < c.BigitLength()) {
+ return -1;
+ }
+
+ Chunk borrow = 0;
+ // Starting at min_exponent all digits are == 0. So no need to compare them.
+ int min_exponent = Min(Min(a.exponent_, b.exponent_), c.exponent_);
+ for (int i = c.BigitLength() - 1; i >= min_exponent; --i) {
+ Chunk chunk_a = a.BigitAt(i);
+ Chunk chunk_b = b.BigitAt(i);
+ Chunk chunk_c = c.BigitAt(i);
+ Chunk sum = chunk_a + chunk_b;
+ if (sum > chunk_c + borrow) {
+ return +1;
+ } else {
+ borrow = chunk_c + borrow - sum;
+ if (borrow > 1) return -1;
+ borrow <<= kBigitSize;
+ }
+ }
+ if (borrow == 0) return 0;
+ return -1;
+}
+
+
+void Bignum::Clamp() {
+ while (used_digits_ > 0 && bigits_[used_digits_ - 1] == 0) {
+ used_digits_--;
+ }
+ if (used_digits_ == 0) {
+ // Zero.
+ exponent_ = 0;
+ }
+}
+
+
+bool Bignum::IsClamped() const {
+ return used_digits_ == 0 || bigits_[used_digits_ - 1] != 0;
+}
+
+
+void Bignum::Zero() {
+ for (int i = 0; i < used_digits_; ++i) {
+ bigits_[i] = 0;
+ }
+ used_digits_ = 0;
+ exponent_ = 0;
+}
+
+
+void Bignum::Align(const Bignum& other) {
+ if (exponent_ > other.exponent_) {
+ // If "X" represents a "hidden" digit (by the exponent) then we are in the
+ // following case (a == this, b == other):
+ // a: aaaaaaXXXX or a: aaaaaXXX
+ // b: bbbbbbX b: bbbbbbbbXX
+ // We replace some of the hidden digits (X) of a with 0 digits.
+ // a: aaaaaa000X or a: aaaaa0XX
+ int zero_digits = exponent_ - other.exponent_;
+ EnsureCapacity(used_digits_ + zero_digits);
+ for (int i = used_digits_ - 1; i >= 0; --i) {
+ bigits_[i + zero_digits] = bigits_[i];
+ }
+ for (int i = 0; i < zero_digits; ++i) {
+ bigits_[i] = 0;
+ }
+ used_digits_ += zero_digits;
+ exponent_ -= zero_digits;
+ ASSERT(used_digits_ >= 0);
+ ASSERT(exponent_ >= 0);
+ }
+}
+
+
+void Bignum::BigitsShiftLeft(int shift_amount) {
+ ASSERT(shift_amount < kBigitSize);
+ ASSERT(shift_amount >= 0);
+ Chunk carry = 0;
+ for (int i = 0; i < used_digits_; ++i) {
+ Chunk new_carry = bigits_[i] >> (kBigitSize - shift_amount);
+ bigits_[i] = ((bigits_[i] << shift_amount) + carry) & kBigitMask;
+ carry = new_carry;
+ }
+ if (carry != 0) {
+ bigits_[used_digits_] = carry;
+ used_digits_++;
+ }
+}
+
+
+void Bignum::SubtractTimes(const Bignum& other, int factor) {
+ ASSERT(exponent_ <= other.exponent_);
+ if (factor < 3) {
+ for (int i = 0; i < factor; ++i) {
+ SubtractBignum(other);
+ }
+ return;
+ }
+ Chunk borrow = 0;
+ int exponent_diff = other.exponent_ - exponent_;
+ for (int i = 0; i < other.used_digits_; ++i) {
+ DoubleChunk product = static_cast<DoubleChunk>(factor) * other.bigits_[i];
+ DoubleChunk remove = borrow + product;
+ Chunk difference = bigits_[i + exponent_diff] - (remove & kBigitMask);
+ bigits_[i + exponent_diff] = difference & kBigitMask;
+ borrow = static_cast<Chunk>((difference >> (kChunkSize - 1)) +
+ (remove >> kBigitSize));
+ }
+ for (int i = other.used_digits_ + exponent_diff; i < used_digits_; ++i) {
+ if (borrow == 0) return;
+ Chunk difference = bigits_[i] - borrow;
+ bigits_[i] = difference & kBigitMask;
+ borrow = difference >> (kChunkSize - 1);
+ ++i;
+ }
+ Clamp();
+}
+
+
+} // namespace double_conversion
diff --git a/mfbt/double-conversion/bignum.h b/mfbt/double-conversion/bignum.h
new file mode 100644
index 0000000..5ec3544
--- /dev/null
+++ b/mfbt/double-conversion/bignum.h
@@ -0,0 +1,145 @@
+// Copyright 2010 the V8 project authors. All rights reserved.
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+// * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+// * 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.
+// * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived
+// from this software without specific prior written permission.
+//
+// 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.
+
+#ifndef DOUBLE_CONVERSION_BIGNUM_H_
+#define DOUBLE_CONVERSION_BIGNUM_H_
+
+#include "utils.h"
+
+namespace double_conversion {
+
+class Bignum {
+ public:
+ // 3584 = 128 * 28. We can represent 2^3584 > 10^1000 accurately.
+ // This bignum can encode much bigger numbers, since it contains an
+ // exponent.
+ static const int kMaxSignificantBits = 3584;
+
+ Bignum();
+ void AssignUInt16(uint16_t value);
+ void AssignUInt64(uint64_t value);
+ void AssignBignum(const Bignum& other);
+
+ void AssignDecimalString(Vector<const char> value);
+ void AssignHexString(Vector<const char> value);
+
+ void AssignPowerUInt16(uint16_t base, int exponent);
+
+ void AddUInt16(uint16_t operand);
+ void AddUInt64(uint64_t operand);
+ void AddBignum(const Bignum& other);
+ // Precondition: this >= other.
+ void SubtractBignum(const Bignum& other);
+
+ void Square();
+ void ShiftLeft(int shift_amount);
+ void MultiplyByUInt32(uint32_t factor);
+ void MultiplyByUInt64(uint64_t factor);
+ void MultiplyByPowerOfTen(int exponent);
+ void Times10() { return MultiplyByUInt32(10); }
+ // Pseudocode:
+ // int result = this / other;
+ // this = this % other;
+ // In the worst case this function is in O(this/other).
+ uint16_t DivideModuloIntBignum(const Bignum& other);
+
+ bool ToHexString(char* buffer, int buffer_size) const;
+
+ // Returns
+ // -1 if a < b,
+ // 0 if a == b, and
+ // +1 if a > b.
+ static int Compare(const Bignum& a, const Bignum& b);
+ static bool Equal(const Bignum& a, const Bignum& b) {
+ return Compare(a, b) == 0;
+ }
+ static bool LessEqual(const Bignum& a, const Bignum& b) {
+ return Compare(a, b) <= 0;
+ }
+ static bool Less(const Bignum& a, const Bignum& b) {
+ return Compare(a, b) < 0;
+ }
+ // Returns Compare(a + b, c);
+ static int PlusCompare(const Bignum& a, const Bignum& b, const Bignum& c);
+ // Returns a + b == c
+ static bool PlusEqual(const Bignum& a, const Bignum& b, const Bignum& c) {
+ return PlusCompare(a, b, c) == 0;
+ }
+ // Returns a + b <= c
+ static bool PlusLessEqual(const Bignum& a, const Bignum& b, const Bignum& c) {
+ return PlusCompare(a, b, c) <= 0;
+ }
+ // Returns a + b < c
+ static bool PlusLess(const Bignum& a, const Bignum& b, const Bignum& c) {
+ return PlusCompare(a, b, c) < 0;
+ }
+ private:
+ typedef uint32_t Chunk;
+ typedef uint64_t DoubleChunk;
+
+ static const int kChunkSize = sizeof(Chunk) * 8;
+ static const int kDoubleChunkSize = sizeof(DoubleChunk) * 8;
+ // With bigit size of 28 we loose some bits, but a double still fits easily
+ // into two chunks, and more importantly we can use the Comba multiplication.
+ static const int kBigitSize = 28;
+ static const Chunk kBigitMask = (1 << kBigitSize) - 1;
+ // Every instance allocates kBigitLength chunks on the stack. Bignums cannot
+ // grow. There are no checks if the stack-allocated space is sufficient.
+ static const int kBigitCapacity = kMaxSignificantBits / kBigitSize;
+
+ void EnsureCapacity(int size) {
+ if (size > kBigitCapacity) {
+ UNREACHABLE();
+ }
+ }
+ void Align(const Bignum& other);
+ void Clamp();
+ bool IsClamped() const;
+ void Zero();
+ // Requires this to have enough capacity (no tests done).
+ // Updates used_digits_ if necessary.
+ // shift_amount must be < kBigitSize.
+ void BigitsShiftLeft(int shift_amount);
+ // BigitLength includes the "hidden" digits encoded in the exponent.
+ int BigitLength() const { return used_digits_ + exponent_; }
+ Chunk BigitAt(int index) const;
+ void SubtractTimes(const Bignum& other, int factor);
+
+ Chunk bigits_buffer_[kBigitCapacity];
+ // A vector backed by bigits_buffer_. This way accesses to the array are
+ // checked for out-of-bounds errors.
+ Vector<Chunk> bigits_;
+ int used_digits_;
+ // The Bignum's value equals value(bigits_) * 2^(exponent_ * kBigitSize).
+ int exponent_;
+
+ DISALLOW_COPY_AND_ASSIGN(Bignum);
+};
+
+} // namespace double_conversion
+
+#endif // DOUBLE_CONVERSION_BIGNUM_H_
diff --git a/mfbt/double-conversion/cached-powers.cc b/mfbt/double-conversion/cached-powers.cc
new file mode 100644
index 0000000..c676429
--- /dev/null
+++ b/mfbt/double-conversion/cached-powers.cc
@@ -0,0 +1,175 @@
+// Copyright 2006-2008 the V8 project authors. All rights reserved.
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+// * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+// * 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.
+// * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived
+// from this software without specific prior written permission.
+//
+// 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.
+
+#include <stdarg.h>
+#include <limits.h>
+#include <math.h>
+
+#include "utils.h"
+
+#include "cached-powers.h"
+
+namespace double_conversion {
+
+struct CachedPower {
+ uint64_t significand;
+ int16_t binary_exponent;
+ int16_t decimal_exponent;
+};
+
+static const CachedPower kCachedPowers[] = {
+ {UINT64_2PART_C(0xfa8fd5a0, 081c0288), -1220, -348},
+ {UINT64_2PART_C(0xbaaee17f, a23ebf76), -1193, -340},
+ {UINT64_2PART_C(0x8b16fb20, 3055ac76), -1166, -332},
+ {UINT64_2PART_C(0xcf42894a, 5dce35ea), -1140, -324},
+ {UINT64_2PART_C(0x9a6bb0aa, 55653b2d), -1113, -316},
+ {UINT64_2PART_C(0xe61acf03, 3d1a45df), -1087, -308},
+ {UINT64_2PART_C(0xab70fe17, c79ac6ca), -1060, -300},
+ {UINT64_2PART_C(0xff77b1fc, bebcdc4f), -1034, -292},
+ {UINT64_2PART_C(0xbe5691ef, 416bd60c), -1007, -284},
+ {UINT64_2PART_C(0x8dd01fad, 907ffc3c), -980, -276},
+ {UINT64_2PART_C(0xd3515c28, 31559a83), -954, -268},
+ {UINT64_2PART_C(0x9d71ac8f, ada6c9b5), -927, -260},
+ {UINT64_2PART_C(0xea9c2277, 23ee8bcb), -901, -252},
+ {UINT64_2PART_C(0xaecc4991, 4078536d), -874, -244},
+ {UINT64_2PART_C(0x823c1279, 5db6ce57), -847, -236},
+ {UINT64_2PART_C(0xc2109436, 4dfb5637), -821, -228},
+ {UINT64_2PART_C(0x9096ea6f, 3848984f), -794, -220},
+ {UINT64_2PART_C(0xd77485cb, 25823ac7), -768, -212},
+ {UINT64_2PART_C(0xa086cfcd, 97bf97f4), -741, -204},
+ {UINT64_2PART_C(0xef340a98, 172aace5), -715, -196},
+ {UINT64_2PART_C(0xb23867fb, 2a35b28e), -688, -188},
+ {UINT64_2PART_C(0x84c8d4df, d2c63f3b), -661, -180},
+ {UINT64_2PART_C(0xc5dd4427, 1ad3cdba), -635, -172},
+ {UINT64_2PART_C(0x936b9fce, bb25c996), -608, -164},
+ {UINT64_2PART_C(0xdbac6c24, 7d62a584), -582, -156},
+ {UINT64_2PART_C(0xa3ab6658, 0d5fdaf6), -555, -148},
+ {UINT64_2PART_C(0xf3e2f893, dec3f126), -529, -140},
+ {UINT64_2PART_C(0xb5b5ada8, aaff80b8), -502, -132},
+ {UINT64_2PART_C(0x87625f05, 6c7c4a8b), -475, -124},
+ {UINT64_2PART_C(0xc9bcff60, 34c13053), -449, -116},
+ {UINT64_2PART_C(0x964e858c, 91ba2655), -422, -108},
+ {UINT64_2PART_C(0xdff97724, 70297ebd), -396, -100},
+ {UINT64_2PART_C(0xa6dfbd9f, b8e5b88f), -369, -92},
+ {UINT64_2PART_C(0xf8a95fcf, 88747d94), -343, -84},
+ {UINT64_2PART_C(0xb9447093, 8fa89bcf), -316, -76},
+ {UINT64_2PART_C(0x8a08f0f8, bf0f156b), -289, -68},
+ {UINT64_2PART_C(0xcdb02555, 653131b6), -263, -60},
+ {UINT64_2PART_C(0x993fe2c6, d07b7fac), -236, -52},
+ {UINT64_2PART_C(0xe45c10c4, 2a2b3b06), -210, -44},
+ {UINT64_2PART_C(0xaa242499, 697392d3), -183, -36},
+ {UINT64_2PART_C(0xfd87b5f2, 8300ca0e), -157, -28},
+ {UINT64_2PART_C(0xbce50864, 92111aeb), -130, -20},
+ {UINT64_2PART_C(0x8cbccc09, 6f5088cc), -103, -12},
+ {UINT64_2PART_C(0xd1b71758, e219652c), -77, -4},
+ {UINT64_2PART_C(0x9c400000, 00000000), -50, 4},
+ {UINT64_2PART_C(0xe8d4a510, 00000000), -24, 12},
+ {UINT64_2PART_C(0xad78ebc5, ac620000), 3, 20},
+ {UINT64_2PART_C(0x813f3978, f8940984), 30, 28},
+ {UINT64_2PART_C(0xc097ce7b, c90715b3), 56, 36},
+ {UINT64_2PART_C(0x8f7e32ce, 7bea5c70), 83, 44},
+ {UINT64_2PART_C(0xd5d238a4, abe98068), 109, 52},
+ {UINT64_2PART_C(0x9f4f2726, 179a2245), 136, 60},
+ {UINT64_2PART_C(0xed63a231, d4c4fb27), 162, 68},
+ {UINT64_2PART_C(0xb0de6538, 8cc8ada8), 189, 76},
+ {UINT64_2PART_C(0x83c7088e, 1aab65db), 216, 84},
+ {UINT64_2PART_C(0xc45d1df9, 42711d9a), 242, 92},
+ {UINT64_2PART_C(0x924d692c, a61be758), 269, 100},
+ {UINT64_2PART_C(0xda01ee64, 1a708dea), 295, 108},
+ {UINT64_2PART_C(0xa26da399, 9aef774a), 322, 116},
+ {UINT64_2PART_C(0xf209787b, b47d6b85), 348, 124},
+ {UINT64_2PART_C(0xb454e4a1, 79dd1877), 375, 132},
+ {UINT64_2PART_C(0x865b8692, 5b9bc5c2), 402, 140},
+ {UINT64_2PART_C(0xc83553c5, c8965d3d), 428, 148},
+ {UINT64_2PART_C(0x952ab45c, fa97a0b3), 455, 156},
+ {UINT64_2PART_C(0xde469fbd, 99a05fe3), 481, 164},
+ {UINT64_2PART_C(0xa59bc234, db398c25), 508, 172},
+ {UINT64_2PART_C(0xf6c69a72, a3989f5c), 534, 180},
+ {UINT64_2PART_C(0xb7dcbf53, 54e9bece), 561, 188},
+ {UINT64_2PART_C(0x88fcf317, f22241e2), 588, 196},
+ {UINT64_2PART_C(0xcc20ce9b, d35c78a5), 614, 204},
+ {UINT64_2PART_C(0x98165af3, 7b2153df), 641, 212},
+ {UINT64_2PART_C(0xe2a0b5dc, 971f303a), 667, 220},
+ {UINT64_2PART_C(0xa8d9d153, 5ce3b396), 694, 228},
+ {UINT64_2PART_C(0xfb9b7cd9, a4a7443c), 720, 236},
+ {UINT64_2PART_C(0xbb764c4c, a7a44410), 747, 244},
+ {UINT64_2PART_C(0x8bab8eef, b6409c1a), 774, 252},
+ {UINT64_2PART_C(0xd01fef10, a657842c), 800, 260},
+ {UINT64_2PART_C(0x9b10a4e5, e9913129), 827, 268},
+ {UINT64_2PART_C(0xe7109bfb, a19c0c9d), 853, 276},
+ {UINT64_2PART_C(0xac2820d9, 623bf429), 880, 284},
+ {UINT64_2PART_C(0x80444b5e, 7aa7cf85), 907, 292},
+ {UINT64_2PART_C(0xbf21e440, 03acdd2d), 933, 300},
+ {UINT64_2PART_C(0x8e679c2f, 5e44ff8f), 960, 308},
+ {UINT64_2PART_C(0xd433179d, 9c8cb841), 986, 316},
+ {UINT64_2PART_C(0x9e19db92, b4e31ba9), 1013, 324},
+ {UINT64_2PART_C(0xeb96bf6e, badf77d9), 1039, 332},
+ {UINT64_2PART_C(0xaf87023b, 9bf0ee6b), 1066, 340},
+};
+
+static const int kCachedPowersLength = ARRAY_SIZE(kCachedPowers);
+static const int kCachedPowersOffset = 348; // -1 * the first decimal_exponent.
+static const double kD_1_LOG2_10 = 0.30102999566398114; // 1 / lg(10)
+// Difference between the decimal exponents in the table above.
+const int PowersOfTenCache::kDecimalExponentDistance = 8;
+const int PowersOfTenCache::kMinDecimalExponent = -348;
+const int PowersOfTenCache::kMaxDecimalExponent = 340;
+
+void PowersOfTenCache::GetCachedPowerForBinaryExponentRange(
+ int min_exponent,
+ int max_exponent,
+ DiyFp* power,
+ int* decimal_exponent) {
+ int kQ = DiyFp::kSignificandSize;
+ double k = ceil((min_exponent + kQ - 1) * kD_1_LOG2_10);
+ int foo = kCachedPowersOffset;
+ int index =
+ (foo + static_cast<int>(k) - 1) / kDecimalExponentDistance + 1;
+ ASSERT(0 <= index && index < kCachedPowersLength);
+ CachedPower cached_power = kCachedPowers[index];
+ ASSERT(min_exponent <= cached_power.binary_exponent);
+ ASSERT(cached_power.binary_exponent <= max_exponent);
+ *decimal_exponent = cached_power.decimal_exponent;
+ *power = DiyFp(cached_power.significand, cached_power.binary_exponent);
+}
+
+
+void PowersOfTenCache::GetCachedPowerForDecimalExponent(int requested_exponent,
+ DiyFp* power,
+ int* found_exponent) {
+ ASSERT(kMinDecimalExponent <= requested_exponent);
+ ASSERT(requested_exponent < kMaxDecimalExponent + kDecimalExponentDistance);
+ int index =
+ (requested_exponent + kCachedPowersOffset) / kDecimalExponentDistance;
+ CachedPower cached_power = kCachedPowers[index];
+ *power = DiyFp(cached_power.significand, cached_power.binary_exponent);
+ *found_exponent = cached_power.decimal_exponent;
+ ASSERT(*found_exponent <= requested_exponent);
+ ASSERT(requested_exponent < *found_exponent + kDecimalExponentDistance);
+}
+
+} // namespace double_conversion
diff --git a/mfbt/double-conversion/cached-powers.h b/mfbt/double-conversion/cached-powers.h
new file mode 100644
index 0000000..61a5061
--- /dev/null
+++ b/mfbt/double-conversion/cached-powers.h
@@ -0,0 +1,64 @@
+// Copyright 2010 the V8 project authors. All rights reserved.
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+// * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+// * 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.
+// * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived
+// from this software without specific prior written permission.
+//
+// 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.
+
+#ifndef DOUBLE_CONVERSION_CACHED_POWERS_H_
+#define DOUBLE_CONVERSION_CACHED_POWERS_H_
+
+#include "diy-fp.h"
+
+namespace double_conversion {
+
+class PowersOfTenCache {
+ public:
+
+ // Not all powers of ten are cached. The decimal exponent of two neighboring
+ // cached numbers will differ by kDecimalExponentDistance.
+ static const int kDecimalExponentDistance;
+
+ static const int kMinDecimalExponent;
+ static const int kMaxDecimalExponent;
+
+ // Returns a cached power-of-ten with a binary exponent in the range
+ // [min_exponent; max_exponent] (boundaries included).
+ static void GetCachedPowerForBinaryExponentRange(int min_exponent,
+ int max_exponent,
+ DiyFp* power,
+ int* decimal_exponent);
+
+ // Returns a cached power of ten x ~= 10^k such that
+ // k <= decimal_exponent < k + kCachedPowersDecimalDistance.
+ // The given decimal_exponent must satisfy
+ // kMinDecimalExponent <= requested_exponent, and
+ // requested_exponent < kMaxDecimalExponent + kDecimalExponentDistance.
+ static void GetCachedPowerForDecimalExponent(int requested_exponent,
+ DiyFp* power,
+ int* found_exponent);
+};
+
+} // namespace double_conversion
+
+#endif // DOUBLE_CONVERSION_CACHED_POWERS_H_
diff --git a/mfbt/double-conversion/diy-fp.cc b/mfbt/double-conversion/diy-fp.cc
new file mode 100644
index 0000000..ddd1891
--- /dev/null
+++ b/mfbt/double-conversion/diy-fp.cc
@@ -0,0 +1,57 @@
+// Copyright 2010 the V8 project authors. All rights reserved.
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+// * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+// * 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.
+// * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived
+// from this software without specific prior written permission.
+//
+// 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.
+
+
+#include "diy-fp.h"
+#include "utils.h"
+
+namespace double_conversion {
+
+void DiyFp::Multiply(const DiyFp& other) {
+ // Simply "emulates" a 128 bit multiplication.
+ // However: the resulting number only contains 64 bits. The least
+ // significant 64 bits are only used for rounding the most significant 64
+ // bits.
+ const uint64_t kM32 = 0xFFFFFFFFU;
+ uint64_t a = f_ >> 32;
+ uint64_t b = f_ & kM32;
+ uint64_t c = other.f_ >> 32;
+ uint64_t d = other.f_ & kM32;
+ uint64_t ac = a * c;
+ uint64_t bc = b * c;
+ uint64_t ad = a * d;
+ uint64_t bd = b * d;
+ uint64_t tmp = (bd >> 32) + (ad & kM32) + (bc & kM32);
+ // By adding 1U << 31 to tmp we round the final result.
+ // Halfway cases will be round up.
+ tmp += 1U << 31;
+ uint64_t result_f = ac + (ad >> 32) + (bc >> 32) + (tmp >> 32);
+ e_ += other.e_ + 64;
+ f_ = result_f;
+}
+
+} // namespace double_conversion
diff --git a/mfbt/double-conversion/diy-fp.h b/mfbt/double-conversion/diy-fp.h
new file mode 100644
index 0000000..9dcf8fb
--- /dev/null
+++ b/mfbt/double-conversion/diy-fp.h
@@ -0,0 +1,118 @@
+// Copyright 2010 the V8 project authors. All rights reserved.
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+// * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+// * 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.
+// * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived
+// from this software without specific prior written permission.
+//
+// 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.
+
+#ifndef DOUBLE_CONVERSION_DIY_FP_H_
+#define DOUBLE_CONVERSION_DIY_FP_H_
+
+#include "utils.h"
+
+namespace double_conversion {
+
+// This "Do It Yourself Floating Point" class implements a floating-point number
+// with a uint64 significand and an int exponent. Normalized DiyFp numbers will
+// have the most significant bit of the significand set.
+// Multiplication and Subtraction do not normalize their results.
+// DiyFp are not designed to contain special doubles (NaN and Infinity).
+class DiyFp {
+ public:
+ static const int kSignificandSize = 64;
+
+ DiyFp() : f_(0), e_(0) {}
+ DiyFp(uint64_t f, int e) : f_(f), e_(e) {}
+
+ // this = this - other.
+ // The exponents of both numbers must be the same and the significand of this
+ // must be bigger than the significand of other.
+ // The result will not be normalized.
+ void Subtract(const DiyFp& other) {
+ ASSERT(e_ == other.e_);
+ ASSERT(f_ >= other.f_);
+ f_ -= other.f_;
+ }
+
+ // Returns a - b.
+ // The exponents of both numbers must be the same and this must be bigger
+ // than other. The result will not be normalized.
+ static DiyFp Minus(const DiyFp& a, const DiyFp& b) {
+ DiyFp result = a;
+ result.Subtract(b);
+ return result;
+ }
+
+
+ // this = this * other.
+ void Multiply(const DiyFp& other);
+
+ // returns a * b;
+ static DiyFp Times(const DiyFp& a, const DiyFp& b) {
+ DiyFp result = a;
+ result.Multiply(b);
+ return result;
+ }
+
+ void Normalize() {
+ ASSERT(f_ != 0);
+ uint64_t f = f_;
+ int e = e_;
+
+ // This method is mainly called for normalizing boundaries. In general
+ // boundaries need to be shifted by 10 bits. We thus optimize for this case.
+ const uint64_t k10MSBits = UINT64_2PART_C(0xFFC00000, 00000000);
+ while ((f & k10MSBits) == 0) {
+ f <<= 10;
+ e -= 10;
+ }
+ while ((f & kUint64MSB) == 0) {
+ f <<= 1;
+ e--;
+ }
+ f_ = f;
+ e_ = e;
+ }
+
+ static DiyFp Normalize(const DiyFp& a) {
+ DiyFp result = a;
+ result.Normalize();
+ return result;
+ }
+
+ uint64_t f() const { return f_; }
+ int e() const { return e_; }
+
+ void set_f(uint64_t new_value) { f_ = new_value; }
+ void set_e(int new_value) { e_ = new_value; }
+
+ private:
+ static const uint64_t kUint64MSB = UINT64_2PART_C(0x80000000, 00000000);
+
+ uint64_t f_;
+ int e_;
+};
+
+} // namespace double_conversion
+
+#endif // DOUBLE_CONVERSION_DIY_FP_H_
diff --git a/mfbt/double-conversion/double-conversion.cc b/mfbt/double-conversion/double-conversion.cc
new file mode 100644
index 0000000..a79fe92
--- /dev/null
+++ b/mfbt/double-conversion/double-conversion.cc
@@ -0,0 +1,889 @@
+// Copyright 2010 the V8 project authors. All rights reserved.
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+// * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+// * 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.
+// * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived
+// from this software without specific prior written permission.
+//
+// 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.
+
+#include <limits.h>
+#include <math.h>
+
+#include "double-conversion.h"
+
+#include "bignum-dtoa.h"
+#include "fast-dtoa.h"
+#include "fixed-dtoa.h"
+#include "ieee.h"
+#include "strtod.h"
+#include "utils.h"
+
+namespace double_conversion {
+
+const DoubleToStringConverter& DoubleToStringConverter::EcmaScriptConverter() {
+ int flags = UNIQUE_ZERO | EMIT_POSITIVE_EXPONENT_SIGN;
+ static DoubleToStringConverter converter(flags,
+ "Infinity",
+ "NaN",
+ 'e',
+ -6, 21,
+ 6, 0);
+ return converter;
+}
+
+
+bool DoubleToStringConverter::HandleSpecialValues(
+ double value,
+ StringBuilder* result_builder) const {
+ Double double_inspect(value);
+ if (double_inspect.IsInfinite()) {
+ if (infinity_symbol_ == NULL) return false;
+ if (value < 0) {
+ result_builder->AddCharacter('-');
+ }
+ result_builder->AddString(infinity_symbol_);
+ return true;
+ }
+ if (double_inspect.IsNan()) {
+ if (nan_symbol_ == NULL) return false;
+ result_builder->AddString(nan_symbol_);
+ return true;
+ }
+ return false;
+}
+
+
+void DoubleToStringConverter::CreateExponentialRepresentation(
+ const char* decimal_digits,
+ int length,
+ int exponent,
+ StringBuilder* result_builder) const {
+ ASSERT(length != 0);
+ result_builder->AddCharacter(decimal_digits[0]);
+ if (length != 1) {
+ result_builder->AddCharacter('.');
+ result_builder->AddSubstring(&decimal_digits[1], length-1);
+ }
+ result_builder->AddCharacter(exponent_character_);
+ if (exponent < 0) {
+ result_builder->AddCharacter('-');
+ exponent = -exponent;
+ } else {
+ if ((flags_ & EMIT_POSITIVE_EXPONENT_SIGN) != 0) {
+ result_builder->AddCharacter('+');
+ }
+ }
+ if (exponent == 0) {
+ result_builder->AddCharacter('0');
+ return;
+ }
+ ASSERT(exponent < 1e4);
+ const int kMaxExponentLength = 5;
+ char buffer[kMaxExponentLength + 1];
+ buffer[kMaxExponentLength] = '\0';
+ int first_char_pos = kMaxExponentLength;
+ while (exponent > 0) {
+ buffer[--first_char_pos] = '0' + (exponent % 10);
+ exponent /= 10;
+ }
+ result_builder->AddSubstring(&buffer[first_char_pos],
+ kMaxExponentLength - first_char_pos);
+}
+
+
+void DoubleToStringConverter::CreateDecimalRepresentation(
+ const char* decimal_digits,
+ int length,
+ int decimal_point,
+ int digits_after_point,
+ StringBuilder* result_builder) const {
+ // Create a representation that is padded with zeros if needed.
+ if (decimal_point <= 0) {
+ // "0.00000decimal_rep".
+ result_builder->AddCharacter('0');
+ if (digits_after_point > 0) {
+ result_builder->AddCharacter('.');
+ result_builder->AddPadding('0', -decimal_point);
+ ASSERT(length <= digits_after_point - (-decimal_point));
+ result_builder->AddSubstring(decimal_digits, length);
+ int remaining_digits = digits_after_point - (-decimal_point) - length;
+ result_builder->AddPadding('0', remaining_digits);
+ }
+ } else if (decimal_point >= length) {
+ // "decimal_rep0000.00000" or "decimal_rep.0000"
+ result_builder->AddSubstring(decimal_digits, length);
+ result_builder->AddPadding('0', decimal_point - length);
+ if (digits_after_point > 0) {
+ result_builder->AddCharacter('.');
+ result_builder->AddPadding('0', digits_after_point);
+ }
+ } else {
+ // "decima.l_rep000"
+ ASSERT(digits_after_point > 0);
+ result_builder->AddSubstring(decimal_digits, decimal_point);
+ result_builder->AddCharacter('.');
+ ASSERT(length - decimal_point <= digits_after_point);
+ result_builder->AddSubstring(&decimal_digits[decimal_point],
+ length - decimal_point);
+ int remaining_digits = digits_after_point - (length - decimal_point);
+ result_builder->AddPadding('0', remaining_digits);
+ }
+ if (digits_after_point == 0) {
+ if ((flags_ & EMIT_TRAILING_DECIMAL_POINT) != 0) {
+ result_builder->AddCharacter('.');
+ }
+ if ((flags_ & EMIT_TRAILING_ZERO_AFTER_POINT) != 0) {
+ result_builder->AddCharacter('0');
+ }
+ }
+}
+
+
+bool DoubleToStringConverter::ToShortestIeeeNumber(
+ double value,
+ StringBuilder* result_builder,
+ DoubleToStringConverter::DtoaMode mode) const {
+ ASSERT(mode == SHORTEST || mode == SHORTEST_SINGLE);
+ if (Double(value).IsSpecial()) {
+ return HandleSpecialValues(value, result_builder);
+ }
+
+ int decimal_point;
+ bool sign;
+ const int kDecimalRepCapacity = kBase10MaximalLength + 1;
+ char decimal_rep[kDecimalRepCapacity];
+ int decimal_rep_length;
+
+ DoubleToAscii(value, mode, 0, decimal_rep, kDecimalRepCapacity,
+ &sign, &decimal_rep_length, &decimal_point);
+
+ bool unique_zero = (flags_ & UNIQUE_ZERO) != 0;
+ if (sign && (value != 0.0 || !unique_zero)) {
+ result_builder->AddCharacter('-');
+ }
+
+ int exponent = decimal_point - 1;
+ if ((decimal_in_shortest_low_ <= exponent) &&
+ (exponent < decimal_in_shortest_high_)) {
+ CreateDecimalRepresentation(decimal_rep, decimal_rep_length,
+ decimal_point,
+ Max(0, decimal_rep_length - decimal_point),
+ result_builder);
+ } else {
+ CreateExponentialRepresentation(decimal_rep, decimal_rep_length, exponent,
+ result_builder);
+ }
+ return true;
+}
+
+
+bool DoubleToStringConverter::ToFixed(double value,
+ int requested_digits,
+ StringBuilder* result_builder) const {
+ ASSERT(kMaxFixedDigitsBeforePoint == 60);
+ const double kFirstNonFixed = 1e60;
+
+ if (Double(value).IsSpecial()) {
+ return HandleSpecialValues(value, result_builder);
+ }
+
+ if (requested_digits > kMaxFixedDigitsAfterPoint) return false;
+ if (value >= kFirstNonFixed || value <= -kFirstNonFixed) return false;
+
+ // Find a sufficiently precise decimal representation of n.
+ int decimal_point;
+ bool sign;
+ // Add space for the '\0' byte.
+ const int kDecimalRepCapacity =
+ kMaxFixedDigitsBeforePoint + kMaxFixedDigitsAfterPoint + 1;
+ char decimal_rep[kDecimalRepCapacity];
+ int decimal_rep_length;
+ DoubleToAscii(value, FIXED, requested_digits,
+ decimal_rep, kDecimalRepCapacity,
+ &sign, &decimal_rep_length, &decimal_point);
+
+ bool unique_zero = ((flags_ & UNIQUE_ZERO) != 0);
+ if (sign && (value != 0.0 || !unique_zero)) {
+ result_builder->AddCharacter('-');
+ }
+
+ CreateDecimalRepresentation(decimal_rep, decimal_rep_length, decimal_point,
+ requested_digits, result_builder);
+ return true;
+}
+
+
+bool DoubleToStringConverter::ToExponential(
+ double value,
+ int requested_digits,
+ StringBuilder* result_builder) const {
+ if (Double(value).IsSpecial()) {
+ return HandleSpecialValues(value, result_builder);
+ }
+
+ if (requested_digits < -1) return false;
+ if (requested_digits > kMaxExponentialDigits) return false;
+
+ int decimal_point;
+ bool sign;
+ // Add space for digit before the decimal point and the '\0' character.
+ const int kDecimalRepCapacity = kMaxExponentialDigits + 2;
+ ASSERT(kDecimalRepCapacity > kBase10MaximalLength);
+ char decimal_rep[kDecimalRepCapacity];
+ int decimal_rep_length;
+
+ if (requested_digits == -1) {
+ DoubleToAscii(value, SHORTEST, 0,
+ decimal_rep, kDecimalRepCapacity,
+ &sign, &decimal_rep_length, &decimal_point);
+ } else {
+ DoubleToAscii(value, PRECISION, requested_digits + 1,
+ decimal_rep, kDecimalRepCapacity,
+ &sign, &decimal_rep_length, &decimal_point);
+ ASSERT(decimal_rep_length <= requested_digits + 1);
+
+ for (int i = decimal_rep_length; i < requested_digits + 1; ++i) {
+ decimal_rep[i] = '0';
+ }
+ decimal_rep_length = requested_digits + 1;
+ }
+
+ bool unique_zero = ((flags_ & UNIQUE_ZERO) != 0);
+ if (sign && (value != 0.0 || !unique_zero)) {
+ result_builder->AddCharacter('-');
+ }
+
+ int exponent = decimal_point - 1;
+ CreateExponentialRepresentation(decimal_rep,
+ decimal_rep_length,
+ exponent,
+ result_builder);
+ return true;
+}
+
+
+bool DoubleToStringConverter::ToPrecision(double value,
+ int precision,
+ StringBuilder* result_builder) const {
+ if (Double(value).IsSpecial()) {
+ return HandleSpecialValues(value, result_builder);
+ }
+
+ if (precision < kMinPrecisionDigits || precision > kMaxPrecisionDigits) {
+ return false;
+ }
+
+ // Find a sufficiently precise decimal representation of n.
+ int decimal_point;
+ bool sign;
+ // Add one for the terminating null character.
+ const int kDecimalRepCapacity = kMaxPrecisionDigits + 1;
+ char decimal_rep[kDecimalRepCapacity];
+ int decimal_rep_length;
+
+ DoubleToAscii(value, PRECISION, precision,
+ decimal_rep, kDecimalRepCapacity,
+ &sign, &decimal_rep_length, &decimal_point);
+ ASSERT(decimal_rep_length <= precision);
+
+ bool unique_zero = ((flags_ & UNIQUE_ZERO) != 0);
+ if (sign && (value != 0.0 || !unique_zero)) {
+ result_builder->AddCharacter('-');
+ }
+
+ // The exponent if we print the number as x.xxeyyy. That is with the
+ // decimal point after the first digit.
+ int exponent = decimal_point - 1;
+
+ int extra_zero = ((flags_ & EMIT_TRAILING_ZERO_AFTER_POINT) != 0) ? 1 : 0;
+ if ((-decimal_point + 1 > max_leading_padding_zeroes_in_precision_mode_) ||
+ (decimal_point - precision + extra_zero >
+ max_trailing_padding_zeroes_in_precision_mode_)) {
+ // Fill buffer to contain 'precision' digits.
+ // Usually the buffer is already at the correct length, but 'DoubleToAscii'
+ // is allowed to return less characters.
+ for (int i = decimal_rep_length; i < precision; ++i) {
+ decimal_rep[i] = '0';
+ }
+
+ CreateExponentialRepresentation(decimal_rep,
+ precision,
+ exponent,
+ result_builder);
+ } else {
+ CreateDecimalRepresentation(decimal_rep, decimal_rep_length, decimal_point,
+ Max(0, precision - decimal_point),
+ result_builder);
+ }
+ return true;
+}
+
+
+static BignumDtoaMode DtoaToBignumDtoaMode(
+ DoubleToStringConverter::DtoaMode dtoa_mode) {
+ switch (dtoa_mode) {
+ case DoubleToStringConverter::SHORTEST: return BIGNUM_DTOA_SHORTEST;
+ case DoubleToStringConverter::SHORTEST_SINGLE:
+ return BIGNUM_DTOA_SHORTEST_SINGLE;
+ case DoubleToStringConverter::FIXED: return BIGNUM_DTOA_FIXED;
+ case DoubleToStringConverter::PRECISION: return BIGNUM_DTOA_PRECISION;
+ default:
+ UNREACHABLE();
+ return BIGNUM_DTOA_SHORTEST; // To silence compiler.
+ }
+}
+
+
+void DoubleToStringConverter::DoubleToAscii(double v,
+ DtoaMode mode,
+ int requested_digits,
+ char* buffer,
+ int buffer_length,
+ bool* sign,
+ int* length,
+ int* point) {
+ Vector<char> vector(buffer, buffer_length);
+ ASSERT(!Double(v).IsSpecial());
+ ASSERT(mode == SHORTEST || mode == SHORTEST_SINGLE || requested_digits >= 0);
+
+ if (Double(v).Sign() < 0) {
+ *sign = true;
+ v = -v;
+ } else {
+ *sign = false;
+ }
+
+ if (mode == PRECISION && requested_digits == 0) {
+ vector[0] = '\0';
+ *length = 0;
+ return;
+ }
+
+ if (v == 0) {
+ vector[0] = '0';
+ vector[1] = '\0';
+ *length = 1;
+ *point = 1;
+ return;
+ }
+
+ bool fast_worked;
+ switch (mode) {
+ case SHORTEST:
+ fast_worked = FastDtoa(v, FAST_DTOA_SHORTEST, 0, vector, length, point);
+ break;
+ case SHORTEST_SINGLE:
+ fast_worked = FastDtoa(v, FAST_DTOA_SHORTEST_SINGLE, 0,
+ vector, length, point);
+ break;
+ case FIXED:
+ fast_worked = FastFixedDtoa(v, requested_digits, vector, length, point);
+ break;
+ case PRECISION:
+ fast_worked = FastDtoa(v, FAST_DTOA_PRECISION, requested_digits,
+ vector, length, point);
+ break;
+ default:
+ UNREACHABLE();
+ fast_worked = false;
+ }
+ if (fast_worked) return;
+
+ // If the fast dtoa didn't succeed use the slower bignum version.
+ BignumDtoaMode bignum_mode = DtoaToBignumDtoaMode(mode);
+ BignumDtoa(v, bignum_mode, requested_digits, vector, length, point);
+ vector[*length] = '\0';
+}
+
+
+// Consumes the given substring from the iterator.
+// Returns false, if the substring does not match.
+static bool ConsumeSubString(const char** current,
+ const char* end,
+ const char* substring) {
+ ASSERT(**current == *substring);
+ for (substring++; *substring != '\0'; substring++) {
+ ++*current;
+ if (*current == end || **current != *substring) return false;
+ }
+ ++*current;
+ return true;
+}
+
+
+// Maximum number of significant digits in decimal representation.
+// The longest possible double in decimal representation is
+// (2^53 - 1) * 2 ^ -1074 that is (2 ^ 53 - 1) * 5 ^ 1074 / 10 ^ 1074
+// (768 digits). If we parse a number whose first digits are equal to a
+// mean of 2 adjacent doubles (that could have up to 769 digits) the result
+// must be rounded to the bigger one unless the tail consists of zeros, so
+// we don't need to preserve all the digits.
+const int kMaxSignificantDigits = 772;
+
+
+// Returns true if a nonspace found and false if the end has reached.
+static inline bool AdvanceToNonspace(const char** current, const char* end) {
+ while (*current != end) {
+ if (**current != ' ') return true;
+ ++*current;
+ }
+ return false;
+}
+
+
+static bool isDigit(int x, int radix) {
+ return (x >= '0' && x <= '9' && x < '0' + radix)
+ || (radix > 10 && x >= 'a' && x < 'a' + radix - 10)
+ || (radix > 10 && x >= 'A' && x < 'A' + radix - 10);
+}
+
+
+static double SignedZero(bool sign) {
+ return sign ? -0.0 : 0.0;
+}
+
+
+// Parsing integers with radix 2, 4, 8, 16, 32. Assumes current != end.
+template <int radix_log_2>
+static double RadixStringToIeee(const char* current,
+ const char* end,
+ bool sign,
+ bool allow_trailing_junk,
+ double junk_string_value,
+ bool read_as_double,
+ const char** trailing_pointer) {
+ ASSERT(current != end);
+
+ const int kDoubleSize = Double::kSignificandSize;
+ const int kSingleSize = Single::kSignificandSize;
+ const int kSignificandSize = read_as_double? kDoubleSize: kSingleSize;
+
+ // Skip leading 0s.
+ while (*current == '0') {
+ ++current;
+ if (current == end) {
+ *trailing_pointer = end;
+ return SignedZero(sign);
+ }
+ }
+
+ int64_t number = 0;
+ int exponent = 0;
+ const int radix = (1 << radix_log_2);
+
+ do {
+ int digit;
+ if (*current >= '0' && *current <= '9' && *current < '0' + radix) {
+ digit = static_cast<char>(*current) - '0';
+ } else if (radix > 10 && *current >= 'a' && *current < 'a' + radix - 10) {
+ digit = static_cast<char>(*current) - 'a' + 10;
+ } else if (radix > 10 && *current >= 'A' && *current < 'A' + radix - 10) {
+ digit = static_cast<char>(*current) - 'A' + 10;
+ } else {
+ if (allow_trailing_junk || !AdvanceToNonspace(&current, end)) {
+ break;
+ } else {
+ return junk_string_value;
+ }
+ }
+
+ number = number * radix + digit;
+ int overflow = static_cast<int>(number >> kSignificandSize);
+ if (overflow != 0) {
+ // Overflow occurred. Need to determine which direction to round the
+ // result.
+ int overflow_bits_count = 1;
+ while (overflow > 1) {
+ overflow_bits_count++;
+ overflow >>= 1;
+ }
+
+ int dropped_bits_mask = ((1 << overflow_bits_count) - 1);
+ int dropped_bits = static_cast<int>(number) & dropped_bits_mask;
+ number >>= overflow_bits_count;
+ exponent = overflow_bits_count;
+
+ bool zero_tail = true;
+ while (true) {
+ ++current;
+ if (current == end || !isDigit(*current, radix)) break;
+ zero_tail = zero_tail && *current == '0';
+ exponent += radix_log_2;
+ }
+
+ if (!allow_trailing_junk && AdvanceToNonspace(&current, end)) {
+ return junk_string_value;
+ }
+
+ int middle_value = (1 << (overflow_bits_count - 1));
+ if (dropped_bits > middle_value) {
+ number++; // Rounding up.
+ } else if (dropped_bits == middle_value) {
+ // Rounding to even to consistency with decimals: half-way case rounds
+ // up if significant part is odd and down otherwise.
+ if ((number & 1) != 0 || !zero_tail) {
+ number++; // Rounding up.
+ }
+ }
+
+ // Rounding up may cause overflow.
+ if ((number & ((int64_t)1 << kSignificandSize)) != 0) {
+ exponent++;
+ number >>= 1;
+ }
+ break;
+ }
+ ++current;
+ } while (current != end);
+
+ ASSERT(number < ((int64_t)1 << kSignificandSize));
+ ASSERT(static_cast<int64_t>(static_cast<double>(number)) == number);
+
+ *trailing_pointer = current;
+
+ if (exponent == 0) {
+ if (sign) {
+ if (number == 0) return -0.0;
+ number = -number;
+ }
+ return static_cast<double>(number);
+ }
+
+ ASSERT(number != 0);
+ return Double(DiyFp(number, exponent)).value();
+}
+
+
+double StringToDoubleConverter::StringToIeee(
+ const char* input,
+ int length,
+ int* processed_characters_count,
+ bool read_as_double) {
+ const char* current = input;
+ const char* end = input + length;
+
+ *processed_characters_count = 0;
+
+ const bool allow_trailing_junk = (flags_ & ALLOW_TRAILING_JUNK) != 0;
+ const bool allow_leading_spaces = (flags_ & ALLOW_LEADING_SPACES) != 0;
+ const bool allow_trailing_spaces = (flags_ & ALLOW_TRAILING_SPACES) != 0;
+ const bool allow_spaces_after_sign = (flags_ & ALLOW_SPACES_AFTER_SIGN) != 0;
+
+ // To make sure that iterator dereferencing is valid the following
+ // convention is used:
+ // 1. Each '++current' statement is followed by check for equality to 'end'.
+ // 2. If AdvanceToNonspace returned false then current == end.
+ // 3. If 'current' becomes equal to 'end' the function returns or goes to
+ // 'parsing_done'.
+ // 4. 'current' is not dereferenced after the 'parsing_done' label.
+ // 5. Code before 'parsing_done' may rely on 'current != end'.
+ if (current == end) return empty_string_value_;
+
+ if (allow_leading_spaces || allow_trailing_spaces) {
+ if (!AdvanceToNonspace(&current, end)) {
+ *processed_characters_count = current - input;
+ return empty_string_value_;
+ }
+ if (!allow_leading_spaces && (input != current)) {
+ // No leading spaces allowed, but AdvanceToNonspace moved forward.
+ return junk_string_value_;
+ }
+ }
+
+ // The longest form of simplified number is: "-<significant digits>.1eXXX\0".
+ const int kBufferSize = kMaxSignificantDigits + 10;
+ char buffer[kBufferSize]; // NOLINT: size is known at compile time.
+ int buffer_pos = 0;
+
+ // Exponent will be adjusted if insignificant digits of the integer part
+ // or insignificant leading zeros of the fractional part are dropped.
+ int exponent = 0;
+ int significant_digits = 0;
+ int insignificant_digits = 0;
+ bool nonzero_digit_dropped = false;
+
+ bool sign = false;
+
+ if (*current == '+' || *current == '-') {
+ sign = (*current == '-');
+ ++current;
+ const char* next_non_space = current;
+ // Skip following spaces (if allowed).
+ if (!AdvanceToNonspace(&next_non_space, end)) return junk_string_value_;
+ if (!allow_spaces_after_sign && (current != next_non_space)) {
+ return junk_string_value_;
+ }
+ current = next_non_space;
+ }
+
+ if (infinity_symbol_ != NULL) {
+ if (*current == infinity_symbol_[0]) {
+ if (!ConsumeSubString(&current, end, infinity_symbol_)) {
+ return junk_string_value_;
+ }
+
+ if (!(allow_trailing_spaces || allow_trailing_junk) && (current != end)) {
+ return junk_string_value_;
+ }
+ if (!allow_trailing_junk && AdvanceToNonspace(&current, end)) {
+ return junk_string_value_;
+ }
+
+ ASSERT(buffer_pos == 0);
+ *processed_characters_count = current - input;
+ return sign ? -Double::Infinity() : Double::Infinity();
+ }
+ }
+
+ if (nan_symbol_ != NULL) {
+ if (*current == nan_symbol_[0]) {
+ if (!ConsumeSubString(&current, end, nan_symbol_)) {
+ return junk_string_value_;
+ }
+
+ if (!(allow_trailing_spaces || allow_trailing_junk) && (current != end)) {
+ return junk_string_value_;
+ }
+ if (!allow_trailing_junk && AdvanceToNonspace(&current, end)) {
+ return junk_string_value_;
+ }
+
+ ASSERT(buffer_pos == 0);
+ *processed_characters_count = current - input;
+ return sign ? -Double::NaN() : Double::NaN();
+ }
+ }
+
+ bool leading_zero = false;
+ if (*current == '0') {
+ ++current;
+ if (current == end) {
+ *processed_characters_count = current - input;
+ return SignedZero(sign);
+ }
+
+ leading_zero = true;
+
+ // It could be hexadecimal value.
+ if ((flags_ & ALLOW_HEX) && (*current == 'x' || *current == 'X')) {
+ ++current;
+ if (current == end || !isDigit(*current, 16)) {
+ return junk_string_value_; // "0x".
+ }
+
+ const char* tail_pointer = NULL;
+ double result = RadixStringToIeee<4>(current,
+ end,
+ sign,
+ allow_trailing_junk,
+ junk_string_value_,
+ read_as_double,
+ &tail_pointer);
+ if (tail_pointer != NULL) {
+ if (allow_trailing_spaces) AdvanceToNonspace(&tail_pointer, end);
+ *processed_characters_count = tail_pointer - input;
+ }
+ return result;
+ }
+
+ // Ignore leading zeros in the integer part.
+ while (*current == '0') {
+ ++current;
+ if (current == end) {
+ *processed_characters_count = current - input;
+ return SignedZero(sign);
+ }
+ }
+ }
+
+ bool octal = leading_zero && (flags_ & ALLOW_OCTALS) != 0;
+
+ // Copy significant digits of the integer part (if any) to the buffer.
+ while (*current >= '0' && *current <= '9') {
+ if (significant_digits < kMaxSignificantDigits) {
+ ASSERT(buffer_pos < kBufferSize);
+ buffer[buffer_pos++] = static_cast<char>(*current);
+ significant_digits++;
+ // Will later check if it's an octal in the buffer.
+ } else {
+ insignificant_digits++; // Move the digit into the exponential part.
+ nonzero_digit_dropped = nonzero_digit_dropped || *current != '0';
+ }
+ octal = octal && *current < '8';
+ ++current;
+ if (current == end) goto parsing_done;
+ }
+
+ if (significant_digits == 0) {
+ octal = false;
+ }
+
+ if (*current == '.') {
+ if (octal && !allow_trailing_junk) return junk_string_value_;
+ if (octal) goto parsing_done;
+
+ ++current;
+ if (current == end) {
+ if (significant_digits == 0 && !leading_zero) {
+ return junk_string_value_;
+ } else {
+ goto parsing_done;
+ }
+ }
+
+ if (significant_digits == 0) {
+ // octal = false;
+ // Integer part consists of 0 or is absent. Significant digits start after
+ // leading zeros (if any).
+ while (*current == '0') {
+ ++current;
+ if (current == end) {
+ *processed_characters_count = current - input;
+ return SignedZero(sign);
+ }
+ exponent--; // Move this 0 into the exponent.
+ }
+ }
+
+ // There is a fractional part.
+ // We don't emit a '.', but adjust the exponent instead.
+ while (*current >= '0' && *current <= '9') {
+ if (significant_digits < kMaxSignificantDigits) {
+ ASSERT(buffer_pos < kBufferSize);
+ buffer[buffer_pos++] = static_cast<char>(*current);
+ significant_digits++;
+ exponent--;
+ } else {
+ // Ignore insignificant digits in the fractional part.
+ nonzero_digit_dropped = nonzero_digit_dropped || *current != '0';
+ }
+ ++current;
+ if (current == end) goto parsing_done;
+ }
+ }
+
+ if (!leading_zero && exponent == 0 && significant_digits == 0) {
+ // If leading_zeros is true then the string contains zeros.
+ // If exponent < 0 then string was [+-]\.0*...
+ // If significant_digits != 0 the string is not equal to 0.
+ // Otherwise there are no digits in the string.
+ return junk_string_value_;
+ }
+
+ // Parse exponential part.
+ if (*current == 'e' || *current == 'E') {
+ if (octal && !allow_trailing_junk) return junk_string_value_;
+ if (octal) goto parsing_done;
+ ++current;
+ if (current == end) {
+ if (allow_trailing_junk) {
+ goto parsing_done;
+ } else {
+ return junk_string_value_;
+ }
+ }
+ char sign = '+';
+ if (*current == '+' || *current == '-') {
+ sign = static_cast<char>(*current);
+ ++current;
+ if (current == end) {
+ if (allow_trailing_junk) {
+ goto parsing_done;
+ } else {
+ return junk_string_value_;
+ }
+ }
+ }
+
+ if (current == end || *current < '0' || *current > '9') {
+ if (allow_trailing_junk) {
+ goto parsing_done;
+ } else {
+ return junk_string_value_;
+ }
+ }
+
+ const int max_exponent = INT_MAX / 2;
+ ASSERT(-max_exponent / 2 <= exponent && exponent <= max_exponent / 2);
+ int num = 0;
+ do {
+ // Check overflow.
+ int digit = *current - '0';
+ if (num >= max_exponent / 10
+ && !(num == max_exponent / 10 && digit <= max_exponent % 10)) {
+ num = max_exponent;
+ } else {
+ num = num * 10 + digit;
+ }
+ ++current;
+ } while (current != end && *current >= '0' && *current <= '9');
+
+ exponent += (sign == '-' ? -num : num);
+ }
+
+ if (!(allow_trailing_spaces || allow_trailing_junk) && (current != end)) {
+ return junk_string_value_;
+ }
+ if (!allow_trailing_junk && AdvanceToNonspace(&current, end)) {
+ return junk_string_value_;
+ }
+ if (allow_trailing_spaces) {
+ AdvanceToNonspace(&current, end);
+ }
+
+ parsing_done:
+ exponent += insignificant_digits;
+
+ if (octal) {
+ double result;
+ const char* tail_pointer = NULL;
+ result = RadixStringToIeee<3>(buffer,
+ buffer + buffer_pos,
+ sign,
+ allow_trailing_junk,
+ junk_string_value_,
+ read_as_double,
+ &tail_pointer);
+ ASSERT(tail_pointer != NULL);
+ *processed_characters_count = current - input;
+ return result;
+ }
+
+ if (nonzero_digit_dropped) {
+ buffer[buffer_pos++] = '1';
+ exponent--;
+ }
+
+ ASSERT(buffer_pos < kBufferSize);
+ buffer[buffer_pos] = '\0';
+
+ double converted;
+ if (read_as_double) {
+ converted = Strtod(Vector<const char>(buffer, buffer_pos), exponent);
+ } else {
+ converted = Strtof(Vector<const char>(buffer, buffer_pos), exponent);
+ }
+ *processed_characters_count = current - input;
+ return sign? -converted: converted;
+}
+
+} // namespace double_conversion
diff --git a/mfbt/double-conversion/double-conversion.h b/mfbt/double-conversion/double-conversion.h
new file mode 100644
index 0000000..c62b16b
--- /dev/null
+++ b/mfbt/double-conversion/double-conversion.h
@@ -0,0 +1,537 @@
+// Copyright 2012 the V8 project authors. All rights reserved.
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+// * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+// * 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.
+// * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived
+// from this software without specific prior written permission.
+//
+// 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.
+
+#ifndef DOUBLE_CONVERSION_DOUBLE_CONVERSION_H_
+#define DOUBLE_CONVERSION_DOUBLE_CONVERSION_H_
+
+#include "mozilla/Types.h"
+#include "utils.h"
+
+namespace double_conversion {
+
+class DoubleToStringConverter {
+ public:
+ // When calling ToFixed with a double > 10^kMaxFixedDigitsBeforePoint
+ // or a requested_digits parameter > kMaxFixedDigitsAfterPoint then the
+ // function returns false.
+ static const int kMaxFixedDigitsBeforePoint = 60;
+ static const int kMaxFixedDigitsAfterPoint = 60;
+
+ // When calling ToExponential with a requested_digits
+ // parameter > kMaxExponentialDigits then the function returns false.
+ static const int kMaxExponentialDigits = 120;
+
+ // When calling ToPrecision with a requested_digits
+ // parameter < kMinPrecisionDigits or requested_digits > kMaxPrecisionDigits
+ // then the function returns false.
+ static const int kMinPrecisionDigits = 1;
+ static const int kMaxPrecisionDigits = 120;
+
+ enum Flags {
+ NO_FLAGS = 0,
+ EMIT_POSITIVE_EXPONENT_SIGN = 1,
+ EMIT_TRAILING_DECIMAL_POINT = 2,
+ EMIT_TRAILING_ZERO_AFTER_POINT = 4,
+ UNIQUE_ZERO = 8
+ };
+
+ // Flags should be a bit-or combination of the possible Flags-enum.
+ // - NO_FLAGS: no special flags.
+ // - EMIT_POSITIVE_EXPONENT_SIGN: when the number is converted into exponent
+ // form, emits a '+' for positive exponents. Example: 1.2e+2.
+ // - EMIT_TRAILING_DECIMAL_POINT: when the input number is an integer and is
+ // converted into decimal format then a trailing decimal point is appended.
+ // Example: 2345.0 is converted to "2345.".
+ // - EMIT_TRAILING_ZERO_AFTER_POINT: in addition to a trailing decimal point
+ // emits a trailing '0'-character. This flag requires the
+ // EXMIT_TRAILING_DECIMAL_POINT flag.
+ // Example: 2345.0 is converted to "2345.0".
+ // - UNIQUE_ZERO: "-0.0" is converted to "0.0".
+ //
+ // Infinity symbol and nan_symbol provide the string representation for these
+ // special values. If the string is NULL and the special value is encountered
+ // then the conversion functions return false.
+ //
+ // The exponent_character is used in exponential representations. It is
+ // usually 'e' or 'E'.
+ //
+ // When converting to the shortest representation the converter will
+ // represent input numbers in decimal format if they are in the interval
+ // [10^decimal_in_shortest_low; 10^decimal_in_shortest_high[
+ // (lower boundary included, greater boundary excluded).
+ // Example: with decimal_in_shortest_low = -6 and
+ // decimal_in_shortest_high = 21:
+ // ToShortest(0.000001) -> "0.000001"
+ // ToShortest(0.0000001) -> "1e-7"
+ // ToShortest(111111111111111111111.0) -> "111111111111111110000"
+ // ToShortest(100000000000000000000.0) -> "100000000000000000000"
+ // ToShortest(1111111111111111111111.0) -> "1.1111111111111111e+21"
+ //
+ // When converting to precision mode the converter may add
+ // max_leading_padding_zeroes before returning the number in exponential
+ // format.
+ // Example with max_leading_padding_zeroes_in_precision_mode = 6.
+ // ToPrecision(0.0000012345, 2) -> "0.0000012"
+ // ToPrecision(0.00000012345, 2) -> "1.2e-7"
+ // Similarily the converter may add up to
+ // max_trailing_padding_zeroes_in_precision_mode in precision mode to avoid
+ // returning an exponential representation. A zero added by the
+ // EMIT_TRAILING_ZERO_AFTER_POINT flag is counted for this limit.
+ // Examples for max_trailing_padding_zeroes_in_precision_mode = 1:
+ // ToPrecision(230.0, 2) -> "230"
+ // ToPrecision(230.0, 2) -> "230." with EMIT_TRAILING_DECIMAL_POINT.
+ // ToPrecision(230.0, 2) -> "2.3e2" with EMIT_TRAILING_ZERO_AFTER_POINT.
+ DoubleToStringConverter(int flags,
+ const char* infinity_symbol,
+ const char* nan_symbol,
+ char exponent_character,
+ int decimal_in_shortest_low,
+ int decimal_in_shortest_high,
+ int max_leading_padding_zeroes_in_precision_mode,
+ int max_trailing_padding_zeroes_in_precision_mode)
+ : flags_(flags),
+ infinity_symbol_(infinity_symbol),
+ nan_symbol_(nan_symbol),
+ exponent_character_(exponent_character),
+ decimal_in_shortest_low_(decimal_in_shortest_low),
+ decimal_in_shortest_high_(decimal_in_shortest_high),
+ max_leading_padding_zeroes_in_precision_mode_(
+ max_leading_padding_zeroes_in_precision_mode),
+ max_trailing_padding_zeroes_in_precision_mode_(
+ max_trailing_padding_zeroes_in_precision_mode) {
+ // When 'trailing zero after the point' is set, then 'trailing point'
+ // must be set too.
+ ASSERT(((flags & EMIT_TRAILING_DECIMAL_POINT) != 0) ||
+ !((flags & EMIT_TRAILING_ZERO_AFTER_POINT) != 0));
+ }
+
+ // Returns a converter following the EcmaScript specification.
+ static MFBT_API const DoubleToStringConverter& EcmaScriptConverter();
+
+ // Computes the shortest string of digits that correctly represent the input
+ // number. Depending on decimal_in_shortest_low and decimal_in_shortest_high
+ // (see constructor) it then either returns a decimal representation, or an
+ // exponential representation.
+ // Example with decimal_in_shortest_low = -6,
+ // decimal_in_shortest_high = 21,
+ // EMIT_POSITIVE_EXPONENT_SIGN activated, and
+ // EMIT_TRAILING_DECIMAL_POINT deactived:
+ // ToShortest(0.000001) -> "0.000001"
+ // ToShortest(0.0000001) -> "1e-7"
+ // ToShortest(111111111111111111111.0) -> "111111111111111110000"
+ // ToShortest(100000000000000000000.0) -> "100000000000000000000"
+ // ToShortest(1111111111111111111111.0) -> "1.1111111111111111e+21"
+ //
+ // Note: the conversion may round the output if the returned string
+ // is accurate enough to uniquely identify the input-number.
+ // For example the most precise representation of the double 9e59 equals
+ // "899999999999999918767229449717619953810131273674690656206848", but
+ // the converter will return the shorter (but still correct) "9e59".
+ //
+ // Returns true if the conversion succeeds. The conversion always succeeds
+ // except when the input value is special and no infinity_symbol or
+ // nan_symbol has been given to the constructor.
+ bool ToShortest(double value, StringBuilder* result_builder) const {
+ return ToShortestIeeeNumber(value, result_builder, SHORTEST);
+ }
+
+ // Same as ToShortest, but for single-precision floats.
+ bool ToShortestSingle(float value, StringBuilder* result_builder) const {
+ return ToShortestIeeeNumber(value, result_builder, SHORTEST_SINGLE);
+ }
+
+
+ // Computes a decimal representation with a fixed number of digits after the
+ // decimal point. The last emitted digit is rounded.
+ //
+ // Examples:
+ // ToFixed(3.12, 1) -> "3.1"
+ // ToFixed(3.1415, 3) -> "3.142"
+ // ToFixed(1234.56789, 4) -> "1234.5679"
+ // ToFixed(1.23, 5) -> "1.23000"
+ // ToFixed(0.1, 4) -> "0.1000"
+ // ToFixed(1e30, 2) -> "1000000000000000019884624838656.00"
+ // ToFixed(0.1, 30) -> "0.100000000000000005551115123126"
+ // ToFixed(0.1, 17) -> "0.10000000000000001"
+ //
+ // If requested_digits equals 0, then the tail of the result depends on
+ // the EMIT_TRAILING_DECIMAL_POINT and EMIT_TRAILING_ZERO_AFTER_POINT.
+ // Examples, for requested_digits == 0,
+ // let EMIT_TRAILING_DECIMAL_POINT and EMIT_TRAILING_ZERO_AFTER_POINT be
+ // - false and false: then 123.45 -> 123
+ // 0.678 -> 1
+ // - true and false: then 123.45 -> 123.
+ // 0.678 -> 1.
+ // - true and true: then 123.45 -> 123.0
+ // 0.678 -> 1.0
+ //
+ // Returns true if the conversion succeeds. The conversion always succeeds
+ // except for the following cases:
+ // - the input value is special and no infinity_symbol or nan_symbol has
+ // been provided to the constructor,
+ // - 'value' > 10^kMaxFixedDigitsBeforePoint, or
+ // - 'requested_digits' > kMaxFixedDigitsAfterPoint.
+ // The last two conditions imply that the result will never contain more than
+ // 1 + kMaxFixedDigitsBeforePoint + 1 + kMaxFixedDigitsAfterPoint characters
+ // (one additional character for the sign, and one for the decimal point).
+ MFBT_API bool ToFixed(double value,
+ int requested_digits,
+ StringBuilder* result_builder) const;
+
+ // Computes a representation in exponential format with requested_digits
+ // after the decimal point. The last emitted digit is rounded.
+ // If requested_digits equals -1, then the shortest exponential representation
+ // is computed.
+ //
+ // Examples with EMIT_POSITIVE_EXPONENT_SIGN deactivated, and
+ // exponent_character set to 'e'.
+ // ToExponential(3.12, 1) -> "3.1e0"
+ // ToExponential(5.0, 3) -> "5.000e0"
+ // ToExponential(0.001, 2) -> "1.00e-3"
+ // ToExponential(3.1415, -1) -> "3.1415e0"
+ // ToExponential(3.1415, 4) -> "3.1415e0"
+ // ToExponential(3.1415, 3) -> "3.142e0"
+ // ToExponential(123456789000000, 3) -> "1.235e14"
+ // ToExponential(1000000000000000019884624838656.0, -1) -> "1e30"
+ // ToExponential(1000000000000000019884624838656.0, 32) ->
+ // "1.00000000000000001988462483865600e30"
+ // ToExponential(1234, 0) -> "1e3"
+ //
+ // Returns true if the conversion succeeds. The conversion always succeeds
+ // except for the following cases:
+ // - the input value is special and no infinity_symbol or nan_symbol has
+ // been provided to the constructor,
+ // - 'requested_digits' > kMaxExponentialDigits.
+ // The last condition implies that the result will never contain more than
+ // kMaxExponentialDigits + 8 characters (the sign, the digit before the
+ // decimal point, the decimal point, the exponent character, the
+ // exponent's sign, and at most 3 exponent digits).
+ MFBT_API bool ToExponential(double value,
+ int requested_digits,
+ StringBuilder* result_builder) const;
+
+ // Computes 'precision' leading digits of the given 'value' and returns them
+ // either in exponential or decimal format, depending on
+ // max_{leading|trailing}_padding_zeroes_in_precision_mode (given to the
+ // constructor).
+ // The last computed digit is rounded.
+ //
+ // Example with max_leading_padding_zeroes_in_precision_mode = 6.
+ // ToPrecision(0.0000012345, 2) -> "0.0000012"
+ // ToPrecision(0.00000012345, 2) -> "1.2e-7"
+ // Similarily the converter may add up to
+ // max_trailing_padding_zeroes_in_precision_mode in precision mode to avoid
+ // returning an exponential representation. A zero added by the
+ // EMIT_TRAILING_ZERO_AFTER_POINT flag is counted for this limit.
+ // Examples for max_trailing_padding_zeroes_in_precision_mode = 1:
+ // ToPrecision(230.0, 2) -> "230"
+ // ToPrecision(230.0, 2) -> "230." with EMIT_TRAILING_DECIMAL_POINT.
+ // ToPrecision(230.0, 2) -> "2.3e2" with EMIT_TRAILING_ZERO_AFTER_POINT.
+ // Examples for max_trailing_padding_zeroes_in_precision_mode = 3, and no
+ // EMIT_TRAILING_ZERO_AFTER_POINT:
+ // ToPrecision(123450.0, 6) -> "123450"
+ // ToPrecision(123450.0, 5) -> "123450"
+ // ToPrecision(123450.0, 4) -> "123500"
+ // ToPrecision(123450.0, 3) -> "123000"
+ // ToPrecision(123450.0, 2) -> "1.2e5"
+ //
+ // Returns true if the conversion succeeds. The conversion always succeeds
+ // except for the following cases:
+ // - the input value is special and no infinity_symbol or nan_symbol has
+ // been provided to the constructor,
+ // - precision < kMinPericisionDigits
+ // - precision > kMaxPrecisionDigits
+ // The last condition implies that the result will never contain more than
+ // kMaxPrecisionDigits + 7 characters (the sign, the decimal point, the
+ // exponent character, the exponent's sign, and at most 3 exponent digits).
+ MFBT_API bool ToPrecision(double value,
+ int precision,
+ StringBuilder* result_builder) const;
+
+ enum DtoaMode {
+ // Produce the shortest correct representation.
+ // For example the output of 0.299999999999999988897 is (the less accurate
+ // but correct) 0.3.
+ SHORTEST,
+ // Same as SHORTEST, but for single-precision floats.
+ SHORTEST_SINGLE,
+ // Produce a fixed number of digits after the decimal point.
+ // For instance fixed(0.1, 4) becomes 0.1000
+ // If the input number is big, the output will be big.
+ FIXED,
+ // Fixed number of digits (independent of the decimal point).
+ PRECISION
+ };
+
+ // The maximal number of digits that are needed to emit a double in base 10.
+ // A higher precision can be achieved by using more digits, but the shortest
+ // accurate representation of any double will never use more digits than
+ // kBase10MaximalLength.
+ // Note that DoubleToAscii null-terminates its input. So the given buffer
+ // should be at least kBase10MaximalLength + 1 characters long.
+ static const MFBT_DATA int kBase10MaximalLength = 17;
+
+ // Converts the given double 'v' to ascii. 'v' must not be NaN, +Infinity, or
+ // -Infinity. In SHORTEST_SINGLE-mode this restriction also applies to 'v'
+ // after it has been casted to a single-precision float. That is, in this
+ // mode static_cast<float>(v) must not be NaN, +Infinity or -Infinity.
+ //
+ // The result should be interpreted as buffer * 10^(point-length).
+ //
+ // The output depends on the given mode:
+ // - SHORTEST: produce the least amount of digits for which the internal
+ // identity requirement is still satisfied. If the digits are printed
+ // (together with the correct exponent) then reading this number will give
+ // 'v' again. The buffer will choose the representation that is closest to
+ // 'v'. If there are two at the same distance, than the one farther away
+ // from 0 is chosen (halfway cases - ending with 5 - are rounded up).
+ // In this mode the 'requested_digits' parameter is ignored.
+ // - SHORTEST_SINGLE: same as SHORTEST but with single-precision.
+ // - FIXED: produces digits necessary to print a given number with
+ // 'requested_digits' digits after the decimal point. The produced digits
+ // might be too short in which case the caller has to fill the remainder
+ // with '0's.
+ // Example: toFixed(0.001, 5) is allowed to return buffer="1", point=-2.
+ // Halfway cases are rounded towards +/-Infinity (away from 0). The call
+ // toFixed(0.15, 2) thus returns buffer="2", point=0.
+ // The returned buffer may contain digits that would be truncated from the
+ // shortest representation of the input.
+ // - PRECISION: produces 'requested_digits' where the first digit is not '0'.
+ // Even though the length of produced digits usually equals
+ // 'requested_digits', the function is allowed to return fewer digits, in
+ // which case the caller has to fill the missing digits with '0's.
+ // Halfway cases are again rounded away from 0.
+ // DoubleToAscii expects the given buffer to be big enough to hold all
+ // digits and a terminating null-character. In SHORTEST-mode it expects a
+ // buffer of at least kBase10MaximalLength + 1. In all other modes the
+ // requested_digits parameter and the padding-zeroes limit the size of the
+ // output. Don't forget the decimal point, the exponent character and the
+ // terminating null-character when computing the maximal output size.
+ // The given length is only used in debug mode to ensure the buffer is big
+ // enough.
+ static MFBT_API void DoubleToAscii(double v,
+ DtoaMode mode,
+ int requested_digits,
+ char* buffer,
+ int buffer_length,
+ bool* sign,
+ int* length,
+ int* point);
+
+ private:
+ // Implementation for ToShortest and ToShortestSingle.
+ MFBT_API bool ToShortestIeeeNumber(double value,
+ StringBuilder* result_builder,
+ DtoaMode mode) const;
+
+ // If the value is a special value (NaN or Infinity) constructs the
+ // corresponding string using the configured infinity/nan-symbol.
+ // If either of them is NULL or the value is not special then the
+ // function returns false.
+ MFBT_API bool HandleSpecialValues(double value, StringBuilder* result_builder) const;
+ // Constructs an exponential representation (i.e. 1.234e56).
+ // The given exponent assumes a decimal point after the first decimal digit.
+ MFBT_API void CreateExponentialRepresentation(const char* decimal_digits,
+ int length,
+ int exponent,
+ StringBuilder* result_builder) const;
+ // Creates a decimal representation (i.e 1234.5678).
+ MFBT_API void CreateDecimalRepresentation(const char* decimal_digits,
+ int length,
+ int decimal_point,
+ int digits_after_point,
+ StringBuilder* result_builder) const;
+
+ const int flags_;
+ const char* const infinity_symbol_;
+ const char* const nan_symbol_;
+ const char exponent_character_;
+ const int decimal_in_shortest_low_;
+ const int decimal_in_shortest_high_;
+ const int max_leading_padding_zeroes_in_precision_mode_;
+ const int max_trailing_padding_zeroes_in_precision_mode_;
+
+ DISALLOW_IMPLICIT_CONSTRUCTORS(DoubleToStringConverter);
+};
+
+
+class StringToDoubleConverter {
+ public:
+ // Enumeration for allowing octals and ignoring junk when converting
+ // strings to numbers.
+ enum Flags {
+ NO_FLAGS = 0,
+ ALLOW_HEX = 1,
+ ALLOW_OCTALS = 2,
+ ALLOW_TRAILING_JUNK = 4,
+ ALLOW_LEADING_SPACES = 8,
+ ALLOW_TRAILING_SPACES = 16,
+ ALLOW_SPACES_AFTER_SIGN = 32
+ };
+
+ // Flags should be a bit-or combination of the possible Flags-enum.
+ // - NO_FLAGS: no special flags.
+ // - ALLOW_HEX: recognizes the prefix "0x". Hex numbers may only be integers.
+ // Ex: StringToDouble("0x1234") -> 4660.0
+ // In StringToDouble("0x1234.56") the characters ".56" are trailing
+ // junk. The result of the call is hence dependent on
+ // the ALLOW_TRAILING_JUNK flag and/or the junk value.
+ // With this flag "0x" is a junk-string. Even with ALLOW_TRAILING_JUNK,
+ // the string will not be parsed as "0" followed by junk.
+ //
+ // - ALLOW_OCTALS: recognizes the prefix "0" for octals:
+ // If a sequence of octal digits starts with '0', then the number is
+ // read as octal integer. Octal numbers may only be integers.
+ // Ex: StringToDouble("01234") -> 668.0
+ // StringToDouble("012349") -> 12349.0 // Not a sequence of octal
+ // // digits.
+ // In StringToDouble("01234.56") the characters ".56" are trailing
+ // junk. The result of the call is hence dependent on
+ // the ALLOW_TRAILING_JUNK flag and/or the junk value.
+ // In StringToDouble("01234e56") the characters "e56" are trailing
+ // junk, too.
+ // - ALLOW_TRAILING_JUNK: ignore trailing characters that are not part of
+ // a double literal.
+ // - ALLOW_LEADING_SPACES: skip over leading spaces.
+ // - ALLOW_TRAILING_SPACES: ignore trailing spaces.
+ // - ALLOW_SPACES_AFTER_SIGN: ignore spaces after the sign.
+ // Ex: StringToDouble("- 123.2") -> -123.2.
+ // StringToDouble("+ 123.2") -> 123.2
+ //
+ // empty_string_value is returned when an empty string is given as input.
+ // If ALLOW_LEADING_SPACES or ALLOW_TRAILING_SPACES are set, then a string
+ // containing only spaces is converted to the 'empty_string_value', too.
+ //
+ // junk_string_value is returned when
+ // a) ALLOW_TRAILING_JUNK is not set, and a junk character (a character not
+ // part of a double-literal) is found.
+ // b) ALLOW_TRAILING_JUNK is set, but the string does not start with a
+ // double literal.
+ //
+ // infinity_symbol and nan_symbol are strings that are used to detect
+ // inputs that represent infinity and NaN. They can be null, in which case
+ // they are ignored.
+ // The conversion routine first reads any possible signs. Then it compares the
+ // following character of the input-string with the first character of
+ // the infinity, and nan-symbol. If either matches, the function assumes, that
+ // a match has been found, and expects the following input characters to match
+ // the remaining characters of the special-value symbol.
+ // This means that the following restrictions apply to special-value symbols:
+ // - they must not start with signs ('+', or '-'),
+ // - they must not have the same first character.
+ // - they must not start with digits.
+ //
+ // Examples:
+ // flags = ALLOW_HEX | ALLOW_TRAILING_JUNK,
+ // empty_string_value = 0.0,
+ // junk_string_value = NaN,
+ // infinity_symbol = "infinity",
+ // nan_symbol = "nan":
+ // StringToDouble("0x1234") -> 4660.0.
+ // StringToDouble("0x1234K") -> 4660.0.
+ // StringToDouble("") -> 0.0 // empty_string_value.
+ // StringToDouble(" ") -> NaN // junk_string_value.
+ // StringToDouble(" 1") -> NaN // junk_string_value.
+ // StringToDouble("0x") -> NaN // junk_string_value.
+ // StringToDouble("-123.45") -> -123.45.
+ // StringToDouble("--123.45") -> NaN // junk_string_value.
+ // StringToDouble("123e45") -> 123e45.
+ // StringToDouble("123E45") -> 123e45.
+ // StringToDouble("123e+45") -> 123e45.
+ // StringToDouble("123E-45") -> 123e-45.
+ // StringToDouble("123e") -> 123.0 // trailing junk ignored.
+ // StringToDouble("123e-") -> 123.0 // trailing junk ignored.
+ // StringToDouble("+NaN") -> NaN // NaN string literal.
+ // StringToDouble("-infinity") -> -inf. // infinity literal.
+ // StringToDouble("Infinity") -> NaN // junk_string_value.
+ //
+ // flags = ALLOW_OCTAL | ALLOW_LEADING_SPACES,
+ // empty_string_value = 0.0,
+ // junk_string_value = NaN,
+ // infinity_symbol = NULL,
+ // nan_symbol = NULL:
+ // StringToDouble("0x1234") -> NaN // junk_string_value.
+ // StringToDouble("01234") -> 668.0.
+ // StringToDouble("") -> 0.0 // empty_string_value.
+ // StringToDouble(" ") -> 0.0 // empty_string_value.
+ // StringToDouble(" 1") -> 1.0
+ // StringToDouble("0x") -> NaN // junk_string_value.
+ // StringToDouble("0123e45") -> NaN // junk_string_value.
+ // StringToDouble("01239E45") -> 1239e45.
+ // StringToDouble("-infinity") -> NaN // junk_string_value.
+ // StringToDouble("NaN") -> NaN // junk_string_value.
+ StringToDoubleConverter(int flags,
+ double empty_string_value,
+ double junk_string_value,
+ const char* infinity_symbol,
+ const char* nan_symbol)
+ : flags_(flags),
+ empty_string_value_(empty_string_value),
+ junk_string_value_(junk_string_value),
+ infinity_symbol_(infinity_symbol),
+ nan_symbol_(nan_symbol) {
+ }
+
+ // Performs the conversion.
+ // The output parameter 'processed_characters_count' is set to the number
+ // of characters that have been processed to read the number.
+ // Spaces than are processed with ALLOW_{LEADING|TRAILING}_SPACES are included
+ // in the 'processed_characters_count'. Trailing junk is never included.
+ double StringToDouble(const char* buffer,
+ int length,
+ int* processed_characters_count) {
+ return StringToIeee(buffer, length, processed_characters_count, true);
+ }
+
+ // Same as StringToDouble but reads a float.
+ // Note that this is not equivalent to static_cast<float>(StringToDouble(...))
+ // due to potential double-rounding.
+ float StringToFloat(const char* buffer,
+ int length,
+ int* processed_characters_count) {
+ return static_cast<float>(StringToIeee(buffer, length,
+ processed_characters_count, false));
+ }
+
+ private:
+ const int flags_;
+ const double empty_string_value_;
+ const double junk_string_value_;
+ const char* const infinity_symbol_;
+ const char* const nan_symbol_;
+
+ double StringToIeee(const char* buffer,
+ int length,
+ int* processed_characters_count,
+ bool read_as_double);
+
+ DISALLOW_IMPLICIT_CONSTRUCTORS(StringToDoubleConverter);
+};
+
+} // namespace double_conversion
+
+#endif // DOUBLE_CONVERSION_DOUBLE_CONVERSION_H_
diff --git a/mfbt/double-conversion/fast-dtoa.cc b/mfbt/double-conversion/fast-dtoa.cc
new file mode 100644
index 0000000..1a0f823
--- /dev/null
+++ b/mfbt/double-conversion/fast-dtoa.cc
@@ -0,0 +1,664 @@
+// Copyright 2012 the V8 project authors. All rights reserved.
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+// * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+// * 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.
+// * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived
+// from this software without specific prior written permission.
+//
+// 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.
+
+#include "fast-dtoa.h"
+
+#include "cached-powers.h"
+#include "diy-fp.h"
+#include "ieee.h"
+
+namespace double_conversion {
+
+// The minimal and maximal target exponent define the range of w's binary
+// exponent, where 'w' is the result of multiplying the input by a cached power
+// of ten.
+//
+// A different range might be chosen on a different platform, to optimize digit
+// generation, but a smaller range requires more powers of ten to be cached.
+static const int kMinimalTargetExponent = -60;
+static const int kMaximalTargetExponent = -32;
+
+
+// Adjusts the last digit of the generated number, and screens out generated
+// solutions that may be inaccurate. A solution may be inaccurate if it is
+// outside the safe interval, or if we cannot prove that it is closer to the
+// input than a neighboring representation of the same length.
+//
+// Input: * buffer containing the digits of too_high / 10^kappa
+// * the buffer's length
+// * distance_too_high_w == (too_high - w).f() * unit
+// * unsafe_interval == (too_high - too_low).f() * unit
+// * rest = (too_high - buffer * 10^kappa).f() * unit
+// * ten_kappa = 10^kappa * unit
+// * unit = the common multiplier
+// Output: returns true if the buffer is guaranteed to contain the closest
+// representable number to the input.
+// Modifies the generated digits in the buffer to approach (round towards) w.
+static bool RoundWeed(Vector<char> buffer,
+ int length,
+ uint64_t distance_too_high_w,
+ uint64_t unsafe_interval,
+ uint64_t rest,
+ uint64_t ten_kappa,
+ uint64_t unit) {
+ uint64_t small_distance = distance_too_high_w - unit;
+ uint64_t big_distance = distance_too_high_w + unit;
+ // Let w_low = too_high - big_distance, and
+ // w_high = too_high - small_distance.
+ // Note: w_low < w < w_high
+ //
+ // The real w (* unit) must lie somewhere inside the interval
+ // ]w_low; w_high[ (often written as "(w_low; w_high)")
+
+ // Basically the buffer currently contains a number in the unsafe interval
+ // ]too_low; too_high[ with too_low < w < too_high
+ //
+ // too_high - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
+ // ^v 1 unit ^ ^ ^ ^
+ // boundary_high --------------------- . . . .
+ // ^v 1 unit . . . .
+ // - - - - - - - - - - - - - - - - - - - + - - + - - - - - - . .
+ // . . ^ . .
+ // . big_distance . . .
+ // . . . . rest
+ // small_distance . . . .
+ // v . . . .
+ // w_high - - - - - - - - - - - - - - - - - - . . . .
+ // ^v 1 unit . . . .
+ // w ---------------------------------------- . . . .
+ // ^v 1 unit v . . .
+ // w_low - - - - - - - - - - - - - - - - - - - - - . . .
+ // . . v
+ // buffer --------------------------------------------------+-------+--------
+ // . .
+ // safe_interval .
+ // v .
+ // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - .
+ // ^v 1 unit .
+ // boundary_low ------------------------- unsafe_interval
+ // ^v 1 unit v
+ // too_low - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
+ //
+ //
+ // Note that the value of buffer could lie anywhere inside the range too_low
+ // to too_high.
+ //
+ // boundary_low, boundary_high and w are approximations of the real boundaries
+ // and v (the input number). They are guaranteed to be precise up to one unit.
+ // In fact the error is guaranteed to be strictly less than one unit.
+ //
+ // Anything that lies outside the unsafe interval is guaranteed not to round
+ // to v when read again.
+ // Anything that lies inside the safe interval is guaranteed to round to v
+ // when read again.
+ // If the number inside the buffer lies inside the unsafe interval but not
+ // inside the safe interval then we simply do not know and bail out (returning
+ // false).
+ //
+ // Similarly we have to take into account the imprecision of 'w' when finding
+ // the closest representation of 'w'. If we have two potential
+ // representations, and one is closer to both w_low and w_high, then we know
+ // it is closer to the actual value v.
+ //
+ // By generating the digits of too_high we got the largest (closest to
+ // too_high) buffer that is still in the unsafe interval. In the case where
+ // w_high < buffer < too_high we try to decrement the buffer.
+ // This way the buffer approaches (rounds towards) w.
+ // There are 3 conditions that stop the decrementation process:
+ // 1) the buffer is already below w_high
+ // 2) decrementing the buffer would make it leave the unsafe interval
+ // 3) decrementing the buffer would yield a number below w_high and farther
+ // away than the current number. In other words:
+ // (buffer{-1} < w_high) && w_high - buffer{-1} > buffer - w_high
+ // Instead of using the buffer directly we use its distance to too_high.
+ // Conceptually rest ~= too_high - buffer
+ // We need to do the following tests in this order to avoid over- and
+ // underflows.
+ ASSERT(rest <= unsafe_interval);
+ while (rest < small_distance && // Negated condition 1
+ unsafe_interval - rest >= ten_kappa && // Negated condition 2
+ (rest + ten_kappa < small_distance || // buffer{-1} > w_high
+ small_distance - rest >= rest + ten_kappa - small_distance)) {
+ buffer[length - 1]--;
+ rest += ten_kappa;
+ }
+
+ // We have approached w+ as much as possible. We now test if approaching w-
+ // would require changing the buffer. If yes, then we have two possible
+ // representations close to w, but we cannot decide which one is closer.
+ if (rest < big_distance &&
+ unsafe_interval - rest >= ten_kappa &&
+ (rest + ten_kappa < big_distance ||
+ big_distance - rest > rest + ten_kappa - big_distance)) {
+ return false;
+ }
+
+ // Weeding test.
+ // The safe interval is [too_low + 2 ulp; too_high - 2 ulp]
+ // Since too_low = too_high - unsafe_interval this is equivalent to
+ // [too_high - unsafe_interval + 4 ulp; too_high - 2 ulp]
+ // Conceptually we have: rest ~= too_high - buffer
+ return (2 * unit <= rest) && (rest <= unsafe_interval - 4 * unit);
+}
+
+
+// Rounds the buffer upwards if the result is closer to v by possibly adding
+// 1 to the buffer. If the precision of the calculation is not sufficient to
+// round correctly, return false.
+// The rounding might shift the whole buffer in which case the kappa is
+// adjusted. For example "99", kappa = 3 might become "10", kappa = 4.
+//
+// If 2*rest > ten_kappa then the buffer needs to be round up.
+// rest can have an error of +/- 1 unit. This function accounts for the
+// imprecision and returns false, if the rounding direction cannot be
+// unambiguously determined.
+//
+// Precondition: rest < ten_kappa.
+static bool RoundWeedCounted(Vector<char> buffer,
+ int length,
+ uint64_t rest,
+ uint64_t ten_kappa,
+ uint64_t unit,
+ int* kappa) {
+ ASSERT(rest < ten_kappa);
+ // The following tests are done in a specific order to avoid overflows. They
+ // will work correctly with any uint64 values of rest < ten_kappa and unit.
+ //
+ // If the unit is too big, then we don't know which way to round. For example
+ // a unit of 50 means that the real number lies within rest +/- 50. If
+ // 10^kappa == 40 then there is no way to tell which way to round.
+ if (unit >= ten_kappa) return false;
+ // Even if unit is just half the size of 10^kappa we are already completely
+ // lost. (And after the previous test we know that the expression will not
+ // over/underflow.)
+ if (ten_kappa - unit <= unit) return false;
+ // If 2 * (rest + unit) <= 10^kappa we can safely round down.
+ if ((ten_kappa - rest > rest) && (ten_kappa - 2 * rest >= 2 * unit)) {
+ return true;
+ }
+ // If 2 * (rest - unit) >= 10^kappa, then we can safely round up.
+ if ((rest > unit) && (ten_kappa - (rest - unit) <= (rest - unit))) {
+ // Increment the last digit recursively until we find a non '9' digit.
+ buffer[length - 1]++;
+ for (int i = length - 1; i > 0; --i) {
+ if (buffer[i] != '0' + 10) break;
+ buffer[i] = '0';
+ buffer[i - 1]++;
+ }
+ // If the first digit is now '0'+ 10 we had a buffer with all '9's. With the
+ // exception of the first digit all digits are now '0'. Simply switch the
+ // first digit to '1' and adjust the kappa. Example: "99" becomes "10" and
+ // the power (the kappa) is increased.
+ if (buffer[0] == '0' + 10) {
+ buffer[0] = '1';
+ (*kappa) += 1;
+ }
+ return true;
+ }
+ return false;
+}
+
+// Returns the biggest power of ten that is less than or equal to the given
+// number. We furthermore receive the maximum number of bits 'number' has.
+//
+// Returns power == 10^(exponent_plus_one-1) such that
+// power <= number < power * 10.
+// If number_bits == 0 then 0^(0-1) is returned.
+// The number of bits must be <= 32.
+// Precondition: number < (1 << (number_bits + 1)).
+
+// Inspired by the method for finding an integer log base 10 from here:
+// http://graphics.stanford.edu/~seander/bithacks.html#IntegerLog10
+static unsigned int const kSmallPowersOfTen[] =
+ {0, 1, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000,
+ 1000000000};
+
+static void BiggestPowerTen(uint32_t number,
+ int number_bits,
+ uint32_t* power,
+ int* exponent_plus_one) {
+ ASSERT(number < (1u << (number_bits + 1)));
+ // 1233/4096 is approximately 1/lg(10).
+ int exponent_plus_one_guess = ((number_bits + 1) * 1233 >> 12);
+ // We increment to skip over the first entry in the kPowersOf10 table.
+ // Note: kPowersOf10[i] == 10^(i-1).
+ exponent_plus_one_guess++;
+ // We don't have any guarantees that 2^number_bits <= number.
+ // TODO(floitsch): can we change the 'while' into an 'if'? We definitely see
+ // number < (2^number_bits - 1), but I haven't encountered
+ // number < (2^number_bits - 2) yet.
+ while (number < kSmallPowersOfTen[exponent_plus_one_guess]) {
+ exponent_plus_one_guess--;
+ }
+ *power = kSmallPowersOfTen[exponent_plus_one_guess];
+ *exponent_plus_one = exponent_plus_one_guess;
+}
+
+// Generates the digits of input number w.
+// w is a floating-point number (DiyFp), consisting of a significand and an
+// exponent. Its exponent is bounded by kMinimalTargetExponent and
+// kMaximalTargetExponent.
+// Hence -60 <= w.e() <= -32.
+//
+// Returns false if it fails, in which case the generated digits in the buffer
+// should not be used.
+// Preconditions:
+// * low, w and high are correct up to 1 ulp (unit in the last place). That
+// is, their error must be less than a unit of their last digits.
+// * low.e() == w.e() == high.e()
+// * low < w < high, and taking into account their error: low~ <= high~
+// * kMinimalTargetExponent <= w.e() <= kMaximalTargetExponent
+// Postconditions: returns false if procedure fails.
+// otherwise:
+// * buffer is not null-terminated, but len contains the number of digits.
+// * buffer contains the shortest possible decimal digit-sequence
+// such that LOW < buffer * 10^kappa < HIGH, where LOW and HIGH are the
+// correct values of low and high (without their error).
+// * if more than one decimal representation gives the minimal number of
+// decimal digits then the one closest to W (where W is the correct value
+// of w) is chosen.
+// Remark: this procedure takes into account the imprecision of its input
+// numbers. If the precision is not enough to guarantee all the postconditions
+// then false is returned. This usually happens rarely (~0.5%).
+//
+// Say, for the sake of example, that
+// w.e() == -48, and w.f() == 0x1234567890abcdef
+// w's value can be computed by w.f() * 2^w.e()
+// We can obtain w's integral digits by simply shifting w.f() by -w.e().
+// -> w's integral part is 0x1234
+// w's fractional part is therefore 0x567890abcdef.
+// Printing w's integral part is easy (simply print 0x1234 in decimal).
+// In order to print its fraction we repeatedly multiply the fraction by 10 and
+// get each digit. Example the first digit after the point would be computed by
+// (0x567890abcdef * 10) >> 48. -> 3
+// The whole thing becomes slightly more complicated because we want to stop
+// once we have enough digits. That is, once the digits inside the buffer
+// represent 'w' we can stop. Everything inside the interval low - high
+// represents w. However we have to pay attention to low, high and w's
+// imprecision.
+static bool DigitGen(DiyFp low,
+ DiyFp w,
+ DiyFp high,
+ Vector<char> buffer,
+ int* length,
+ int* kappa) {
+ ASSERT(low.e() == w.e() && w.e() == high.e());
+ ASSERT(low.f() + 1 <= high.f() - 1);
+ ASSERT(kMinimalTargetExponent <= w.e() && w.e() <= kMaximalTargetExponent);
+ // low, w and high are imprecise, but by less than one ulp (unit in the last
+ // place).
+ // If we remove (resp. add) 1 ulp from low (resp. high) we are certain that
+ // the new numbers are outside of the interval we want the final
+ // representation to lie in.
+ // Inversely adding (resp. removing) 1 ulp from low (resp. high) would yield
+ // numbers that are certain to lie in the interval. We will use this fact
+ // later on.
+ // We will now start by generating the digits within the uncertain
+ // interval. Later we will weed out representations that lie outside the safe
+ // interval and thus _might_ lie outside the correct interval.
+ uint64_t unit = 1;
+ DiyFp too_low = DiyFp(low.f() - unit, low.e());
+ DiyFp too_high = DiyFp(high.f() + unit, high.e());
+ // too_low and too_high are guaranteed to lie outside the interval we want the
+ // generated number in.
+ DiyFp unsafe_interval = DiyFp::Minus(too_high, too_low);
+ // We now cut the input number into two parts: the integral digits and the
+ // fractionals. We will not write any decimal separator though, but adapt
+ // kappa instead.
+ // Reminder: we are currently computing the digits (stored inside the buffer)
+ // such that: too_low < buffer * 10^kappa < too_high
+ // We use too_high for the digit_generation and stop as soon as possible.
+ // If we stop early we effectively round down.
+ DiyFp one = DiyFp(static_cast<uint64_t>(1) << -w.e(), w.e());
+ // Division by one is a shift.
+ uint32_t integrals = static_cast<uint32_t>(too_high.f() >> -one.e());
+ // Modulo by one is an and.
+ uint64_t fractionals = too_high.f() & (one.f() - 1);
+ uint32_t divisor;
+ int divisor_exponent_plus_one;
+ BiggestPowerTen(integrals, DiyFp::kSignificandSize - (-one.e()),
+ &divisor, &divisor_exponent_plus_one);
+ *kappa = divisor_exponent_plus_one;
+ *length = 0;
+ // Loop invariant: buffer = too_high / 10^kappa (integer division)
+ // The invariant holds for the first iteration: kappa has been initialized
+ // with the divisor exponent + 1. And the divisor is the biggest power of ten
+ // that is smaller than integrals.
+ while (*kappa > 0) {
+ int digit = integrals / divisor;
+ buffer[*length] = '0' + digit;
+ (*length)++;
+ integrals %= divisor;
+ (*kappa)--;
+ // Note that kappa now equals the exponent of the divisor and that the
+ // invariant thus holds again.
+ uint64_t rest =
+ (static_cast<uint64_t>(integrals) << -one.e()) + fractionals;
+ // Invariant: too_high = buffer * 10^kappa + DiyFp(rest, one.e())
+ // Reminder: unsafe_interval.e() == one.e()
+ if (rest < unsafe_interval.f()) {
+ // Rounding down (by not emitting the remaining digits) yields a number
+ // that lies within the unsafe interval.
+ return RoundWeed(buffer, *length, DiyFp::Minus(too_high, w).f(),
+ unsafe_interval.f(), rest,
+ static_cast<uint64_t>(divisor) << -one.e(), unit);
+ }
+ divisor /= 10;
+ }
+
+ // The integrals have been generated. We are at the point of the decimal
+ // separator. In the following loop we simply multiply the remaining digits by
+ // 10 and divide by one. We just need to pay attention to multiply associated
+ // data (like the interval or 'unit'), too.
+ // Note that the multiplication by 10 does not overflow, because w.e >= -60
+ // and thus one.e >= -60.
+ ASSERT(one.e() >= -60);
+ ASSERT(fractionals < one.f());
+ ASSERT(UINT64_2PART_C(0xFFFFFFFF, FFFFFFFF) / 10 >= one.f());
+ while (true) {
+ fractionals *= 10;
+ unit *= 10;
+ unsafe_interval.set_f(unsafe_interval.f() * 10);
+ // Integer division by one.
+ int digit = static_cast<int>(fractionals >> -one.e());
+ buffer[*length] = '0' + digit;
+ (*length)++;
+ fractionals &= one.f() - 1; // Modulo by one.
+ (*kappa)--;
+ if (fractionals < unsafe_interval.f()) {
+ return RoundWeed(buffer, *length, DiyFp::Minus(too_high, w).f() * unit,
+ unsafe_interval.f(), fractionals, one.f(), unit);
+ }
+ }
+}
+
+
+
+// Generates (at most) requested_digits digits of input number w.
+// w is a floating-point number (DiyFp), consisting of a significand and an
+// exponent. Its exponent is bounded by kMinimalTargetExponent and
+// kMaximalTargetExponent.
+// Hence -60 <= w.e() <= -32.
+//
+// Returns false if it fails, in which case the generated digits in the buffer
+// should not be used.
+// Preconditions:
+// * w is correct up to 1 ulp (unit in the last place). That
+// is, its error must be strictly less than a unit of its last digit.
+// * kMinimalTargetExponent <= w.e() <= kMaximalTargetExponent
+//
+// Postconditions: returns false if procedure fails.
+// otherwise:
+// * buffer is not null-terminated, but length contains the number of
+// digits.
+// * the representation in buffer is the most precise representation of
+// requested_digits digits.
+// * buffer contains at most requested_digits digits of w. If there are less
+// than requested_digits digits then some trailing '0's have been removed.
+// * kappa is such that
+// w = buffer * 10^kappa + eps with |eps| < 10^kappa / 2.
+//
+// Remark: This procedure takes into account the imprecision of its input
+// numbers. If the precision is not enough to guarantee all the postconditions
+// then false is returned. This usually happens rarely, but the failure-rate
+// increases with higher requested_digits.
+static bool DigitGenCounted(DiyFp w,
+ int requested_digits,
+ Vector<char> buffer,
+ int* length,
+ int* kappa) {
+ ASSERT(kMinimalTargetExponent <= w.e() && w.e() <= kMaximalTargetExponent);
+ ASSERT(kMinimalTargetExponent >= -60);
+ ASSERT(kMaximalTargetExponent <= -32);
+ // w is assumed to have an error less than 1 unit. Whenever w is scaled we
+ // also scale its error.
+ uint64_t w_error = 1;
+ // We cut the input number into two parts: the integral digits and the
+ // fractional digits. We don't emit any decimal separator, but adapt kappa
+ // instead. Example: instead of writing "1.2" we put "12" into the buffer and
+ // increase kappa by 1.
+ DiyFp one = DiyFp(static_cast<uint64_t>(1) << -w.e(), w.e());
+ // Division by one is a shift.
+ uint32_t integrals = static_cast<uint32_t>(w.f() >> -one.e());
+ // Modulo by one is an and.
+ uint64_t fractionals = w.f() & (one.f() - 1);
+ uint32_t divisor;
+ int divisor_exponent_plus_one;
+ BiggestPowerTen(integrals, DiyFp::kSignificandSize - (-one.e()),
+ &divisor, &divisor_exponent_plus_one);
+ *kappa = divisor_exponent_plus_one;
+ *length = 0;
+
+ // Loop invariant: buffer = w / 10^kappa (integer division)
+ // The invariant holds for the first iteration: kappa has been initialized
+ // with the divisor exponent + 1. And the divisor is the biggest power of ten
+ // that is smaller than 'integrals'.
+ while (*kappa > 0) {
+ int digit = integrals / divisor;
+ buffer[*length] = '0' + digit;
+ (*length)++;
+ requested_digits--;
+ integrals %= divisor;
+ (*kappa)--;
+ // Note that kappa now equals the exponent of the divisor and that the
+ // invariant thus holds again.
+ if (requested_digits == 0) break;
+ divisor /= 10;
+ }
+
+ if (requested_digits == 0) {
+ uint64_t rest =
+ (static_cast<uint64_t>(integrals) << -one.e()) + fractionals;
+ return RoundWeedCounted(buffer, *length, rest,
+ static_cast<uint64_t>(divisor) << -one.e(), w_error,
+ kappa);
+ }
+
+ // The integrals have been generated. We are at the point of the decimal
+ // separator. In the following loop we simply multiply the remaining digits by
+ // 10 and divide by one. We just need to pay attention to multiply associated
+ // data (the 'unit'), too.
+ // Note that the multiplication by 10 does not overflow, because w.e >= -60
+ // and thus one.e >= -60.
+ ASSERT(one.e() >= -60);
+ ASSERT(fractionals < one.f());
+ ASSERT(UINT64_2PART_C(0xFFFFFFFF, FFFFFFFF) / 10 >= one.f());
+ while (requested_digits > 0 && fractionals > w_error) {
+ fractionals *= 10;
+ w_error *= 10;
+ // Integer division by one.
+ int digit = static_cast<int>(fractionals >> -one.e());
+ buffer[*length] = '0' + digit;
+ (*length)++;
+ requested_digits--;
+ fractionals &= one.f() - 1; // Modulo by one.
+ (*kappa)--;
+ }
+ if (requested_digits != 0) return false;
+ return RoundWeedCounted(buffer, *length, fractionals, one.f(), w_error,
+ kappa);
+}
+
+
+// Provides a decimal representation of v.
+// Returns true if it succeeds, otherwise the result cannot be trusted.
+// There will be *length digits inside the buffer (not null-terminated).
+// If the function returns true then
+// v == (double) (buffer * 10^decimal_exponent).
+// The digits in the buffer are the shortest representation possible: no
+// 0.09999999999999999 instead of 0.1. The shorter representation will even be
+// chosen even if the longer one would be closer to v.
+// The last digit will be closest to the actual v. That is, even if several
+// digits might correctly yield 'v' when read again, the closest will be
+// computed.
+static bool Grisu3(double v,
+ FastDtoaMode mode,
+ Vector<char> buffer,
+ int* length,
+ int* decimal_exponent) {
+ DiyFp w = Double(v).AsNormalizedDiyFp();
+ // boundary_minus and boundary_plus are the boundaries between v and its
+ // closest floating-point neighbors. Any number strictly between
+ // boundary_minus and boundary_plus will round to v when convert to a double.
+ // Grisu3 will never output representations that lie exactly on a boundary.
+ DiyFp boundary_minus, boundary_plus;
+ if (mode == FAST_DTOA_SHORTEST) {
+ Double(v).NormalizedBoundaries(&boundary_minus, &boundary_plus);
+ } else {
+ ASSERT(mode == FAST_DTOA_SHORTEST_SINGLE);
+ float single_v = static_cast<float>(v);
+ Single(single_v).NormalizedBoundaries(&boundary_minus, &boundary_plus);
+ }
+ ASSERT(boundary_plus.e() == w.e());
+ DiyFp ten_mk; // Cached power of ten: 10^-k
+ int mk; // -k
+ int ten_mk_minimal_binary_exponent =
+ kMinimalTargetExponent - (w.e() + DiyFp::kSignificandSize);
+ int ten_mk_maximal_binary_exponent =
+ kMaximalTargetExponent - (w.e() + DiyFp::kSignificandSize);
+ PowersOfTenCache::GetCachedPowerForBinaryExponentRange(
+ ten_mk_minimal_binary_exponent,
+ ten_mk_maximal_binary_exponent,
+ &ten_mk, &mk);
+ ASSERT((kMinimalTargetExponent <= w.e() + ten_mk.e() +
+ DiyFp::kSignificandSize) &&
+ (kMaximalTargetExponent >= w.e() + ten_mk.e() +
+ DiyFp::kSignificandSize));
+ // Note that ten_mk is only an approximation of 10^-k. A DiyFp only contains a
+ // 64 bit significand and ten_mk is thus only precise up to 64 bits.
+
+ // The DiyFp::Times procedure rounds its result, and ten_mk is approximated
+ // too. The variable scaled_w (as well as scaled_boundary_minus/plus) are now
+ // off by a small amount.
+ // In fact: scaled_w - w*10^k < 1ulp (unit in the last place) of scaled_w.
+ // In other words: let f = scaled_w.f() and e = scaled_w.e(), then
+ // (f-1) * 2^e < w*10^k < (f+1) * 2^e
+ DiyFp scaled_w = DiyFp::Times(w, ten_mk);
+ ASSERT(scaled_w.e() ==
+ boundary_plus.e() + ten_mk.e() + DiyFp::kSignificandSize);
+ // In theory it would be possible to avoid some recomputations by computing
+ // the difference between w and boundary_minus/plus (a power of 2) and to
+ // compute scaled_boundary_minus/plus by subtracting/adding from
+ // scaled_w. However the code becomes much less readable and the speed
+ // enhancements are not terriffic.
+ DiyFp scaled_boundary_minus = DiyFp::Times(boundary_minus, ten_mk);
+ DiyFp scaled_boundary_plus = DiyFp::Times(boundary_plus, ten_mk);
+
+ // DigitGen will generate the digits of scaled_w. Therefore we have
+ // v == (double) (scaled_w * 10^-mk).
+ // Set decimal_exponent == -mk and pass it to DigitGen. If scaled_w is not an
+ // integer than it will be updated. For instance if scaled_w == 1.23 then
+ // the buffer will be filled with "123" und the decimal_exponent will be
+ // decreased by 2.
+ int kappa;
+ bool result = DigitGen(scaled_boundary_minus, scaled_w, scaled_boundary_plus,
+ buffer, length, &kappa);
+ *decimal_exponent = -mk + kappa;
+ return result;
+}
+
+
+// The "counted" version of grisu3 (see above) only generates requested_digits
+// number of digits. This version does not generate the shortest representation,
+// and with enough requested digits 0.1 will at some point print as 0.9999999...
+// Grisu3 is too imprecise for real halfway cases (1.5 will not work) and
+// therefore the rounding strategy for halfway cases is irrelevant.
+static bool Grisu3Counted(double v,
+ int requested_digits,
+ Vector<char> buffer,
+ int* length,
+ int* decimal_exponent) {
+ DiyFp w = Double(v).AsNormalizedDiyFp();
+ DiyFp ten_mk; // Cached power of ten: 10^-k
+ int mk; // -k
+ int ten_mk_minimal_binary_exponent =
+ kMinimalTargetExponent - (w.e() + DiyFp::kSignificandSize);
+ int ten_mk_maximal_binary_exponent =
+ kMaximalTargetExponent - (w.e() + DiyFp::kSignificandSize);
+ PowersOfTenCache::GetCachedPowerForBinaryExponentRange(
+ ten_mk_minimal_binary_exponent,
+ ten_mk_maximal_binary_exponent,
+ &ten_mk, &mk);
+ ASSERT((kMinimalTargetExponent <= w.e() + ten_mk.e() +
+ DiyFp::kSignificandSize) &&
+ (kMaximalTargetExponent >= w.e() + ten_mk.e() +
+ DiyFp::kSignificandSize));
+ // Note that ten_mk is only an approximation of 10^-k. A DiyFp only contains a
+ // 64 bit significand and ten_mk is thus only precise up to 64 bits.
+
+ // The DiyFp::Times procedure rounds its result, and ten_mk is approximated
+ // too. The variable scaled_w (as well as scaled_boundary_minus/plus) are now
+ // off by a small amount.
+ // In fact: scaled_w - w*10^k < 1ulp (unit in the last place) of scaled_w.
+ // In other words: let f = scaled_w.f() and e = scaled_w.e(), then
+ // (f-1) * 2^e < w*10^k < (f+1) * 2^e
+ DiyFp scaled_w = DiyFp::Times(w, ten_mk);
+
+ // We now have (double) (scaled_w * 10^-mk).
+ // DigitGen will generate the first requested_digits digits of scaled_w and
+ // return together with a kappa such that scaled_w ~= buffer * 10^kappa. (It
+ // will not always be exactly the same since DigitGenCounted only produces a
+ // limited number of digits.)
+ int kappa;
+ bool result = DigitGenCounted(scaled_w, requested_digits,
+ buffer, length, &kappa);
+ *decimal_exponent = -mk + kappa;
+ return result;
+}
+
+
+bool FastDtoa(double v,
+ FastDtoaMode mode,
+ int requested_digits,
+ Vector<char> buffer,
+ int* length,
+ int* decimal_point) {
+ ASSERT(v > 0);
+ ASSERT(!Double(v).IsSpecial());
+
+ bool result = false;
+ int decimal_exponent = 0;
+ switch (mode) {
+ case FAST_DTOA_SHORTEST:
+ case FAST_DTOA_SHORTEST_SINGLE:
+ result = Grisu3(v, mode, buffer, length, &decimal_exponent);
+ break;
+ case FAST_DTOA_PRECISION:
+ result = Grisu3Counted(v, requested_digits,
+ buffer, length, &decimal_exponent);
+ break;
+ default:
+ UNREACHABLE();
+ }
+ if (result) {
+ *decimal_point = *length + decimal_exponent;
+ buffer[*length] = '\0';
+ }
+ return result;
+}
+
+} // namespace double_conversion
diff --git a/mfbt/double-conversion/fast-dtoa.h b/mfbt/double-conversion/fast-dtoa.h
new file mode 100644
index 0000000..5f1e8ee
--- /dev/null
+++ b/mfbt/double-conversion/fast-dtoa.h
@@ -0,0 +1,88 @@
+// Copyright 2010 the V8 project authors. All rights reserved.
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+// * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+// * 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.
+// * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived
+// from this software without specific prior written permission.
+//
+// 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.
+
+#ifndef DOUBLE_CONVERSION_FAST_DTOA_H_
+#define DOUBLE_CONVERSION_FAST_DTOA_H_
+
+#include "utils.h"
+
+namespace double_conversion {
+
+enum FastDtoaMode {
+ // Computes the shortest representation of the given input. The returned
+ // result will be the most accurate number of this length. Longer
+ // representations might be more accurate.
+ FAST_DTOA_SHORTEST,
+ // Same as FAST_DTOA_SHORTEST but for single-precision floats.
+ FAST_DTOA_SHORTEST_SINGLE,
+ // Computes a representation where the precision (number of digits) is
+ // given as input. The precision is independent of the decimal point.
+ FAST_DTOA_PRECISION
+};
+
+// FastDtoa will produce at most kFastDtoaMaximalLength digits. This does not
+// include the terminating '\0' character.
+static const int kFastDtoaMaximalLength = 17;
+// Same for single-precision numbers.
+static const int kFastDtoaMaximalSingleLength = 9;
+
+// Provides a decimal representation of v.
+// The result should be interpreted as buffer * 10^(point - length).
+//
+// Precondition:
+// * v must be a strictly positive finite double.
+//
+// Returns true if it succeeds, otherwise the result can not be trusted.
+// There will be *length digits inside the buffer followed by a null terminator.
+// If the function returns true and mode equals
+// - FAST_DTOA_SHORTEST, then
+// the parameter requested_digits is ignored.
+// The result satisfies
+// v == (double) (buffer * 10^(point - length)).
+// The digits in the buffer are the shortest representation possible. E.g.
+// if 0.099999999999 and 0.1 represent the same double then "1" is returned
+// with point = 0.
+// The last digit will be closest to the actual v. That is, even if several
+// digits might correctly yield 'v' when read again, the buffer will contain
+// the one closest to v.
+// - FAST_DTOA_PRECISION, then
+// the buffer contains requested_digits digits.
+// the difference v - (buffer * 10^(point-length)) is closest to zero for
+// all possible representations of requested_digits digits.
+// If there are two values that are equally close, then FastDtoa returns
+// false.
+// For both modes the buffer must be large enough to hold the result.
+bool FastDtoa(double d,
+ FastDtoaMode mode,
+ int requested_digits,
+ Vector<char> buffer,
+ int* length,
+ int* decimal_point);
+
+} // namespace double_conversion
+
+#endif // DOUBLE_CONVERSION_FAST_DTOA_H_
diff --git a/mfbt/double-conversion/fixed-dtoa.cc b/mfbt/double-conversion/fixed-dtoa.cc
new file mode 100644
index 0000000..d56b144
--- /dev/null
+++ b/mfbt/double-conversion/fixed-dtoa.cc
@@ -0,0 +1,402 @@
+// Copyright 2010 the V8 project authors. All rights reserved.
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+// * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+// * 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.
+// * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived
+// from this software without specific prior written permission.
+//
+// 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.
+
+#include <math.h>
+
+#include "fixed-dtoa.h"
+#include "ieee.h"
+
+namespace double_conversion {
+
+// Represents a 128bit type. This class should be replaced by a native type on
+// platforms that support 128bit integers.
+class UInt128 {
+ public:
+ UInt128() : high_bits_(0), low_bits_(0) { }
+ UInt128(uint64_t high, uint64_t low) : high_bits_(high), low_bits_(low) { }
+
+ void Multiply(uint32_t multiplicand) {
+ uint64_t accumulator;
+
+ accumulator = (low_bits_ & kMask32) * multiplicand;
+ uint32_t part = static_cast<uint32_t>(accumulator & kMask32);
+ accumulator >>= 32;
+ accumulator = accumulator + (low_bits_ >> 32) * multiplicand;
+ low_bits_ = (accumulator << 32) + part;
+ accumulator >>= 32;
+ accumulator = accumulator + (high_bits_ & kMask32) * multiplicand;
+ part = static_cast<uint32_t>(accumulator & kMask32);
+ accumulator >>= 32;
+ accumulator = accumulator + (high_bits_ >> 32) * multiplicand;
+ high_bits_ = (accumulator << 32) + part;
+ ASSERT((accumulator >> 32) == 0);
+ }
+
+ void Shift(int shift_amount) {
+ ASSERT(-64 <= shift_amount && shift_amount <= 64);
+ if (shift_amount == 0) {
+ return;
+ } else if (shift_amount == -64) {
+ high_bits_ = low_bits_;
+ low_bits_ = 0;
+ } else if (shift_amount == 64) {
+ low_bits_ = high_bits_;
+ high_bits_ = 0;
+ } else if (shift_amount <= 0) {
+ high_bits_ <<= -shift_amount;
+ high_bits_ += low_bits_ >> (64 + shift_amount);
+ low_bits_ <<= -shift_amount;
+ } else {
+ low_bits_ >>= shift_amount;
+ low_bits_ += high_bits_ << (64 - shift_amount);
+ high_bits_ >>= shift_amount;
+ }
+ }
+
+ // Modifies *this to *this MOD (2^power).
+ // Returns *this DIV (2^power).
+ int DivModPowerOf2(int power) {
+ if (power >= 64) {
+ int result = static_cast<int>(high_bits_ >> (power - 64));
+ high_bits_ -= static_cast<uint64_t>(result) << (power - 64);
+ return result;
+ } else {
+ uint64_t part_low = low_bits_ >> power;
+ uint64_t part_high = high_bits_ << (64 - power);
+ int result = static_cast<int>(part_low + part_high);
+ high_bits_ = 0;
+ low_bits_ -= part_low << power;
+ return result;
+ }
+ }
+
+ bool IsZero() const {
+ return high_bits_ == 0 && low_bits_ == 0;
+ }
+
+ int BitAt(int position) {
+ if (position >= 64) {
+ return static_cast<int>(high_bits_ >> (position - 64)) & 1;
+ } else {
+ return static_cast<int>(low_bits_ >> position) & 1;
+ }
+ }
+
+ private:
+ static const uint64_t kMask32 = 0xFFFFFFFF;
+ // Value == (high_bits_ << 64) + low_bits_
+ uint64_t high_bits_;
+ uint64_t low_bits_;
+};
+
+
+static const int kDoubleSignificandSize = 53; // Includes the hidden bit.
+
+
+static void FillDigits32FixedLength(uint32_t number, int requested_length,
+ Vector<char> buffer, int* length) {
+ for (int i = requested_length - 1; i >= 0; --i) {
+ buffer[(*length) + i] = '0' + number % 10;
+ number /= 10;
+ }
+ *length += requested_length;
+}
+
+
+static void FillDigits32(uint32_t number, Vector<char> buffer, int* length) {
+ int number_length = 0;
+ // We fill the digits in reverse order and exchange them afterwards.
+ while (number != 0) {
+ int digit = number % 10;
+ number /= 10;
+ buffer[(*length) + number_length] = '0' + digit;
+ number_length++;
+ }
+ // Exchange the digits.
+ int i = *length;
+ int j = *length + number_length - 1;
+ while (i < j) {
+ char tmp = buffer[i];
+ buffer[i] = buffer[j];
+ buffer[j] = tmp;
+ i++;
+ j--;
+ }
+ *length += number_length;
+}
+
+
+static void FillDigits64FixedLength(uint64_t number, int requested_length,
+ Vector<char> buffer, int* length) {
+ const uint32_t kTen7 = 10000000;
+ // For efficiency cut the number into 3 uint32_t parts, and print those.
+ uint32_t part2 = static_cast<uint32_t>(number % kTen7);
+ number /= kTen7;
+ uint32_t part1 = static_cast<uint32_t>(number % kTen7);
+ uint32_t part0 = static_cast<uint32_t>(number / kTen7);
+
+ FillDigits32FixedLength(part0, 3, buffer, length);
+ FillDigits32FixedLength(part1, 7, buffer, length);
+ FillDigits32FixedLength(part2, 7, buffer, length);
+}
+
+
+static void FillDigits64(uint64_t number, Vector<char> buffer, int* length) {
+ const uint32_t kTen7 = 10000000;
+ // For efficiency cut the number into 3 uint32_t parts, and print those.
+ uint32_t part2 = static_cast<uint32_t>(number % kTen7);
+ number /= kTen7;
+ uint32_t part1 = static_cast<uint32_t>(number % kTen7);
+ uint32_t part0 = static_cast<uint32_t>(number / kTen7);
+
+ if (part0 != 0) {
+ FillDigits32(part0, buffer, length);
+ FillDigits32FixedLength(part1, 7, buffer, length);
+ FillDigits32FixedLength(part2, 7, buffer, length);
+ } else if (part1 != 0) {
+ FillDigits32(part1, buffer, length);
+ FillDigits32FixedLength(part2, 7, buffer, length);
+ } else {
+ FillDigits32(part2, buffer, length);
+ }
+}
+
+
+static void RoundUp(Vector<char> buffer, int* length, int* decimal_point) {
+ // An empty buffer represents 0.
+ if (*length == 0) {
+ buffer[0] = '1';
+ *decimal_point = 1;
+ *length = 1;
+ return;
+ }
+ // Round the last digit until we either have a digit that was not '9' or until
+ // we reached the first digit.
+ buffer[(*length) - 1]++;
+ for (int i = (*length) - 1; i > 0; --i) {
+ if (buffer[i] != '0' + 10) {
+ return;
+ }
+ buffer[i] = '0';
+ buffer[i - 1]++;
+ }
+ // If the first digit is now '0' + 10, we would need to set it to '0' and add
+ // a '1' in front. However we reach the first digit only if all following
+ // digits had been '9' before rounding up. Now all trailing digits are '0' and
+ // we simply switch the first digit to '1' and update the decimal-point
+ // (indicating that the point is now one digit to the right).
+ if (buffer[0] == '0' + 10) {
+ buffer[0] = '1';
+ (*decimal_point)++;
+ }
+}
+
+
+// The given fractionals number represents a fixed-point number with binary
+// point at bit (-exponent).
+// Preconditions:
+// -128 <= exponent <= 0.
+// 0 <= fractionals * 2^exponent < 1
+// The buffer holds the result.
+// The function will round its result. During the rounding-process digits not
+// generated by this function might be updated, and the decimal-point variable
+// might be updated. If this function generates the digits 99 and the buffer
+// already contained "199" (thus yielding a buffer of "19999") then a
+// rounding-up will change the contents of the buffer to "20000".
+static void FillFractionals(uint64_t fractionals, int exponent,
+ int fractional_count, Vector<char> buffer,
+ int* length, int* decimal_point) {
+ ASSERT(-128 <= exponent && exponent <= 0);
+ // 'fractionals' is a fixed-point number, with binary point at bit
+ // (-exponent). Inside the function the non-converted remainder of fractionals
+ // is a fixed-point number, with binary point at bit 'point'.
+ if (-exponent <= 64) {
+ // One 64 bit number is sufficient.
+ ASSERT(fractionals >> 56 == 0);
+ int point = -exponent;
+ for (int i = 0; i < fractional_count; ++i) {
+ if (fractionals == 0) break;
+ // Instead of multiplying by 10 we multiply by 5 and adjust the point
+ // location. This way the fractionals variable will not overflow.
+ // Invariant at the beginning of the loop: fractionals < 2^point.
+ // Initially we have: point <= 64 and fractionals < 2^56
+ // After each iteration the point is decremented by one.
+ // Note that 5^3 = 125 < 128 = 2^7.
+ // Therefore three iterations of this loop will not overflow fractionals
+ // (even without the subtraction at the end of the loop body). At this
+ // time point will satisfy point <= 61 and therefore fractionals < 2^point
+ // and any further multiplication of fractionals by 5 will not overflow.
+ fractionals *= 5;
+ point--;
+ int digit = static_cast<int>(fractionals >> point);
+ buffer[*length] = '0' + digit;
+ (*length)++;
+ fractionals -= static_cast<uint64_t>(digit) << point;
+ }
+ // If the first bit after the point is set we have to round up.
+ if (((fractionals >> (point - 1)) & 1) == 1) {
+ RoundUp(buffer, length, decimal_point);
+ }
+ } else { // We need 128 bits.
+ ASSERT(64 < -exponent && -exponent <= 128);
+ UInt128 fractionals128 = UInt128(fractionals, 0);
+ fractionals128.Shift(-exponent - 64);
+ int point = 128;
+ for (int i = 0; i < fractional_count; ++i) {
+ if (fractionals128.IsZero()) break;
+ // As before: instead of multiplying by 10 we multiply by 5 and adjust the
+ // point location.
+ // This multiplication will not overflow for the same reasons as before.
+ fractionals128.Multiply(5);
+ point--;
+ int digit = fractionals128.DivModPowerOf2(point);
+ buffer[*length] = '0' + digit;
+ (*length)++;
+ }
+ if (fractionals128.BitAt(point - 1) == 1) {
+ RoundUp(buffer, length, decimal_point);
+ }
+ }
+}
+
+
+// Removes leading and trailing zeros.
+// If leading zeros are removed then the decimal point position is adjusted.
+static void TrimZeros(Vector<char> buffer, int* length, int* decimal_point) {
+ while (*length > 0 && buffer[(*length) - 1] == '0') {
+ (*length)--;
+ }
+ int first_non_zero = 0;
+ while (first_non_zero < *length && buffer[first_non_zero] == '0') {
+ first_non_zero++;
+ }
+ if (first_non_zero != 0) {
+ for (int i = first_non_zero; i < *length; ++i) {
+ buffer[i - first_non_zero] = buffer[i];
+ }
+ *length -= first_non_zero;
+ *decimal_point -= first_non_zero;
+ }
+}
+
+
+bool FastFixedDtoa(double v,
+ int fractional_count,
+ Vector<char> buffer,
+ int* length,
+ int* decimal_point) {
+ const uint32_t kMaxUInt32 = 0xFFFFFFFF;
+ uint64_t significand = Double(v).Significand();
+ int exponent = Double(v).Exponent();
+ // v = significand * 2^exponent (with significand a 53bit integer).
+ // If the exponent is larger than 20 (i.e. we may have a 73bit number) then we
+ // don't know how to compute the representation. 2^73 ~= 9.5*10^21.
+ // If necessary this limit could probably be increased, but we don't need
+ // more.
+ if (exponent > 20) return false;
+ if (fractional_count > 20) return false;
+ *length = 0;
+ // At most kDoubleSignificandSize bits of the significand are non-zero.
+ // Given a 64 bit integer we have 11 0s followed by 53 potentially non-zero
+ // bits: 0..11*..0xxx..53*..xx
+ if (exponent + kDoubleSignificandSize > 64) {
+ // The exponent must be > 11.
+ //
+ // We know that v = significand * 2^exponent.
+ // And the exponent > 11.
+ // We simplify the task by dividing v by 10^17.
+ // The quotient delivers the first digits, and the remainder fits into a 64
+ // bit number.
+ // Dividing by 10^17 is equivalent to dividing by 5^17*2^17.
+ const uint64_t kFive17 = UINT64_2PART_C(0xB1, A2BC2EC5); // 5^17
+ uint64_t divisor = kFive17;
+ int divisor_power = 17;
+ uint64_t dividend = significand;
+ uint32_t quotient;
+ uint64_t remainder;
+ // Let v = f * 2^e with f == significand and e == exponent.
+ // Then need q (quotient) and r (remainder) as follows:
+ // v = q * 10^17 + r
+ // f * 2^e = q * 10^17 + r
+ // f * 2^e = q * 5^17 * 2^17 + r
+ // If e > 17 then
+ // f * 2^(e-17) = q * 5^17 + r/2^17
+ // else
+ // f = q * 5^17 * 2^(17-e) + r/2^e
+ if (exponent > divisor_power) {
+ // We only allow exponents of up to 20 and therefore (17 - e) <= 3
+ dividend <<= exponent - divisor_power;
+ quotient = static_cast<uint32_t>(dividend / divisor);
+ remainder = (dividend % divisor) << divisor_power;
+ } else {
+ divisor <<= divisor_power - exponent;
+ quotient = static_cast<uint32_t>(dividend / divisor);
+ remainder = (dividend % divisor) << exponent;
+ }
+ FillDigits32(quotient, buffer, length);
+ FillDigits64FixedLength(remainder, divisor_power, buffer, length);
+ *decimal_point = *length;
+ } else if (exponent >= 0) {
+ // 0 <= exponent <= 11
+ significand <<= exponent;
+ FillDigits64(significand, buffer, length);
+ *decimal_point = *length;
+ } else if (exponent > -kDoubleSignificandSize) {
+ // We have to cut the number.
+ uint64_t integrals = significand >> -exponent;
+ uint64_t fractionals = significand - (integrals << -exponent);
+ if (integrals > kMaxUInt32) {
+ FillDigits64(integrals, buffer, length);
+ } else {
+ FillDigits32(static_cast<uint32_t>(integrals), buffer, length);
+ }
+ *decimal_point = *length;
+ FillFractionals(fractionals, exponent, fractional_count,
+ buffer, length, decimal_point);
+ } else if (exponent < -128) {
+ // This configuration (with at most 20 digits) means that all digits must be
+ // 0.
+ ASSERT(fractional_count <= 20);
+ buffer[0] = '\0';
+ *length = 0;
+ *decimal_point = -fractional_count;
+ } else {
+ *decimal_point = 0;
+ FillFractionals(significand, exponent, fractional_count,
+ buffer, length, decimal_point);
+ }
+ TrimZeros(buffer, length, decimal_point);
+ buffer[*length] = '\0';
+ if ((*length) == 0) {
+ // The string is empty and the decimal_point thus has no importance. Mimick
+ // Gay's dtoa and and set it to -fractional_count.
+ *decimal_point = -fractional_count;
+ }
+ return true;
+}
+
+} // namespace double_conversion
diff --git a/mfbt/double-conversion/fixed-dtoa.h b/mfbt/double-conversion/fixed-dtoa.h
new file mode 100644
index 0000000..3bdd08e
--- /dev/null
+++ b/mfbt/double-conversion/fixed-dtoa.h
@@ -0,0 +1,56 @@
+// Copyright 2010 the V8 project authors. All rights reserved.
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+// * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+// * 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.
+// * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived
+// from this software without specific prior written permission.
+//
+// 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.
+
+#ifndef DOUBLE_CONVERSION_FIXED_DTOA_H_
+#define DOUBLE_CONVERSION_FIXED_DTOA_H_
+
+#include "utils.h"
+
+namespace double_conversion {
+
+// Produces digits necessary to print a given number with
+// 'fractional_count' digits after the decimal point.
+// The buffer must be big enough to hold the result plus one terminating null
+// character.
+//
+// The produced digits might be too short in which case the caller has to fill
+// the gaps with '0's.
+// Example: FastFixedDtoa(0.001, 5, ...) is allowed to return buffer = "1", and
+// decimal_point = -2.
+// Halfway cases are rounded towards +/-Infinity (away from 0). The call
+// FastFixedDtoa(0.15, 2, ...) thus returns buffer = "2", decimal_point = 0.
+// The returned buffer may contain digits that would be truncated from the
+// shortest representation of the input.
+//
+// This method only works for some parameters. If it can't handle the input it
+// returns false. The output is null-terminated when the function succeeds.
+bool FastFixedDtoa(double v, int fractional_count,
+ Vector<char> buffer, int* length, int* decimal_point);
+
+} // namespace double_conversion
+
+#endif // DOUBLE_CONVERSION_FIXED_DTOA_H_
diff --git a/mfbt/double-conversion/ieee.h b/mfbt/double-conversion/ieee.h
new file mode 100644
index 0000000..839dc47
--- /dev/null
+++ b/mfbt/double-conversion/ieee.h
@@ -0,0 +1,398 @@
+// Copyright 2012 the V8 project authors. All rights reserved.
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+// * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+// * 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.
+// * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived
+// from this software without specific prior written permission.
+//
+// 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.
+
+#ifndef DOUBLE_CONVERSION_DOUBLE_H_
+#define DOUBLE_CONVERSION_DOUBLE_H_
+
+#include "diy-fp.h"
+
+namespace double_conversion {
+
+// We assume that doubles and uint64_t have the same endianness.
+static uint64_t double_to_uint64(double d) { return BitCast<uint64_t>(d); }
+static double uint64_to_double(uint64_t d64) { return BitCast<double>(d64); }
+static uint32_t float_to_uint32(float f) { return BitCast<uint32_t>(f); }
+static float uint32_to_float(uint32_t d32) { return BitCast<float>(d32); }
+
+// Helper functions for doubles.
+class Double {
+ public:
+ static const uint64_t kSignMask = UINT64_2PART_C(0x80000000, 00000000);
+ static const uint64_t kExponentMask = UINT64_2PART_C(0x7FF00000, 00000000);
+ static const uint64_t kSignificandMask = UINT64_2PART_C(0x000FFFFF, FFFFFFFF);
+ static const uint64_t kHiddenBit = UINT64_2PART_C(0x00100000, 00000000);
+ static const int kPhysicalSignificandSize = 52; // Excludes the hidden bit.
+ static const int kSignificandSize = 53;
+
+ Double() : d64_(0) {}
+ explicit Double(double d) : d64_(double_to_uint64(d)) {}
+ explicit Double(uint64_t d64) : d64_(d64) {}
+ explicit Double(DiyFp diy_fp)
+ : d64_(DiyFpToUint64(diy_fp)) {}
+
+ // The value encoded by this Double must be greater or equal to +0.0.
+ // It must not be special (infinity, or NaN).
+ DiyFp AsDiyFp() const {
+ ASSERT(Sign() > 0);
+ ASSERT(!IsSpecial());
+ return DiyFp(Significand(), Exponent());
+ }
+
+ // The value encoded by this Double must be strictly greater than 0.
+ DiyFp AsNormalizedDiyFp() const {
+ ASSERT(value() > 0.0);
+ uint64_t f = Significand();
+ int e = Exponent();
+
+ // The current double could be a denormal.
+ while ((f & kHiddenBit) == 0) {
+ f <<= 1;
+ e--;
+ }
+ // Do the final shifts in one go.
+ f <<= DiyFp::kSignificandSize - kSignificandSize;
+ e -= DiyFp::kSignificandSize - kSignificandSize;
+ return DiyFp(f, e);
+ }
+
+ // Returns the double's bit as uint64.
+ uint64_t AsUint64() const {
+ return d64_;
+ }
+
+ // Returns the next greater double. Returns +infinity on input +infinity.
+ double NextDouble() const {
+ if (d64_ == kInfinity) return Double(kInfinity).value();
+ if (Sign() < 0 && Significand() == 0) {
+ // -0.0
+ return 0.0;
+ }
+ if (Sign() < 0) {
+ return Double(d64_ - 1).value();
+ } else {
+ return Double(d64_ + 1).value();
+ }
+ }
+
+ double PreviousDouble() const {
+ if (d64_ == (kInfinity | kSignMask)) return -Double::Infinity();
+ if (Sign() < 0) {
+ return Double(d64_ + 1).value();
+ } else {
+ if (Significand() == 0) return -0.0;
+ return Double(d64_ - 1).value();
+ }
+ }
+
+ int Exponent() const {
+ if (IsDenormal()) return kDenormalExponent;
+
+ uint64_t d64 = AsUint64();
+ int biased_e =
+ static_cast<int>((d64 & kExponentMask) >> kPhysicalSignificandSize);
+ return biased_e - kExponentBias;
+ }
+
+ uint64_t Significand() const {
+ uint64_t d64 = AsUint64();
+ uint64_t significand = d64 & kSignificandMask;
+ if (!IsDenormal()) {
+ return significand + kHiddenBit;
+ } else {
+ return significand;
+ }
+ }
+
+ // Returns true if the double is a denormal.
+ bool IsDenormal() const {
+ uint64_t d64 = AsUint64();
+ return (d64 & kExponentMask) == 0;
+ }
+
+ // We consider denormals not to be special.
+ // Hence only Infinity and NaN are special.
+ bool IsSpecial() const {
+ uint64_t d64 = AsUint64();
+ return (d64 & kExponentMask) == kExponentMask;
+ }
+
+ bool IsNan() const {
+ uint64_t d64 = AsUint64();
+ return ((d64 & kExponentMask) == kExponentMask) &&
+ ((d64 & kSignificandMask) != 0);
+ }
+
+ bool IsInfinite() const {
+ uint64_t d64 = AsUint64();
+ return ((d64 & kExponentMask) == kExponentMask) &&
+ ((d64 & kSignificandMask) == 0);
+ }
+
+ int Sign() const {
+ uint64_t d64 = AsUint64();
+ return (d64 & kSignMask) == 0? 1: -1;
+ }
+
+ // Precondition: the value encoded by this Double must be greater or equal
+ // than +0.0.
+ DiyFp UpperBoundary() const {
+ ASSERT(Sign() > 0);
+ return DiyFp(Significand() * 2 + 1, Exponent() - 1);
+ }
+
+ // Computes the two boundaries of this.
+ // The bigger boundary (m_plus) is normalized. The lower boundary has the same
+ // exponent as m_plus.
+ // Precondition: the value encoded by this Double must be greater than 0.
+ void NormalizedBoundaries(DiyFp* out_m_minus, DiyFp* out_m_plus) const {
+ ASSERT(value() > 0.0);
+ DiyFp v = this->AsDiyFp();
+ DiyFp m_plus = DiyFp::Normalize(DiyFp((v.f() << 1) + 1, v.e() - 1));
+ DiyFp m_minus;
+ if (LowerBoundaryIsCloser()) {
+ m_minus = DiyFp((v.f() << 2) - 1, v.e() - 2);
+ } else {
+ m_minus = DiyFp((v.f() << 1) - 1, v.e() - 1);
+ }
+ m_minus.set_f(m_minus.f() << (m_minus.e() - m_plus.e()));
+ m_minus.set_e(m_plus.e());
+ *out_m_plus = m_plus;
+ *out_m_minus = m_minus;
+ }
+
+ bool LowerBoundaryIsCloser() const {
+ // The boundary is closer if the significand is of the form f == 2^p-1 then
+ // the lower boundary is closer.
+ // Think of v = 1000e10 and v- = 9999e9.
+ // Then the boundary (== (v - v-)/2) is not just at a distance of 1e9 but
+ // at a distance of 1e8.
+ // The only exception is for the smallest normal: the largest denormal is
+ // at the same distance as its successor.
+ // Note: denormals have the same exponent as the smallest normals.
+ bool physical_significand_is_zero = ((AsUint64() & kSignificandMask) == 0);
+ return physical_significand_is_zero && (Exponent() != kDenormalExponent);
+ }
+
+ double value() const { return uint64_to_double(d64_); }
+
+ // Returns the significand size for a given order of magnitude.
+ // If v = f*2^e with 2^p-1 <= f <= 2^p then p+e is v's order of magnitude.
+ // This function returns the number of significant binary digits v will have
+ // once it's encoded into a double. In almost all cases this is equal to
+ // kSignificandSize. The only exceptions are denormals. They start with
+ // leading zeroes and their effective significand-size is hence smaller.
+ static int SignificandSizeForOrderOfMagnitude(int order) {
+ if (order >= (kDenormalExponent + kSignificandSize)) {
+ return kSignificandSize;
+ }
+ if (order <= kDenormalExponent) return 0;
+ return order - kDenormalExponent;
+ }
+
+ static double Infinity() {
+ return Double(kInfinity).value();
+ }
+
+ static double NaN() {
+ return Double(kNaN).value();
+ }
+
+ private:
+ static const int kExponentBias = 0x3FF + kPhysicalSignificandSize;
+ static const int kDenormalExponent = -kExponentBias + 1;
+ static const int kMaxExponent = 0x7FF - kExponentBias;
+ static const uint64_t kInfinity = UINT64_2PART_C(0x7FF00000, 00000000);
+ static const uint64_t kNaN = UINT64_2PART_C(0x7FF80000, 00000000);
+
+ const uint64_t d64_;
+
+ static uint64_t DiyFpToUint64(DiyFp diy_fp) {
+ uint64_t significand = diy_fp.f();
+ int exponent = diy_fp.e();
+ while (significand > kHiddenBit + kSignificandMask) {
+ significand >>= 1;
+ exponent++;
+ }
+ if (exponent >= kMaxExponent) {
+ return kInfinity;
+ }
+ if (exponent < kDenormalExponent) {
+ return 0;
+ }
+ while (exponent > kDenormalExponent && (significand & kHiddenBit) == 0) {
+ significand <<= 1;
+ exponent--;
+ }
+ uint64_t biased_exponent;
+ if (exponent == kDenormalExponent && (significand & kHiddenBit) == 0) {
+ biased_exponent = 0;
+ } else {
+ biased_exponent = static_cast<uint64_t>(exponent + kExponentBias);
+ }
+ return (significand & kSignificandMask) |
+ (biased_exponent << kPhysicalSignificandSize);
+ }
+};
+
+class Single {
+ public:
+ static const uint32_t kSignMask = 0x80000000;
+ static const uint32_t kExponentMask = 0x7F800000;
+ static const uint32_t kSignificandMask = 0x007FFFFF;
+ static const uint32_t kHiddenBit = 0x00800000;
+ static const int kPhysicalSignificandSize = 23; // Excludes the hidden bit.
+ static const int kSignificandSize = 24;
+
+ Single() : d32_(0) {}
+ explicit Single(float f) : d32_(float_to_uint32(f)) {}
+ explicit Single(uint32_t d32) : d32_(d32) {}
+
+ // The value encoded by this Single must be greater or equal to +0.0.
+ // It must not be special (infinity, or NaN).
+ DiyFp AsDiyFp() const {
+ ASSERT(Sign() > 0);
+ ASSERT(!IsSpecial());
+ return DiyFp(Significand(), Exponent());
+ }
+
+ // Returns the single's bit as uint64.
+ uint32_t AsUint32() const {
+ return d32_;
+ }
+
+ int Exponent() const {
+ if (IsDenormal()) return kDenormalExponent;
+
+ uint32_t d32 = AsUint32();
+ int biased_e =
+ static_cast<int>((d32 & kExponentMask) >> kPhysicalSignificandSize);
+ return biased_e - kExponentBias;
+ }
+
+ uint32_t Significand() const {
+ uint32_t d32 = AsUint32();
+ uint32_t significand = d32 & kSignificandMask;
+ if (!IsDenormal()) {
+ return significand + kHiddenBit;
+ } else {
+ return significand;
+ }
+ }
+
+ // Returns true if the single is a denormal.
+ bool IsDenormal() const {
+ uint32_t d32 = AsUint32();
+ return (d32 & kExponentMask) == 0;
+ }
+
+ // We consider denormals not to be special.
+ // Hence only Infinity and NaN are special.
+ bool IsSpecial() const {
+ uint32_t d32 = AsUint32();
+ return (d32 & kExponentMask) == kExponentMask;
+ }
+
+ bool IsNan() const {
+ uint32_t d32 = AsUint32();
+ return ((d32 & kExponentMask) == kExponentMask) &&
+ ((d32 & kSignificandMask) != 0);
+ }
+
+ bool IsInfinite() const {
+ uint32_t d32 = AsUint32();
+ return ((d32 & kExponentMask) == kExponentMask) &&
+ ((d32 & kSignificandMask) == 0);
+ }
+
+ int Sign() const {
+ uint32_t d32 = AsUint32();
+ return (d32 & kSignMask) == 0? 1: -1;
+ }
+
+ // Computes the two boundaries of this.
+ // The bigger boundary (m_plus) is normalized. The lower boundary has the same
+ // exponent as m_plus.
+ // Precondition: the value encoded by this Single must be greater than 0.
+ void NormalizedBoundaries(DiyFp* out_m_minus, DiyFp* out_m_plus) const {
+ ASSERT(value() > 0.0);
+ DiyFp v = this->AsDiyFp();
+ DiyFp m_plus = DiyFp::Normalize(DiyFp((v.f() << 1) + 1, v.e() - 1));
+ DiyFp m_minus;
+ if (LowerBoundaryIsCloser()) {
+ m_minus = DiyFp((v.f() << 2) - 1, v.e() - 2);
+ } else {
+ m_minus = DiyFp((v.f() << 1) - 1, v.e() - 1);
+ }
+ m_minus.set_f(m_minus.f() << (m_minus.e() - m_plus.e()));
+ m_minus.set_e(m_plus.e());
+ *out_m_plus = m_plus;
+ *out_m_minus = m_minus;
+ }
+
+ // Precondition: the value encoded by this Single must be greater or equal
+ // than +0.0.
+ DiyFp UpperBoundary() const {
+ ASSERT(Sign() > 0);
+ return DiyFp(Significand() * 2 + 1, Exponent() - 1);
+ }
+
+ bool LowerBoundaryIsCloser() const {
+ // The boundary is closer if the significand is of the form f == 2^p-1 then
+ // the lower boundary is closer.
+ // Think of v = 1000e10 and v- = 9999e9.
+ // Then the boundary (== (v - v-)/2) is not just at a distance of 1e9 but
+ // at a distance of 1e8.
+ // The only exception is for the smallest normal: the largest denormal is
+ // at the same distance as its successor.
+ // Note: denormals have the same exponent as the smallest normals.
+ bool physical_significand_is_zero = ((AsUint32() & kSignificandMask) == 0);
+ return physical_significand_is_zero && (Exponent() != kDenormalExponent);
+ }
+
+ float value() const { return uint32_to_float(d32_); }
+
+ static float Infinity() {
+ return Single(kInfinity).value();
+ }
+
+ static float NaN() {
+ return Single(kNaN).value();
+ }
+
+ private:
+ static const int kExponentBias = 0x7F + kPhysicalSignificandSize;
+ static const int kDenormalExponent = -kExponentBias + 1;
+ static const int kMaxExponent = 0xFF - kExponentBias;
+ static const uint32_t kInfinity = 0x7F800000;
+ static const uint32_t kNaN = 0x7FC00000;
+
+ const uint32_t d32_;
+};
+
+} // namespace double_conversion
+
+#endif // DOUBLE_CONVERSION_DOUBLE_H_
diff --git a/mfbt/double-conversion/strtod.cc b/mfbt/double-conversion/strtod.cc
new file mode 100644
index 0000000..9758989
--- /dev/null
+++ b/mfbt/double-conversion/strtod.cc
@@ -0,0 +1,554 @@
+// Copyright 2010 the V8 project authors. All rights reserved.
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+// * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+// * 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.
+// * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived
+// from this software without specific prior written permission.
+//
+// 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.
+
+#include <stdarg.h>
+#include <limits.h>
+
+#include "strtod.h"
+#include "bignum.h"
+#include "cached-powers.h"
+#include "ieee.h"
+
+namespace double_conversion {
+
+// 2^53 = 9007199254740992.
+// Any integer with at most 15 decimal digits will hence fit into a double
+// (which has a 53bit significand) without loss of precision.
+static const int kMaxExactDoubleIntegerDecimalDigits = 15;
+// 2^64 = 18446744073709551616 > 10^19
+static const int kMaxUint64DecimalDigits = 19;
+
+// Max double: 1.7976931348623157 x 10^308
+// Min non-zero double: 4.9406564584124654 x 10^-324
+// Any x >= 10^309 is interpreted as +infinity.
+// Any x <= 10^-324 is interpreted as 0.
+// Note that 2.5e-324 (despite being smaller than the min double) will be read
+// as non-zero (equal to the min non-zero double).
+static const int kMaxDecimalPower = 309;
+static const int kMinDecimalPower = -324;
+
+// 2^64 = 18446744073709551616
+static const uint64_t kMaxUint64 = UINT64_2PART_C(0xFFFFFFFF, FFFFFFFF);
+
+
+static const double exact_powers_of_ten[] = {
+ 1.0, // 10^0
+ 10.0,
+ 100.0,
+ 1000.0,
+ 10000.0,
+ 100000.0,
+ 1000000.0,
+ 10000000.0,
+ 100000000.0,
+ 1000000000.0,
+ 10000000000.0, // 10^10
+ 100000000000.0,
+ 1000000000000.0,
+ 10000000000000.0,
+ 100000000000000.0,
+ 1000000000000000.0,
+ 10000000000000000.0,
+ 100000000000000000.0,
+ 1000000000000000000.0,
+ 10000000000000000000.0,
+ 100000000000000000000.0, // 10^20
+ 1000000000000000000000.0,
+ // 10^22 = 0x21e19e0c9bab2400000 = 0x878678326eac9 * 2^22
+ 10000000000000000000000.0
+};
+static const int kExactPowersOfTenSize = ARRAY_SIZE(exact_powers_of_ten);
+
+// Maximum number of significant digits in the decimal representation.
+// In fact the value is 772 (see conversions.cc), but to give us some margin
+// we round up to 780.
+static const int kMaxSignificantDecimalDigits = 780;
+
+static Vector<const char> TrimLeadingZeros(Vector<const char> buffer) {
+ for (int i = 0; i < buffer.length(); i++) {
+ if (buffer[i] != '0') {
+ return buffer.SubVector(i, buffer.length());
+ }
+ }
+ return Vector<const char>(buffer.start(), 0);
+}
+
+
+static Vector<const char> TrimTrailingZeros(Vector<const char> buffer) {
+ for (int i = buffer.length() - 1; i >= 0; --i) {
+ if (buffer[i] != '0') {
+ return buffer.SubVector(0, i + 1);
+ }
+ }
+ return Vector<const char>(buffer.start(), 0);
+}
+
+
+static void CutToMaxSignificantDigits(Vector<const char> buffer,
+ int exponent,
+ char* significant_buffer,
+ int* significant_exponent) {
+ for (int i = 0; i < kMaxSignificantDecimalDigits - 1; ++i) {
+ significant_buffer[i] = buffer[i];
+ }
+ // The input buffer has been trimmed. Therefore the last digit must be
+ // different from '0'.
+ ASSERT(buffer[buffer.length() - 1] != '0');
+ // Set the last digit to be non-zero. This is sufficient to guarantee
+ // correct rounding.
+ significant_buffer[kMaxSignificantDecimalDigits - 1] = '1';
+ *significant_exponent =
+ exponent + (buffer.length() - kMaxSignificantDecimalDigits);
+}
+
+
+// Trims the buffer and cuts it to at most kMaxSignificantDecimalDigits.
+// If possible the input-buffer is reused, but if the buffer needs to be
+// modified (due to cutting), then the input needs to be copied into the
+// buffer_copy_space.
+static void TrimAndCut(Vector<const char> buffer, int exponent,
+ char* buffer_copy_space, int space_size,
+ Vector<const char>* trimmed, int* updated_exponent) {
+ Vector<const char> left_trimmed = TrimLeadingZeros(buffer);
+ Vector<const char> right_trimmed = TrimTrailingZeros(left_trimmed);
+ exponent += left_trimmed.length() - right_trimmed.length();
+ if (right_trimmed.length() > kMaxSignificantDecimalDigits) {
+ ASSERT(space_size >= kMaxSignificantDecimalDigits);
+ CutToMaxSignificantDigits(right_trimmed, exponent,
+ buffer_copy_space, updated_exponent);
+ *trimmed = Vector<const char>(buffer_copy_space,
+ kMaxSignificantDecimalDigits);
+ } else {
+ *trimmed = right_trimmed;
+ *updated_exponent = exponent;
+ }
+}
+
+
+// Reads digits from the buffer and converts them to a uint64.
+// Reads in as many digits as fit into a uint64.
+// When the string starts with "1844674407370955161" no further digit is read.
+// Since 2^64 = 18446744073709551616 it would still be possible read another
+// digit if it was less or equal than 6, but this would complicate the code.
+static uint64_t ReadUint64(Vector<const char> buffer,
+ int* number_of_read_digits) {
+ uint64_t result = 0;
+ int i = 0;
+ while (i < buffer.length() && result <= (kMaxUint64 / 10 - 1)) {
+ int digit = buffer[i++] - '0';
+ ASSERT(0 <= digit && digit <= 9);
+ result = 10 * result + digit;
+ }
+ *number_of_read_digits = i;
+ return result;
+}
+
+
+// Reads a DiyFp from the buffer.
+// The returned DiyFp is not necessarily normalized.
+// If remaining_decimals is zero then the returned DiyFp is accurate.
+// Otherwise it has been rounded and has error of at most 1/2 ulp.
+static void ReadDiyFp(Vector<const char> buffer,
+ DiyFp* result,
+ int* remaining_decimals) {
+ int read_digits;
+ uint64_t significand = ReadUint64(buffer, &read_digits);
+ if (buffer.length() == read_digits) {
+ *result = DiyFp(significand, 0);
+ *remaining_decimals = 0;
+ } else {
+ // Round the significand.
+ if (buffer[read_digits] >= '5') {
+ significand++;
+ }
+ // Compute the binary exponent.
+ int exponent = 0;
+ *result = DiyFp(significand, exponent);
+ *remaining_decimals = buffer.length() - read_digits;
+ }
+}
+
+
+static bool DoubleStrtod(Vector<const char> trimmed,
+ int exponent,
+ double* result) {
+#if !defined(DOUBLE_CONVERSION_CORRECT_DOUBLE_OPERATIONS)
+ // On x86 the floating-point stack can be 64 or 80 bits wide. If it is
+ // 80 bits wide (as is the case on Linux) then double-rounding occurs and the
+ // result is not accurate.
+ // We know that Windows32 uses 64 bits and is therefore accurate.
+ // Note that the ARM simulator is compiled for 32bits. It therefore exhibits
+ // the same problem.
+ return false;
+#endif
+ if (trimmed.length() <= kMaxExactDoubleIntegerDecimalDigits) {
+ int read_digits;
+ // The trimmed input fits into a double.
+ // If the 10^exponent (resp. 10^-exponent) fits into a double too then we
+ // can compute the result-double simply by multiplying (resp. dividing) the
+ // two numbers.
+ // This is possible because IEEE guarantees that floating-point operations
+ // return the best possible approximation.
+ if (exponent < 0 && -exponent < kExactPowersOfTenSize) {
+ // 10^-exponent fits into a double.
+ *result = static_cast<double>(ReadUint64(trimmed, &read_digits));
+ ASSERT(read_digits == trimmed.length());
+ *result /= exact_powers_of_ten[-exponent];
+ return true;
+ }
+ if (0 <= exponent && exponent < kExactPowersOfTenSize) {
+ // 10^exponent fits into a double.
+ *result = static_cast<double>(ReadUint64(trimmed, &read_digits));
+ ASSERT(read_digits == trimmed.length());
+ *result *= exact_powers_of_ten[exponent];
+ return true;
+ }
+ int remaining_digits =
+ kMaxExactDoubleIntegerDecimalDigits - trimmed.length();
+ if ((0 <= exponent) &&
+ (exponent - remaining_digits < kExactPowersOfTenSize)) {
+ // The trimmed string was short and we can multiply it with
+ // 10^remaining_digits. As a result the remaining exponent now fits
+ // into a double too.
+ *result = static_cast<double>(ReadUint64(trimmed, &read_digits));
+ ASSERT(read_digits == trimmed.length());
+ *result *= exact_powers_of_ten[remaining_digits];
+ *result *= exact_powers_of_ten[exponent - remaining_digits];
+ return true;
+ }
+ }
+ return false;
+}
+
+
+// Returns 10^exponent as an exact DiyFp.
+// The given exponent must be in the range [1; kDecimalExponentDistance[.
+static DiyFp AdjustmentPowerOfTen(int exponent) {
+ ASSERT(0 < exponent);
+ ASSERT(exponent < PowersOfTenCache::kDecimalExponentDistance);
+ // Simply hardcode the remaining powers for the given decimal exponent
+ // distance.
+ ASSERT(PowersOfTenCache::kDecimalExponentDistance == 8);
+ switch (exponent) {
+ case 1: return DiyFp(UINT64_2PART_C(0xa0000000, 00000000), -60);
+ case 2: return DiyFp(UINT64_2PART_C(0xc8000000, 00000000), -57);
+ case 3: return DiyFp(UINT64_2PART_C(0xfa000000, 00000000), -54);
+ case 4: return DiyFp(UINT64_2PART_C(0x9c400000, 00000000), -50);
+ case 5: return DiyFp(UINT64_2PART_C(0xc3500000, 00000000), -47);
+ case 6: return DiyFp(UINT64_2PART_C(0xf4240000, 00000000), -44);
+ case 7: return DiyFp(UINT64_2PART_C(0x98968000, 00000000), -40);
+ default:
+ UNREACHABLE();
+ return DiyFp(0, 0);
+ }
+}
+
+
+// If the function returns true then the result is the correct double.
+// Otherwise it is either the correct double or the double that is just below
+// the correct double.
+static bool DiyFpStrtod(Vector<const char> buffer,
+ int exponent,
+ double* result) {
+ DiyFp input;
+ int remaining_decimals;
+ ReadDiyFp(buffer, &input, &remaining_decimals);
+ // Since we may have dropped some digits the input is not accurate.
+ // If remaining_decimals is different than 0 than the error is at most
+ // .5 ulp (unit in the last place).
+ // We don't want to deal with fractions and therefore keep a common
+ // denominator.
+ const int kDenominatorLog = 3;
+ const int kDenominator = 1 << kDenominatorLog;
+ // Move the remaining decimals into the exponent.
+ exponent += remaining_decimals;
+ int error = (remaining_decimals == 0 ? 0 : kDenominator / 2);
+
+ int old_e = input.e();
+ input.Normalize();
+ error <<= old_e - input.e();
+
+ ASSERT(exponent <= PowersOfTenCache::kMaxDecimalExponent);
+ if (exponent < PowersOfTenCache::kMinDecimalExponent) {
+ *result = 0.0;
+ return true;
+ }
+ DiyFp cached_power;
+ int cached_decimal_exponent;
+ PowersOfTenCache::GetCachedPowerForDecimalExponent(exponent,
+ &cached_power,
+ &cached_decimal_exponent);
+
+ if (cached_decimal_exponent != exponent) {
+ int adjustment_exponent = exponent - cached_decimal_exponent;
+ DiyFp adjustment_power = AdjustmentPowerOfTen(adjustment_exponent);
+ input.Multiply(adjustment_power);
+ if (kMaxUint64DecimalDigits - buffer.length() >= adjustment_exponent) {
+ // The product of input with the adjustment power fits into a 64 bit
+ // integer.
+ ASSERT(DiyFp::kSignificandSize == 64);
+ } else {
+ // The adjustment power is exact. There is hence only an error of 0.5.
+ error += kDenominator / 2;
+ }
+ }
+
+ input.Multiply(cached_power);
+ // The error introduced by a multiplication of a*b equals
+ // error_a + error_b + error_a*error_b/2^64 + 0.5
+ // Substituting a with 'input' and b with 'cached_power' we have
+ // error_b = 0.5 (all cached powers have an error of less than 0.5 ulp),
+ // error_ab = 0 or 1 / kDenominator > error_a*error_b/ 2^64
+ int error_b = kDenominator / 2;
+ int error_ab = (error == 0 ? 0 : 1); // We round up to 1.
+ int fixed_error = kDenominator / 2;
+ error += error_b + error_ab + fixed_error;
+
+ old_e = input.e();
+ input.Normalize();
+ error <<= old_e - input.e();
+
+ // See if the double's significand changes if we add/subtract the error.
+ int order_of_magnitude = DiyFp::kSignificandSize + input.e();
+ int effective_significand_size =
+ Double::SignificandSizeForOrderOfMagnitude(order_of_magnitude);
+ int precision_digits_count =
+ DiyFp::kSignificandSize - effective_significand_size;
+ if (precision_digits_count + kDenominatorLog >= DiyFp::kSignificandSize) {
+ // This can only happen for very small denormals. In this case the
+ // half-way multiplied by the denominator exceeds the range of an uint64.
+ // Simply shift everything to the right.
+ int shift_amount = (precision_digits_count + kDenominatorLog) -
+ DiyFp::kSignificandSize + 1;
+ input.set_f(input.f() >> shift_amount);
+ input.set_e(input.e() + shift_amount);
+ // We add 1 for the lost precision of error, and kDenominator for
+ // the lost precision of input.f().
+ error = (error >> shift_amount) + 1 + kDenominator;
+ precision_digits_count -= shift_amount;
+ }
+ // We use uint64_ts now. This only works if the DiyFp uses uint64_ts too.
+ ASSERT(DiyFp::kSignificandSize == 64);
+ ASSERT(precision_digits_count < 64);
+ uint64_t one64 = 1;
+ uint64_t precision_bits_mask = (one64 << precision_digits_count) - 1;
+ uint64_t precision_bits = input.f() & precision_bits_mask;
+ uint64_t half_way = one64 << (precision_digits_count - 1);
+ precision_bits *= kDenominator;
+ half_way *= kDenominator;
+ DiyFp rounded_input(input.f() >> precision_digits_count,
+ input.e() + precision_digits_count);
+ if (precision_bits >= half_way + error) {
+ rounded_input.set_f(rounded_input.f() + 1);
+ }
+ // If the last_bits are too close to the half-way case than we are too
+ // inaccurate and round down. In this case we return false so that we can
+ // fall back to a more precise algorithm.
+
+ *result = Double(rounded_input).value();
+ if (half_way - error < precision_bits && precision_bits < half_way + error) {
+ // Too imprecise. The caller will have to fall back to a slower version.
+ // However the returned number is guaranteed to be either the correct
+ // double, or the next-lower double.
+ return false;
+ } else {
+ return true;
+ }
+}
+
+
+// Returns
+// - -1 if buffer*10^exponent < diy_fp.
+// - 0 if buffer*10^exponent == diy_fp.
+// - +1 if buffer*10^exponent > diy_fp.
+// Preconditions:
+// buffer.length() + exponent <= kMaxDecimalPower + 1
+// buffer.length() + exponent > kMinDecimalPower
+// buffer.length() <= kMaxDecimalSignificantDigits
+static int CompareBufferWithDiyFp(Vector<const char> buffer,
+ int exponent,
+ DiyFp diy_fp) {
+ ASSERT(buffer.length() + exponent <= kMaxDecimalPower + 1);
+ ASSERT(buffer.length() + exponent > kMinDecimalPower);
+ ASSERT(buffer.length() <= kMaxSignificantDecimalDigits);
+ // Make sure that the Bignum will be able to hold all our numbers.
+ // Our Bignum implementation has a separate field for exponents. Shifts will
+ // consume at most one bigit (< 64 bits).
+ // ln(10) == 3.3219...
+ ASSERT(((kMaxDecimalPower + 1) * 333 / 100) < Bignum::kMaxSignificantBits);
+ Bignum buffer_bignum;
+ Bignum diy_fp_bignum;
+ buffer_bignum.AssignDecimalString(buffer);
+ diy_fp_bignum.AssignUInt64(diy_fp.f());
+ if (exponent >= 0) {
+ buffer_bignum.MultiplyByPowerOfTen(exponent);
+ } else {
+ diy_fp_bignum.MultiplyByPowerOfTen(-exponent);
+ }
+ if (diy_fp.e() > 0) {
+ diy_fp_bignum.ShiftLeft(diy_fp.e());
+ } else {
+ buffer_bignum.ShiftLeft(-diy_fp.e());
+ }
+ return Bignum::Compare(buffer_bignum, diy_fp_bignum);
+}
+
+
+// Returns true if the guess is the correct double.
+// Returns false, when guess is either correct or the next-lower double.
+static bool ComputeGuess(Vector<const char> trimmed, int exponent,
+ double* guess) {
+ if (trimmed.length() == 0) {
+ *guess = 0.0;
+ return true;
+ }
+ if (exponent + trimmed.length() - 1 >= kMaxDecimalPower) {
+ *guess = Double::Infinity();
+ return true;
+ }
+ if (exponent + trimmed.length() <= kMinDecimalPower) {
+ *guess = 0.0;
+ return true;
+ }
+
+ if (DoubleStrtod(trimmed, exponent, guess) ||
+ DiyFpStrtod(trimmed, exponent, guess)) {
+ return true;
+ }
+ if (*guess == Double::Infinity()) {
+ return true;
+ }
+ return false;
+}
+
+double Strtod(Vector<const char> buffer, int exponent) {
+ char copy_buffer[kMaxSignificantDecimalDigits];
+ Vector<const char> trimmed;
+ int updated_exponent;
+ TrimAndCut(buffer, exponent, copy_buffer, kMaxSignificantDecimalDigits,
+ &trimmed, &updated_exponent);
+ exponent = updated_exponent;
+
+ double guess;
+ bool is_correct = ComputeGuess(trimmed, exponent, &guess);
+ if (is_correct) return guess;
+
+ DiyFp upper_boundary = Double(guess).UpperBoundary();
+ int comparison = CompareBufferWithDiyFp(trimmed, exponent, upper_boundary);
+ if (comparison < 0) {
+ return guess;
+ } else if (comparison > 0) {
+ return Double(guess).NextDouble();
+ } else if ((Double(guess).Significand() & 1) == 0) {
+ // Round towards even.
+ return guess;
+ } else {
+ return Double(guess).NextDouble();
+ }
+}
+
+float Strtof(Vector<const char> buffer, int exponent) {
+ char copy_buffer[kMaxSignificantDecimalDigits];
+ Vector<const char> trimmed;
+ int updated_exponent;
+ TrimAndCut(buffer, exponent, copy_buffer, kMaxSignificantDecimalDigits,
+ &trimmed, &updated_exponent);
+ exponent = updated_exponent;
+
+ double double_guess;
+ bool is_correct = ComputeGuess(trimmed, exponent, &double_guess);
+
+ float float_guess = static_cast<float>(double_guess);
+ if (float_guess == double_guess) {
+ // This shortcut triggers for integer values.
+ return float_guess;
+ }
+
+ // We must catch double-rounding. Say the double has been rounded up, and is
+ // now a boundary of a float, and rounds up again. This is why we have to
+ // look at previous too.
+ // Example (in decimal numbers):
+ // input: 12349
+ // high-precision (4 digits): 1235
+ // low-precision (3 digits):
+ // when read from input: 123
+ // when rounded from high precision: 124.
+ // To do this we simply look at the neigbors of the correct result and see
+ // if they would round to the same float. If the guess is not correct we have
+ // to look at four values (since two different doubles could be the correct
+ // double).
+
+ double double_next = Double(double_guess).NextDouble();
+ double double_previous = Double(double_guess).PreviousDouble();
+
+ float f1 = static_cast<float>(double_previous);
+ float f2 = float_guess;
+ float f3 = static_cast<float>(double_next);
+ float f4;
+ if (is_correct) {
+ f4 = f3;
+ } else {
+ double double_next2 = Double(double_next).NextDouble();
+ f4 = static_cast<float>(double_next2);
+ }
+ ASSERT(f1 <= f2 && f2 <= f3 && f3 <= f4);
+
+ // If the guess doesn't lie near a single-precision boundary we can simply
+ // return its float-value.
+ if (f1 == f4) {
+ return float_guess;
+ }
+
+ ASSERT((f1 != f2 && f2 == f3 && f3 == f4) ||
+ (f1 == f2 && f2 != f3 && f3 == f4) ||
+ (f1 == f2 && f2 == f3 && f3 != f4));
+
+ // guess and next are the two possible canditates (in the same way that
+ // double_guess was the lower candidate for a double-precision guess).
+ float guess = f1;
+ float next = f4;
+ DiyFp upper_boundary;
+ if (guess == 0.0f) {
+ float min_float = 1e-45f;
+ upper_boundary = Double(static_cast<double>(min_float) / 2).AsDiyFp();
+ } else {
+ upper_boundary = Single(guess).UpperBoundary();
+ }
+ int comparison = CompareBufferWithDiyFp(trimmed, exponent, upper_boundary);
+ if (comparison < 0) {
+ return guess;
+ } else if (comparison > 0) {
+ return next;
+ } else if ((Single(guess).Significand() & 1) == 0) {
+ // Round towards even.
+ return guess;
+ } else {
+ return next;
+ }
+}
+
+} // namespace double_conversion
diff --git a/mfbt/double-conversion/strtod.h b/mfbt/double-conversion/strtod.h
new file mode 100644
index 0000000..ed0293b
--- /dev/null
+++ b/mfbt/double-conversion/strtod.h
@@ -0,0 +1,45 @@
+// Copyright 2010 the V8 project authors. All rights reserved.
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+// * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+// * 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.
+// * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived
+// from this software without specific prior written permission.
+//
+// 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.
+
+#ifndef DOUBLE_CONVERSION_STRTOD_H_
+#define DOUBLE_CONVERSION_STRTOD_H_
+
+#include "utils.h"
+
+namespace double_conversion {
+
+// The buffer must only contain digits in the range [0-9]. It must not
+// contain a dot or a sign. It must not start with '0', and must not be empty.
+double Strtod(Vector<const char> buffer, int exponent);
+
+// The buffer must only contain digits in the range [0-9]. It must not
+// contain a dot or a sign. It must not start with '0', and must not be empty.
+float Strtof(Vector<const char> buffer, int exponent);
+
+} // namespace double_conversion
+
+#endif // DOUBLE_CONVERSION_STRTOD_H_
diff --git a/mfbt/double-conversion/update.sh b/mfbt/double-conversion/update.sh
new file mode 100755
index 0000000..43091e3
--- /dev/null
+++ b/mfbt/double-conversion/update.sh
@@ -0,0 +1,20 @@
+# Usage: ./update.sh <double-conversion-src-directory>
+#
+# Copies the needed files from a directory containing the original
+# double-conversion source that we need.
+
+# This was last updated with git rev e5b34421b763f7bf7e4f9081403db417d5a55a36.
+
+set -e
+
+cp $1/LICENSE ./
+cp $1/README ./
+
+# Includes
+cp $1/src/*.h ./
+
+# Source
+cp $1/src/*.cc ./
+
+patch -p3 < add-mfbt-api-markers.patch
+patch -p3 < use-StandardInteger.patch
diff --git a/mfbt/double-conversion/use-StandardInteger.patch b/mfbt/double-conversion/use-StandardInteger.patch
new file mode 100644
index 0000000..6cd49b3
--- /dev/null
+++ b/mfbt/double-conversion/use-StandardInteger.patch
@@ -0,0 +1,29 @@
+diff --git a/mfbt/double-conversion/utils.h b/mfbt/double-conversion/utils.h
+index cd3e330..bdc7d4b 100644
+--- a/mfbt/double-conversion/utils.h
++++ b/mfbt/double-conversion/utils.h
+@@ -68,23 +68,7 @@
+ #endif
+
+
+-#if defined(_WIN32) && !defined(__MINGW32__)
+-
+-typedef signed char int8_t;
+-typedef unsigned char uint8_t;
+-typedef short int16_t; // NOLINT
+-typedef unsigned short uint16_t; // NOLINT
+-typedef int int32_t;
+-typedef unsigned int uint32_t;
+-typedef __int64 int64_t;
+-typedef unsigned __int64 uint64_t;
+-// intptr_t and friends are defined in crtdefs.h through stdio.h.
+-
+-#else
+-
+-#include <stdint.h>
+-
+-#endif
++#include "mozilla/StandardInteger.h"
+
+ // The following macro works on both 32 and 64-bit platforms.
+ // Usage: instead of writing 0x1234567890123456
diff --git a/mfbt/double-conversion/utils.h b/mfbt/double-conversion/utils.h
new file mode 100644
index 0000000..0eec2d9
--- /dev/null
+++ b/mfbt/double-conversion/utils.h
@@ -0,0 +1,297 @@
+// Copyright 2010 the V8 project authors. All rights reserved.
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+// * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+// * 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.
+// * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived
+// from this software without specific prior written permission.
+//
+// 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.
+
+#ifndef DOUBLE_CONVERSION_UTILS_H_
+#define DOUBLE_CONVERSION_UTILS_H_
+
+#include <stdlib.h>
+#include <string.h>
+
+#include <assert.h>
+#ifndef ASSERT
+#define ASSERT(condition) (assert(condition))
+#endif
+#ifndef UNIMPLEMENTED
+#define UNIMPLEMENTED() (abort())
+#endif
+#ifndef UNREACHABLE
+#define UNREACHABLE() (abort())
+#endif
+
+// Double operations detection based on target architecture.
+// Linux uses a 80bit wide floating point stack on x86. This induces double
+// rounding, which in turn leads to wrong results.
+// An easy way to test if the floating-point operations are correct is to
+// evaluate: 89255.0/1e22. If the floating-point stack is 64 bits wide then
+// the result is equal to 89255e-22.
+// The best way to test this, is to create a division-function and to compare
+// the output of the division with the expected result. (Inlining must be
+// disabled.)
+// On Linux,x86 89255e-22 != Div_double(89255.0/1e22)
+#if defined(_M_X64) || defined(__x86_64__) || \
+ defined(__ARMEL__) || defined(__avr32__) || \
+ defined(__hppa__) || defined(__ia64__) || \
+ defined(__mips__) || defined(__powerpc__) || \
+ defined(__sparc__) || defined(__sparc) || defined(__s390__) || \
+ defined(__SH4__) || defined(__alpha__) || \
+ defined(_MIPS_ARCH_MIPS32R2)
+#define DOUBLE_CONVERSION_CORRECT_DOUBLE_OPERATIONS 1
+#elif defined(_M_IX86) || defined(__i386__) || defined(__i386)
+#if defined(_WIN32)
+// Windows uses a 64bit wide floating point stack.
+#define DOUBLE_CONVERSION_CORRECT_DOUBLE_OPERATIONS 1
+#else
+#undef DOUBLE_CONVERSION_CORRECT_DOUBLE_OPERATIONS
+#endif // _WIN32
+#else
+#error Target architecture was not detected as supported by Double-Conversion.
+#endif
+
+
+#include "mozilla/StandardInteger.h"
+
+// The following macro works on both 32 and 64-bit platforms.
+// Usage: instead of writing 0x1234567890123456
+// write UINT64_2PART_C(0x12345678,90123456);
+#define UINT64_2PART_C(a, b) (((static_cast<uint64_t>(a) << 32) + 0x##b##u))
+
+
+// The expression ARRAY_SIZE(a) is a compile-time constant of type
+// size_t which represents the number of elements of the given
+// array. You should only use ARRAY_SIZE on statically allocated
+// arrays.
+#ifndef ARRAY_SIZE
+#define ARRAY_SIZE(a) \
+ ((sizeof(a) / sizeof(*(a))) / \
+ static_cast<size_t>(!(sizeof(a) % sizeof(*(a)))))
+#endif
+
+// A macro to disallow the evil copy constructor and operator= functions
+// This should be used in the private: declarations for a class
+#ifndef DISALLOW_COPY_AND_ASSIGN
+#define DISALLOW_COPY_AND_ASSIGN(TypeName) \
+ TypeName(const TypeName&); \
+ void operator=(const TypeName&)
+#endif
+
+// A macro to disallow all the implicit constructors, namely the
+// default constructor, copy constructor and operator= functions.
+//
+// This should be used in the private: declarations for a class
+// that wants to prevent anyone from instantiating it. This is
+// especially useful for classes containing only static methods.
+#ifndef DISALLOW_IMPLICIT_CONSTRUCTORS
+#define DISALLOW_IMPLICIT_CONSTRUCTORS(TypeName) \
+ TypeName(); \
+ DISALLOW_COPY_AND_ASSIGN(TypeName)
+#endif
+
+namespace double_conversion {
+
+static const int kCharSize = sizeof(char);
+
+// Returns the maximum of the two parameters.
+template <typename T>
+static T Max(T a, T b) {
+ return a < b ? b : a;
+}
+
+
+// Returns the minimum of the two parameters.
+template <typename T>
+static T Min(T a, T b) {
+ return a < b ? a : b;
+}
+
+
+inline int StrLength(const char* string) {
+ size_t length = strlen(string);
+ ASSERT(length == static_cast<size_t>(static_cast<int>(length)));
+ return static_cast<int>(length);
+}
+
+// This is a simplified version of V8's Vector class.
+template <typename T>
+class Vector {
+ public:
+ Vector() : start_(NULL), length_(0) {}
+ Vector(T* data, int length) : start_(data), length_(length) {
+ ASSERT(length == 0 || (length > 0 && data != NULL));
+ }
+
+ // Returns a vector using the same backing storage as this one,
+ // spanning from and including 'from', to but not including 'to'.
+ Vector<T> SubVector(int from, int to) {
+ ASSERT(to <= length_);
+ ASSERT(from < to);
+ ASSERT(0 <= from);
+ return Vector<T>(start() + from, to - from);
+ }
+
+ // Returns the length of the vector.
+ int length() const { return length_; }
+
+ // Returns whether or not the vector is empty.
+ bool is_empty() const { return length_ == 0; }
+
+ // Returns the pointer to the start of the data in the vector.
+ T* start() const { return start_; }
+
+ // Access individual vector elements - checks bounds in debug mode.
+ T& operator[](int index) const {
+ ASSERT(0 <= index && index < length_);
+ return start_[index];
+ }
+
+ T& first() { return start_[0]; }
+
+ T& last() { return start_[length_ - 1]; }
+
+ private:
+ T* start_;
+ int length_;
+};
+
+
+// Helper class for building result strings in a character buffer. The
+// purpose of the class is to use safe operations that checks the
+// buffer bounds on all operations in debug mode.
+class StringBuilder {
+ public:
+ StringBuilder(char* buffer, int size)
+ : buffer_(buffer, size), position_(0) { }
+
+ ~StringBuilder() { if (!is_finalized()) Finalize(); }
+
+ int size() const { return buffer_.length(); }
+
+ // Get the current position in the builder.
+ int position() const {
+ ASSERT(!is_finalized());
+ return position_;
+ }
+
+ // Reset the position.
+ void Reset() { position_ = 0; }
+
+ // Add a single character to the builder. It is not allowed to add
+ // 0-characters; use the Finalize() method to terminate the string
+ // instead.
+ void AddCharacter(char c) {
+ ASSERT(c != '\0');
+ ASSERT(!is_finalized() && position_ < buffer_.length());
+ buffer_[position_++] = c;
+ }
+
+ // Add an entire string to the builder. Uses strlen() internally to
+ // compute the length of the input string.
+ void AddString(const char* s) {
+ AddSubstring(s, StrLength(s));
+ }
+
+ // Add the first 'n' characters of the given string 's' to the
+ // builder. The input string must have enough characters.
+ void AddSubstring(const char* s, int n) {
+ ASSERT(!is_finalized() && position_ + n < buffer_.length());
+ ASSERT(static_cast<size_t>(n) <= strlen(s));
+ memmove(&buffer_[position_], s, n * kCharSize);
+ position_ += n;
+ }
+
+
+ // Add character padding to the builder. If count is non-positive,
+ // nothing is added to the builder.
+ void AddPadding(char c, int count) {
+ for (int i = 0; i < count; i++) {
+ AddCharacter(c);
+ }
+ }
+
+ // Finalize the string by 0-terminating it and returning the buffer.
+ char* Finalize() {
+ ASSERT(!is_finalized() && position_ < buffer_.length());
+ buffer_[position_] = '\0';
+ // Make sure nobody managed to add a 0-character to the
+ // buffer while building the string.
+ ASSERT(strlen(buffer_.start()) == static_cast<size_t>(position_));
+ position_ = -1;
+ ASSERT(is_finalized());
+ return buffer_.start();
+ }
+
+ private:
+ Vector<char> buffer_;
+ int position_;
+
+ bool is_finalized() const { return position_ < 0; }
+
+ DISALLOW_IMPLICIT_CONSTRUCTORS(StringBuilder);
+};
+
+// The type-based aliasing rule allows the compiler to assume that pointers of
+// different types (for some definition of different) never alias each other.
+// Thus the following code does not work:
+//
+// float f = foo();
+// int fbits = *(int*)(&f);
+//
+// The compiler 'knows' that the int pointer can't refer to f since the types
+// don't match, so the compiler may cache f in a register, leaving random data
+// in fbits. Using C++ style casts makes no difference, however a pointer to
+// char data is assumed to alias any other pointer. This is the 'memcpy
+// exception'.
+//
+// Bit_cast uses the memcpy exception to move the bits from a variable of one
+// type of a variable of another type. Of course the end result is likely to
+// be implementation dependent. Most compilers (gcc-4.2 and MSVC 2005)
+// will completely optimize BitCast away.
+//
+// There is an additional use for BitCast.
+// Recent gccs will warn when they see casts that may result in breakage due to
+// the type-based aliasing rule. If you have checked that there is no breakage
+// you can use BitCast to cast one pointer type to another. This confuses gcc
+// enough that it can no longer see that you have cast one pointer type to
+// another thus avoiding the warning.
+template <class Dest, class Source>
+inline Dest BitCast(const Source& source) {
+ // Compile time assertion: sizeof(Dest) == sizeof(Source)
+ // A compile error here means your Dest and Source have different sizes.
+ typedef char VerifySizesAreEqual[sizeof(Dest) == sizeof(Source) ? 1 : -1];
+
+ Dest dest;
+ memmove(&dest, &source, sizeof(dest));
+ return dest;
+}
+
+template <class Dest, class Source>
+inline Dest BitCast(Source* source) {
+ return BitCast<Dest>(reinterpret_cast<uintptr_t>(source));
+}
+
+} // namespace double_conversion
+
+#endif // DOUBLE_CONVERSION_UTILS_H_
diff --git a/mfbt/exported_headers.mk b/mfbt/exported_headers.mk
new file mode 100644
index 0000000..6370936
--- /dev/null
+++ b/mfbt/exported_headers.mk
@@ -0,0 +1,49 @@
+# This Source Code Form is subject to the terms of the Mozilla Public
+# License, v. 2.0. If a copy of the MPL was not distributed with this
+# file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+# This file defines the headers exported by mfbt. It is included by mfbt
+# itself and by the JS engine, which, when built standalone, must install
+# mfbt's exported headers itself.
+
+EXPORTS_NAMESPACES += mozilla
+
+EXPORTS_mozilla += \
+ Assertions.h \
+ Atomics.h \
+ Attributes.h \
+ BloomFilter.h \
+ Casting.h \
+ Char16.h \
+ CheckedInt.h \
+ Compiler.h \
+ Constants.h \
+ DebugOnly.h \
+ decimal/Decimal.h \
+ Endian.h \
+ EnumSet.h \
+ FloatingPoint.h \
+ GuardObjects.h \
+ HashFunctions.h \
+ Likely.h \
+ LinkedList.h \
+ MathAlgorithms.h \
+ MemoryChecking.h \
+ MSStdInt.h \
+ NullPtr.h \
+ PodOperations.h \
+ Poison.h \
+ Range.h \
+ RangedPtr.h \
+ RefPtr.h \
+ Scoped.h \
+ SHA1.h \
+ SplayTree.h \
+ StandardInteger.h \
+ ThreadLocal.h \
+ TypedEnum.h \
+ Types.h \
+ TypeTraits.h \
+ Util.h \
+ WeakPtr.h \
+ $(NULL)
diff --git a/mfbt/moz.build b/mfbt/moz.build
new file mode 100644
index 0000000..9e424bc
--- /dev/null
+++ b/mfbt/moz.build
@@ -0,0 +1,12 @@
+# -*- Mode: python; c-basic-offset: 4; indent-tabs-mode: nil; tab-width: 40 -*-
+# vim: set filetype=python:
+# This Source Code Form is subject to the terms of the Mozilla Public
+# License, v. 2.0. If a copy of the MPL was not distributed with this
+# file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+TEST_DIRS += ['tests']
+
+MODULE = 'mozglue'
+
+LIBRARY_NAME = 'mfbt'
+
diff --git a/mfbt/sources.mk b/mfbt/sources.mk
new file mode 100644
index 0000000..fac20c8
--- /dev/null
+++ b/mfbt/sources.mk
@@ -0,0 +1,37 @@
+# This Source Code Form is subject to the terms of the Mozilla Public
+# License, v. 2.0. If a copy of the MPL was not distributed with this
+# file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+ifndef MFBT_ROOT
+$(error Before including this file, you must define MFBT_ROOT to point to \
+the MFBT source directory)
+endif
+
+CPPSRCS += \
+ HashFunctions.cpp \
+ Poison.cpp \
+ SHA1.cpp \
+ $(NULL)
+
+# Imported double-conversion sources.
+VPATH += $(MFBT_ROOT)/double-conversion \
+ $(NULL)
+
+CPPSRCS += \
+ bignum-dtoa.cc \
+ bignum.cc \
+ cached-powers.cc \
+ diy-fp.cc \
+ double-conversion.cc \
+ fast-dtoa.cc \
+ fixed-dtoa.cc \
+ strtod.cc \
+ $(NULL)
+
+# Imported decimal sources.
+VPATH += $(MFBT_ROOT)/decimal \
+ $(NULL)
+
+CPPSRCS += \
+ Decimal.cpp
+
diff --git a/mfbt/tests/Makefile.in b/mfbt/tests/Makefile.in
new file mode 100644
index 0000000..faac3bc
--- /dev/null
+++ b/mfbt/tests/Makefile.in
@@ -0,0 +1,47 @@
+# This Source Code Form is subject to the terms of the Mozilla Public
+# License, v. 2.0. If a copy of the MPL was not distributed with this file,
+# You can obtain one at http://mozilla.org/MPL/2.0/.
+
+DEPTH = @DEPTH@
+topsrcdir = @top_srcdir@
+srcdir = @srcdir@
+VPATH = @srcdir@
+
+include $(DEPTH)/config/autoconf.mk
+
+STL_FLAGS =
+
+CPP_UNIT_TESTS = \
+ TestAtomics.cpp \
+ TestBloomFilter.cpp \
+ TestCasting.cpp \
+ TestCheckedInt.cpp \
+ TestEndian.cpp \
+ TestEnumSet.cpp \
+ TestSHA1.cpp \
+ TestTypeTraits.cpp \
+ TestWeakPtr.cpp \
+ $(NULL)
+
+# These tests don't work with AddressSanitizer enabled
+ifndef MOZ_ASAN
+CPP_UNIT_TESTS += \
+ TestPoisonArea.cpp \
+ $(NULL)
+endif
+
+# in order to prevent rules.mk from trying to link to libraries that are
+# not available to MFBT, we have to reset these MOZ_GLUE*_LDFLAGS before including it
+# and LIBS_ after including it. For WRAP_LDFLAGS, it shouldn't matter.
+# See later comments in bug 732875.
+
+MOZ_GLUE_PROGRAM_LDFLAGS=
+MOZ_GLUE_LDFLAGS =
+WRAP_LDFLAGS=
+
+# Since we link directly with MFBT object files, define IMPL_MFBT
+DEFINES += -DIMPL_MFBT
+
+include $(topsrcdir)/config/rules.mk
+
+LIBS= $(call EXPAND_LIBNAME_PATH,mfbt,$(DEPTH)/mfbt)
diff --git a/mfbt/tests/TestAtomics.cpp b/mfbt/tests/TestAtomics.cpp
new file mode 100644
index 0000000..3e05893
--- /dev/null
+++ b/mfbt/tests/TestAtomics.cpp
@@ -0,0 +1,159 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#include "mozilla/Assertions.h"
+#include "mozilla/Atomics.h"
+#include "mozilla/DebugOnly.h"
+
+#include <stdint.h>
+
+using mozilla::Atomic;
+using mozilla::DebugOnly;
+using mozilla::MemoryOrdering;
+using mozilla::Relaxed;
+using mozilla::ReleaseAcquire;
+using mozilla::SequentiallyConsistent;
+
+template <typename T, MemoryOrdering Order>
+static void
+TestTypeWithOrdering()
+{
+ Atomic<T, Order> atomic(5);
+ MOZ_ASSERT(atomic == 5, "Atomic variable did not initialize");
+
+ // Test atomic increment
+ MOZ_ASSERT(++atomic == T(6), "Atomic increment did not work");
+ MOZ_ASSERT(atomic++ == T(6), "Atomic post-increment did not work");
+ MOZ_ASSERT(atomic == T(7), "Atomic post-increment did not work");
+
+ // Test atomic decrement
+ MOZ_ASSERT(--atomic == 6, "Atomic decrement did not work");
+ MOZ_ASSERT(atomic-- == 6, "Atomic post-decrement did not work");
+ MOZ_ASSERT(atomic == 5, "Atomic post-decrement did not work");
+
+ // Test other arithmetic.
+ DebugOnly<T> result;
+ result = (atomic += T(5));
+ MOZ_ASSERT(atomic == T(10), "Atomic += did not work");
+ MOZ_ASSERT(result == T(10), "Atomic += returned the wrong value");
+ result = (atomic -= T(3));
+ MOZ_ASSERT(atomic == T(7), "Atomic -= did not work");
+ MOZ_ASSERT(result == T(7), "Atomic -= returned the wrong value");
+
+ // Test assignment
+ result = (atomic = T(5));
+ MOZ_ASSERT(atomic == T(5), "Atomic assignment failed");
+ MOZ_ASSERT(result == T(5), "Atomic assignment returned the wrong value");
+
+ // Test logical operations.
+ result = (atomic ^= T(2));
+ MOZ_ASSERT(atomic == T(7), "Atomic ^= did not work");
+ MOZ_ASSERT(result == T(7), "Atomic ^= returned the wrong value");
+ result = (atomic ^= T(4));
+ MOZ_ASSERT(atomic == T(3), "Atomic ^= did not work");
+ MOZ_ASSERT(result == T(3), "Atomic ^= returned the wrong value");
+ result = (atomic |= T(8));
+ MOZ_ASSERT(atomic == T(11), "Atomic |= did not work");
+ MOZ_ASSERT(result == T(11), "Atomic |= returned the wrong value");
+ result = (atomic |= T(8));
+ MOZ_ASSERT(atomic == T(11), "Atomic |= did not work");
+ MOZ_ASSERT(result == T(11), "Atomic |= returned the wrong value");
+ result = (atomic &= T(12));
+ MOZ_ASSERT(atomic == T(8), "Atomic &= did not work");
+ MOZ_ASSERT(result == T(8), "Atomic &= returned the wrong value");
+
+ // Test exchange.
+ atomic = T(30);
+ result = atomic.exchange(42);
+ MOZ_ASSERT(atomic == T(42), "Atomic exchange did not work");
+ MOZ_ASSERT(result == T(30), "Atomic exchange returned the wrong value");
+
+ // Test CAS.
+ atomic = T(1);
+ DebugOnly<bool> boolResult = atomic.compareExchange(0, 2);
+ MOZ_ASSERT(!boolResult, "CAS should have returned false.");
+ MOZ_ASSERT(atomic == T(1), "CAS shouldn't have done anything.");
+
+ boolResult = atomic.compareExchange(1, 42);
+ MOZ_ASSERT(boolResult, "CAS should have succeeded.");
+ MOZ_ASSERT(atomic == T(42), "CAS should have changed atomic's value.");
+}
+
+template<typename T, MemoryOrdering Order>
+static void
+TestPointerWithOrdering()
+{
+ T array1[10];
+ Atomic<T*, Order> atomic(array1);
+ MOZ_ASSERT(atomic == array1, "Atomic variable did not initialize");
+
+ // Test atomic increment
+ MOZ_ASSERT(++atomic == array1 + 1, "Atomic increment did not work");
+ MOZ_ASSERT(atomic++ == array1 + 1, "Atomic post-increment did not work");
+ MOZ_ASSERT(atomic == array1 + 2, "Atomic post-increment did not work");
+
+ // Test atomic decrement
+ MOZ_ASSERT(--atomic == array1 + 1, "Atomic decrement did not work");
+ MOZ_ASSERT(atomic-- == array1 + 1, "Atomic post-decrement did not work");
+ MOZ_ASSERT(atomic == array1, "Atomic post-decrement did not work");
+
+ // Test other arithmetic operations
+ DebugOnly<T*> result;
+ result = (atomic += 2);
+ MOZ_ASSERT(atomic == array1 + 2, "Atomic += did not work");
+ MOZ_ASSERT(result == array1 + 2, "Atomic += returned the wrong value");
+ result = (atomic -= 1);
+ MOZ_ASSERT(atomic == array1 + 1, "Atomic -= did not work");
+ MOZ_ASSERT(result == array1 + 1, "Atomic -= returned the wrong value");
+
+ // Test stores
+ result = (atomic = array1);
+ MOZ_ASSERT(atomic == array1, "Atomic assignment did not work");
+ MOZ_ASSERT(result == array1, "Atomic assignment returned the wrong value");
+
+ // Test exchange
+ atomic = array1 + 2;
+ result = atomic.exchange(array1);
+ MOZ_ASSERT(atomic == array1, "Atomic exchange did not work");
+ MOZ_ASSERT(result == array1 + 2, "Atomic exchange returned the wrong value");
+
+ atomic = array1;
+ DebugOnly<bool> boolResult = atomic.compareExchange(array1 + 1, array1 + 2);
+ MOZ_ASSERT(!boolResult, "CAS should have returned false.");
+ MOZ_ASSERT(atomic == array1, "CAS shouldn't have done anything.");
+
+ boolResult = atomic.compareExchange(array1, array1 + 3);
+ MOZ_ASSERT(boolResult, "CAS should have succeeded.");
+ MOZ_ASSERT(atomic == array1 + 3, "CAS should have changed atomic's value.");
+}
+
+template <typename T>
+static void
+TestType()
+{
+ TestTypeWithOrdering<T, SequentiallyConsistent>();
+ TestTypeWithOrdering<T, ReleaseAcquire>();
+ TestTypeWithOrdering<T, Relaxed>();
+}
+
+template<typename T>
+static void
+TestPointer()
+{
+ TestPointerWithOrdering<T, SequentiallyConsistent>();
+ TestPointerWithOrdering<T, ReleaseAcquire>();
+ TestPointerWithOrdering<T, Relaxed>();
+}
+
+int main()
+{
+ TestType<uint32_t>();
+ TestType<int32_t>();
+ TestType<intptr_t>();
+ TestType<uintptr_t>();
+ TestPointer<int>();
+ TestPointer<float>();
+ TestPointer<uint16_t*>();
+ TestPointer<uint32_t*>();
+}
diff --git a/mfbt/tests/TestBloomFilter.cpp b/mfbt/tests/TestBloomFilter.cpp
new file mode 100644
index 0000000..7a8a0ec
--- /dev/null
+++ b/mfbt/tests/TestBloomFilter.cpp
@@ -0,0 +1,102 @@
+/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#include "mozilla/Assertions.h"
+#include "mozilla/BloomFilter.h"
+
+#include <stddef.h>
+#include <stdio.h>
+
+using mozilla::BloomFilter;
+
+class FilterChecker
+{
+ public:
+ FilterChecker(uint32_t hash) : mHash(hash) { }
+
+ uint32_t hash() const { return mHash; }
+
+ private:
+ uint32_t mHash;
+};
+
+int
+main()
+{
+ BloomFilter<12, FilterChecker> *filter = new BloomFilter<12, FilterChecker>();
+ MOZ_ASSERT(filter);
+
+ FilterChecker one(1);
+ FilterChecker two(0x20000);
+ FilterChecker many(0x10000);
+ FilterChecker multiple(0x20001);
+
+ filter->add(&one);
+ MOZ_ASSERT(filter->mightContain(&one),
+ "Filter should contain 'one'");
+
+ MOZ_ASSERT(!filter->mightContain(&multiple),
+ "Filter claims to contain 'multiple' when it should not");
+
+ MOZ_ASSERT(filter->mightContain(&many),
+ "Filter should contain 'many' (false positive)");
+
+ filter->add(&two);
+ MOZ_ASSERT(filter->mightContain(&multiple),
+ "Filter should contain 'multiple' (false positive)");
+
+ // Test basic removals
+ filter->remove(&two);
+ MOZ_ASSERT(!filter->mightContain(&multiple),
+ "Filter claims to contain 'multiple' when it should not after two "
+ "was removed");
+
+ // Test multiple addition/removal
+ const size_t FILTER_SIZE = 255;
+ for (size_t i = 0; i < FILTER_SIZE - 1; ++i)
+ filter->add(&two);
+
+ MOZ_ASSERT(filter->mightContain(&multiple),
+ "Filter should contain 'multiple' after 'two' added lots of times "
+ "(false positive)");
+
+ for (size_t i = 0; i < FILTER_SIZE - 1; ++i)
+ filter->remove(&two);
+
+ MOZ_ASSERT(!filter->mightContain(&multiple),
+ "Filter claims to contain 'multiple' when it should not after two "
+ "was removed lots of times");
+
+ // Test overflowing the filter buckets
+ for (size_t i = 0; i < FILTER_SIZE + 1; ++i)
+ filter->add(&two);
+
+ MOZ_ASSERT(filter->mightContain(&multiple),
+ "Filter should contain 'multiple' after 'two' added lots more "
+ "times (false positive)");
+
+ for (size_t i = 0; i < FILTER_SIZE + 1; ++i)
+ filter->remove(&two);
+
+ MOZ_ASSERT(filter->mightContain(&multiple),
+ "Filter claims to not contain 'multiple' even though we should "
+ "have run out of space in the buckets (false positive)");
+ MOZ_ASSERT(filter->mightContain(&two),
+ "Filter claims to not contain 'two' even though we should have "
+ "run out of space in the buckets (false positive)");
+
+ filter->remove(&one);
+
+ MOZ_ASSERT(!filter->mightContain(&one),
+ "Filter should not contain 'one', because we didn't overflow its "
+ "bucket");
+
+ filter->clear();
+
+ MOZ_ASSERT(!filter->mightContain(&multiple),
+ "clear() failed to work");
+
+ return 0;
+}
diff --git a/mfbt/tests/TestCasting.cpp b/mfbt/tests/TestCasting.cpp
new file mode 100644
index 0000000..1e19b07
--- /dev/null
+++ b/mfbt/tests/TestCasting.cpp
@@ -0,0 +1,107 @@
+/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#include "mozilla/Casting.h"
+#include "mozilla/StandardInteger.h"
+
+using mozilla::BitwiseCast;
+using mozilla::detail::IsInBounds;
+
+template<typename Uint, typename Ulong, bool = (sizeof(Uint) == sizeof(Ulong))>
+struct UintUlongBitwiseCast;
+
+template<typename Uint, typename Ulong>
+struct UintUlongBitwiseCast<Uint, Ulong, true>
+{
+ static void test() {
+ MOZ_ASSERT(BitwiseCast<Ulong>(Uint(8675309)) == Ulong(8675309));
+ }
+};
+
+template<typename Uint, typename Ulong>
+struct UintUlongBitwiseCast<Uint, Ulong, false>
+{
+ static void test() { }
+};
+
+static void
+TestBitwiseCast()
+{
+ MOZ_ASSERT(BitwiseCast<int>(int(8675309)) == int(8675309));
+ UintUlongBitwiseCast<unsigned int, unsigned long>::test();
+}
+
+static void
+TestSameSize()
+{
+ MOZ_ASSERT((IsInBounds<int16_t, int16_t>(int16_t(0))));
+ MOZ_ASSERT((IsInBounds<int16_t, int16_t>(int16_t(INT16_MIN))));
+ MOZ_ASSERT((IsInBounds<int16_t, int16_t>(int16_t(INT16_MAX))));
+ MOZ_ASSERT((IsInBounds<uint16_t, uint16_t>(uint16_t(UINT16_MAX))));
+ MOZ_ASSERT((IsInBounds<uint16_t, int16_t>(uint16_t(0))));
+ MOZ_ASSERT((!IsInBounds<uint16_t, int16_t>(uint16_t(-1))));
+ MOZ_ASSERT((!IsInBounds<int16_t, uint16_t>(int16_t(-1))));
+ MOZ_ASSERT((IsInBounds<int16_t, uint16_t>(int16_t(INT16_MAX))));
+ MOZ_ASSERT((!IsInBounds<int16_t, uint16_t>(int16_t(INT16_MIN))));
+ MOZ_ASSERT((IsInBounds<int32_t, uint32_t>(int32_t(INT32_MAX))));
+ MOZ_ASSERT((!IsInBounds<int32_t, uint32_t>(int32_t(INT32_MIN))));
+}
+
+static void
+TestToBiggerSize()
+{
+ MOZ_ASSERT((IsInBounds<int16_t, int32_t>(int16_t(0))));
+ MOZ_ASSERT((IsInBounds<int16_t, int32_t>(int16_t(INT16_MIN))));
+ MOZ_ASSERT((IsInBounds<int16_t, int32_t>(int16_t(INT16_MAX))));
+ MOZ_ASSERT((IsInBounds<uint16_t, uint32_t>(uint16_t(UINT16_MAX))));
+ MOZ_ASSERT((IsInBounds<uint16_t, int32_t>(uint16_t(0))));
+ MOZ_ASSERT((IsInBounds<uint16_t, int32_t>(uint16_t(-1))));
+ MOZ_ASSERT((!IsInBounds<int16_t, uint32_t>(int16_t(-1))));
+ MOZ_ASSERT((IsInBounds<int16_t, uint32_t>(int16_t(INT16_MAX))));
+ MOZ_ASSERT((!IsInBounds<int16_t, uint32_t>(int16_t(INT16_MIN))));
+ MOZ_ASSERT((IsInBounds<int32_t, uint64_t>(int32_t(INT32_MAX))));
+ MOZ_ASSERT((!IsInBounds<int32_t, uint64_t>(int32_t(INT32_MIN))));
+}
+
+static void
+TestToSmallerSize()
+{
+ MOZ_ASSERT((IsInBounds<int16_t, int8_t>(int16_t(0))));
+ MOZ_ASSERT((!IsInBounds<int16_t, int8_t>(int16_t(INT16_MIN))));
+ MOZ_ASSERT((!IsInBounds<int16_t, int8_t>(int16_t(INT16_MAX))));
+ MOZ_ASSERT((!IsInBounds<uint16_t, uint8_t>(uint16_t(UINT16_MAX))));
+ MOZ_ASSERT((IsInBounds<uint16_t, int8_t>(uint16_t(0))));
+ MOZ_ASSERT((!IsInBounds<uint16_t, int8_t>(uint16_t(-1))));
+ MOZ_ASSERT((!IsInBounds<int16_t, uint8_t>(int16_t(-1))));
+ MOZ_ASSERT((!IsInBounds<int16_t, uint8_t>(int16_t(INT16_MAX))));
+ MOZ_ASSERT((!IsInBounds<int16_t, uint8_t>(int16_t(INT16_MIN))));
+ MOZ_ASSERT((!IsInBounds<int32_t, uint16_t>(int32_t(INT32_MAX))));
+ MOZ_ASSERT((!IsInBounds<int32_t, uint16_t>(int32_t(INT32_MIN))));
+
+ // Boundary cases
+ MOZ_ASSERT((!IsInBounds<int64_t, int32_t>(int64_t(INT32_MIN) - 1)));
+ MOZ_ASSERT((IsInBounds<int64_t, int32_t>(int64_t(INT32_MIN))));
+ MOZ_ASSERT((IsInBounds<int64_t, int32_t>(int64_t(INT32_MIN) + 1)));
+ MOZ_ASSERT((IsInBounds<int64_t, int32_t>(int64_t(INT32_MAX) - 1)));
+ MOZ_ASSERT((IsInBounds<int64_t, int32_t>(int64_t(INT32_MAX))));
+ MOZ_ASSERT((!IsInBounds<int64_t, int32_t>(int64_t(INT32_MAX) + 1)));
+
+ MOZ_ASSERT((!IsInBounds<int64_t, uint32_t>(int64_t(-1))));
+ MOZ_ASSERT((IsInBounds<int64_t, uint32_t>(int64_t(0))));
+ MOZ_ASSERT((IsInBounds<int64_t, uint32_t>(int64_t(1))));
+ MOZ_ASSERT((IsInBounds<int64_t, uint32_t>(int64_t(UINT32_MAX) - 1)));
+ MOZ_ASSERT((IsInBounds<int64_t, uint32_t>(int64_t(UINT32_MAX))));
+ MOZ_ASSERT((!IsInBounds<int64_t, uint32_t>(int64_t(UINT32_MAX) + 1)));
+}
+
+int
+main()
+{
+ TestBitwiseCast();
+
+ TestSameSize();
+ TestToBiggerSize();
+ TestToSmallerSize();
+}
diff --git a/mfbt/tests/TestCheckedInt.cpp b/mfbt/tests/TestCheckedInt.cpp
new file mode 100644
index 0000000..5a9cba7
--- /dev/null
+++ b/mfbt/tests/TestCheckedInt.cpp
@@ -0,0 +1,567 @@
+/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#include "mozilla/CheckedInt.h"
+
+#include <iostream>
+#include <climits>
+
+#ifndef MOZ_CHECKEDINT_USE_MFBT
+# error "MOZ_CHECKEDINT_USE_MFBT should be defined by CheckedInt.h"
+#endif
+
+using namespace mozilla;
+
+int gIntegerTypesTested = 0;
+int gTestsPassed = 0;
+int gTestsFailed = 0;
+
+void verifyImplFunction(bool x, bool expected,
+ const char* file, int line,
+ int size, bool isTSigned)
+{
+ if (x == expected) {
+ gTestsPassed++;
+ } else {
+ gTestsFailed++;
+ std::cerr << "Test failed at " << file << ":" << line;
+ std::cerr << " with T a ";
+ if (isTSigned)
+ std::cerr << "signed";
+ else
+ std::cerr << "unsigned";
+ std::cerr << " " << CHAR_BIT*size << "-bit integer type" << std::endl;
+ }
+}
+
+#define VERIFY_IMPL(x, expected) \
+ verifyImplFunction((x), \
+ (expected), \
+ __FILE__, \
+ __LINE__, \
+ sizeof(T), \
+ detail::IsSigned<T>::value)
+
+#define VERIFY(x) VERIFY_IMPL(x, true)
+#define VERIFY_IS_FALSE(x) VERIFY_IMPL(x, false)
+#define VERIFY_IS_VALID(x) VERIFY_IMPL((x).isValid(), true)
+#define VERIFY_IS_INVALID(x) VERIFY_IMPL((x).isValid(), false)
+#define VERIFY_IS_VALID_IF(x,condition) VERIFY_IMPL((x).isValid(), (condition))
+
+template<typename T, size_t Size = sizeof(T)>
+struct testTwiceBiggerType
+{
+ static void run()
+ {
+ VERIFY(detail::IsSupported<typename detail::TwiceBiggerType<T>::Type>::value);
+ VERIFY(sizeof(typename detail::TwiceBiggerType<T>::Type)
+ == 2 * sizeof(T));
+ VERIFY(bool(detail::IsSigned<typename detail::TwiceBiggerType<T>::Type>::value)
+ == bool(detail::IsSigned<T>::value));
+ }
+};
+
+template<typename T>
+struct testTwiceBiggerType<T, 8>
+{
+ static void run()
+ {
+ VERIFY_IS_FALSE(detail::IsSupported<
+ typename detail::TwiceBiggerType<T>::Type
+ >::value);
+ }
+};
+
+
+template<typename T>
+void test()
+{
+ static bool alreadyRun = false;
+ // Integer types from different families may just be typedefs for types from other families.
+ // e.g. int32_t might be just a typedef for int. No point re-running the same tests then.
+ if (alreadyRun)
+ return;
+ alreadyRun = true;
+
+ VERIFY(detail::IsSupported<T>::value);
+ const bool isTSigned = detail::IsSigned<T>::value;
+ VERIFY(bool(isTSigned) == !bool(T(-1) > T(0)));
+
+ testTwiceBiggerType<T>::run();
+
+ typedef typename detail::UnsignedType<T>::Type unsignedT;
+
+ VERIFY(sizeof(unsignedT) == sizeof(T));
+ VERIFY(detail::IsSigned<unsignedT>::value == false);
+
+ const CheckedInt<T> max(detail::MaxValue<T>::value);
+ const CheckedInt<T> min(detail::MinValue<T>::value);
+
+ // Check MinValue and MaxValue, since they are custom implementations and a mistake there
+ // could potentially NOT be caught by any other tests... while making everything wrong!
+
+ unsignedT bit = 1;
+ unsignedT unsignedMinValue(min.value());
+ unsignedT unsignedMaxValue(max.value());
+ for (size_t i = 0; i < sizeof(T) * CHAR_BIT - 1; i++)
+ {
+ VERIFY((unsignedMinValue & bit) == 0);
+ bit <<= 1;
+ }
+ VERIFY((unsignedMinValue & bit) == (isTSigned ? bit : unsignedT(0)));
+ VERIFY(unsignedMaxValue == unsignedT(~unsignedMinValue));
+
+ const CheckedInt<T> zero(0);
+ const CheckedInt<T> one(1);
+ const CheckedInt<T> two(2);
+ const CheckedInt<T> three(3);
+ const CheckedInt<T> four(4);
+
+ /* Addition / subtraction checks */
+
+ VERIFY_IS_VALID(zero + zero);
+ VERIFY(zero + zero == zero);
+ VERIFY_IS_FALSE(zero + zero == one); // Check that == doesn't always return true
+ VERIFY_IS_VALID(zero + one);
+ VERIFY(zero + one == one);
+ VERIFY_IS_VALID(one + one);
+ VERIFY(one + one == two);
+
+ const CheckedInt<T> maxMinusOne = max - one;
+ const CheckedInt<T> maxMinusTwo = max - two;
+ VERIFY_IS_VALID(maxMinusOne);
+ VERIFY_IS_VALID(maxMinusTwo);
+ VERIFY_IS_VALID(maxMinusOne + one);
+ VERIFY_IS_VALID(maxMinusTwo + one);
+ VERIFY_IS_VALID(maxMinusTwo + two);
+ VERIFY(maxMinusOne + one == max);
+ VERIFY(maxMinusTwo + one == maxMinusOne);
+ VERIFY(maxMinusTwo + two == max);
+
+ VERIFY_IS_VALID(max + zero);
+ VERIFY_IS_VALID(max - zero);
+ VERIFY_IS_INVALID(max + one);
+ VERIFY_IS_INVALID(max + two);
+ VERIFY_IS_INVALID(max + maxMinusOne);
+ VERIFY_IS_INVALID(max + max);
+
+ const CheckedInt<T> minPlusOne = min + one;
+ const CheckedInt<T> minPlusTwo = min + two;
+ VERIFY_IS_VALID(minPlusOne);
+ VERIFY_IS_VALID(minPlusTwo);
+ VERIFY_IS_VALID(minPlusOne - one);
+ VERIFY_IS_VALID(minPlusTwo - one);
+ VERIFY_IS_VALID(minPlusTwo - two);
+ VERIFY(minPlusOne - one == min);
+ VERIFY(minPlusTwo - one == minPlusOne);
+ VERIFY(minPlusTwo - two == min);
+
+ const CheckedInt<T> minMinusOne = min - one;
+ VERIFY_IS_VALID(min + zero);
+ VERIFY_IS_VALID(min - zero);
+ VERIFY_IS_INVALID(min - one);
+ VERIFY_IS_INVALID(min - two);
+ VERIFY_IS_INVALID(min - minMinusOne);
+ VERIFY_IS_VALID(min - min);
+
+ const CheckedInt<T> maxOverTwo = max / two;
+ VERIFY_IS_VALID(maxOverTwo + maxOverTwo);
+ VERIFY_IS_VALID(maxOverTwo + one);
+ VERIFY((maxOverTwo + one) - one == maxOverTwo);
+ VERIFY_IS_VALID(maxOverTwo - maxOverTwo);
+ VERIFY(maxOverTwo - maxOverTwo == zero);
+
+ const CheckedInt<T> minOverTwo = min / two;
+ VERIFY_IS_VALID(minOverTwo + minOverTwo);
+ VERIFY_IS_VALID(minOverTwo + one);
+ VERIFY((minOverTwo + one) - one == minOverTwo);
+ VERIFY_IS_VALID(minOverTwo - minOverTwo);
+ VERIFY(minOverTwo - minOverTwo == zero);
+
+ VERIFY_IS_INVALID(min - one);
+ VERIFY_IS_INVALID(min - two);
+
+ if (isTSigned) {
+ VERIFY_IS_INVALID(min + min);
+ VERIFY_IS_INVALID(minOverTwo + minOverTwo + minOverTwo);
+ VERIFY_IS_INVALID(zero - min + min);
+ VERIFY_IS_INVALID(one - min + min);
+ }
+
+ /* Modulo checks */
+ VERIFY_IS_INVALID(zero % zero);
+ VERIFY_IS_INVALID(one % zero);
+ VERIFY_IS_VALID(zero % one);
+ VERIFY_IS_VALID(zero % max);
+ VERIFY_IS_VALID(one % max);
+ VERIFY_IS_VALID(max % one);
+ VERIFY_IS_VALID(max % max);
+ if (isTSigned) {
+ const CheckedInt<T> minusOne = zero - one;
+ VERIFY_IS_INVALID(minusOne % minusOne);
+ VERIFY_IS_INVALID(zero % minusOne);
+ VERIFY_IS_INVALID(one % minusOne);
+ VERIFY_IS_INVALID(minusOne % one);
+
+ VERIFY_IS_INVALID(min % min);
+ VERIFY_IS_INVALID(zero % min);
+ VERIFY_IS_INVALID(min % one);
+ }
+
+ /* Unary operator- checks */
+
+ const CheckedInt<T> negOne = -one;
+ const CheckedInt<T> negTwo = -two;
+
+ if (isTSigned) {
+ VERIFY_IS_VALID(-max);
+ VERIFY_IS_INVALID(-min);
+ VERIFY(-max - min == one);
+ VERIFY_IS_VALID(-max - one);
+ VERIFY_IS_VALID(negOne);
+ VERIFY_IS_VALID(-max + negOne);
+ VERIFY_IS_VALID(negOne + one);
+ VERIFY(negOne + one == zero);
+ VERIFY_IS_VALID(negTwo);
+ VERIFY_IS_VALID(negOne + negOne);
+ VERIFY(negOne + negOne == negTwo);
+ } else {
+ VERIFY_IS_INVALID(-max);
+ VERIFY_IS_VALID(-min);
+ VERIFY(min == zero);
+ VERIFY_IS_INVALID(negOne);
+ }
+
+ /* multiplication checks */
+
+ VERIFY_IS_VALID(zero * zero);
+ VERIFY(zero * zero == zero);
+ VERIFY_IS_VALID(zero * one);
+ VERIFY(zero * one == zero);
+ VERIFY_IS_VALID(one * zero);
+ VERIFY(one * zero == zero);
+ VERIFY_IS_VALID(one * one);
+ VERIFY(one * one == one);
+ VERIFY_IS_VALID(one * three);
+ VERIFY(one * three == three);
+ VERIFY_IS_VALID(two * two);
+ VERIFY(two * two == four);
+
+ VERIFY_IS_INVALID(max * max);
+ VERIFY_IS_INVALID(maxOverTwo * max);
+ VERIFY_IS_INVALID(maxOverTwo * maxOverTwo);
+
+ const CheckedInt<T> maxApproxSqrt(T(T(1) << (CHAR_BIT*sizeof(T)/2)));
+
+ VERIFY_IS_VALID(maxApproxSqrt);
+ VERIFY_IS_VALID(maxApproxSqrt * two);
+ VERIFY_IS_INVALID(maxApproxSqrt * maxApproxSqrt);
+ VERIFY_IS_INVALID(maxApproxSqrt * maxApproxSqrt * maxApproxSqrt);
+
+ if (isTSigned) {
+ VERIFY_IS_INVALID(min * min);
+ VERIFY_IS_INVALID(minOverTwo * min);
+ VERIFY_IS_INVALID(minOverTwo * minOverTwo);
+
+ const CheckedInt<T> minApproxSqrt = -maxApproxSqrt;
+
+ VERIFY_IS_VALID(minApproxSqrt);
+ VERIFY_IS_VALID(minApproxSqrt * two);
+ VERIFY_IS_INVALID(minApproxSqrt * maxApproxSqrt);
+ VERIFY_IS_INVALID(minApproxSqrt * minApproxSqrt);
+ }
+
+ // make sure to check all 4 paths in signed multiplication validity check.
+ // test positive * positive
+ VERIFY_IS_VALID(max * one);
+ VERIFY(max * one == max);
+ VERIFY_IS_INVALID(max * two);
+ VERIFY_IS_VALID(maxOverTwo * two);
+ VERIFY((maxOverTwo + maxOverTwo) == (maxOverTwo * two));
+
+ if (isTSigned) {
+ // test positive * negative
+ VERIFY_IS_VALID(max * negOne);
+ VERIFY_IS_VALID(-max);
+ VERIFY(max * negOne == -max);
+ VERIFY_IS_VALID(one * min);
+ VERIFY_IS_INVALID(max * negTwo);
+ VERIFY_IS_VALID(maxOverTwo * negTwo);
+ VERIFY_IS_VALID(two * minOverTwo);
+ VERIFY_IS_VALID((maxOverTwo + one) * negTwo);
+ VERIFY_IS_INVALID((maxOverTwo + two) * negTwo);
+ VERIFY_IS_INVALID(two * (minOverTwo - one));
+
+ // test negative * positive
+ VERIFY_IS_VALID(min * one);
+ VERIFY_IS_VALID(minPlusOne * one);
+ VERIFY_IS_INVALID(min * two);
+ VERIFY_IS_VALID(minOverTwo * two);
+ VERIFY(minOverTwo * two == min);
+ VERIFY_IS_INVALID((minOverTwo - one) * negTwo);
+ VERIFY_IS_INVALID(negTwo * max);
+ VERIFY_IS_VALID(minOverTwo * two);
+ VERIFY(minOverTwo * two == min);
+ VERIFY_IS_VALID(negTwo * maxOverTwo);
+ VERIFY_IS_INVALID((minOverTwo - one) * two);
+ VERIFY_IS_VALID(negTwo * (maxOverTwo + one));
+ VERIFY_IS_INVALID(negTwo * (maxOverTwo + two));
+
+ // test negative * negative
+ VERIFY_IS_INVALID(min * negOne);
+ VERIFY_IS_VALID(minPlusOne * negOne);
+ VERIFY(minPlusOne * negOne == max);
+ VERIFY_IS_INVALID(min * negTwo);
+ VERIFY_IS_INVALID(minOverTwo * negTwo);
+ VERIFY_IS_INVALID(negOne * min);
+ VERIFY_IS_VALID(negOne * minPlusOne);
+ VERIFY(negOne * minPlusOne == max);
+ VERIFY_IS_INVALID(negTwo * min);
+ VERIFY_IS_INVALID(negTwo * minOverTwo);
+ }
+
+ /* Division checks */
+
+ VERIFY_IS_VALID(one / one);
+ VERIFY(one / one == one);
+ VERIFY_IS_VALID(three / three);
+ VERIFY(three / three == one);
+ VERIFY_IS_VALID(four / two);
+ VERIFY(four / two == two);
+ VERIFY((four*three)/four == three);
+
+ // Check that div by zero is invalid
+ VERIFY_IS_INVALID(zero / zero);
+ VERIFY_IS_INVALID(one / zero);
+ VERIFY_IS_INVALID(two / zero);
+ VERIFY_IS_INVALID(negOne / zero);
+ VERIFY_IS_INVALID(max / zero);
+ VERIFY_IS_INVALID(min / zero);
+
+ if (isTSigned) {
+ // Check that min / -1 is invalid
+ VERIFY_IS_INVALID(min / negOne);
+
+ // Check that the test for div by -1 isn't banning other numerators than min
+ VERIFY_IS_VALID(one / negOne);
+ VERIFY_IS_VALID(zero / negOne);
+ VERIFY_IS_VALID(negOne / negOne);
+ VERIFY_IS_VALID(max / negOne);
+ }
+
+ /* Check that invalidity is correctly preserved by arithmetic ops */
+
+ const CheckedInt<T> someInvalid = max + max;
+ VERIFY_IS_INVALID(someInvalid + zero);
+ VERIFY_IS_INVALID(someInvalid - zero);
+ VERIFY_IS_INVALID(zero + someInvalid);
+ VERIFY_IS_INVALID(zero - someInvalid);
+ VERIFY_IS_INVALID(-someInvalid);
+ VERIFY_IS_INVALID(someInvalid * zero);
+ VERIFY_IS_INVALID(someInvalid * one);
+ VERIFY_IS_INVALID(zero * someInvalid);
+ VERIFY_IS_INVALID(one * someInvalid);
+ VERIFY_IS_INVALID(someInvalid / zero);
+ VERIFY_IS_INVALID(someInvalid / one);
+ VERIFY_IS_INVALID(zero / someInvalid);
+ VERIFY_IS_INVALID(one / someInvalid);
+ VERIFY_IS_INVALID(someInvalid % zero);
+ VERIFY_IS_INVALID(someInvalid % one);
+ VERIFY_IS_INVALID(zero % someInvalid);
+ VERIFY_IS_INVALID(one % someInvalid);
+ VERIFY_IS_INVALID(someInvalid + someInvalid);
+ VERIFY_IS_INVALID(someInvalid - someInvalid);
+ VERIFY_IS_INVALID(someInvalid * someInvalid);
+ VERIFY_IS_INVALID(someInvalid / someInvalid);
+ VERIFY_IS_INVALID(someInvalid % someInvalid);
+
+ /* Check that mixing checked integers with plain integers in expressions is allowed */
+
+ VERIFY(one + T(2) == three);
+ VERIFY(2 + one == three);
+ {
+ CheckedInt<T> x = one;
+ x += 2;
+ VERIFY(x == three);
+ }
+ VERIFY(two - 1 == one);
+ VERIFY(2 - one == one);
+ {
+ CheckedInt<T> x = two;
+ x -= 1;
+ VERIFY(x == one);
+ }
+ VERIFY(one * 2 == two);
+ VERIFY(2 * one == two);
+ {
+ CheckedInt<T> x = one;
+ x *= 2;
+ VERIFY(x == two);
+ }
+ VERIFY(four / 2 == two);
+ VERIFY(4 / two == two);
+ {
+ CheckedInt<T> x = four;
+ x /= 2;
+ VERIFY(x == two);
+ }
+ VERIFY(three % 2 == one);
+ VERIFY(3 % two == one);
+ {
+ CheckedInt<T> x = three;
+ x %= 2;
+ VERIFY(x == one);
+ }
+
+ VERIFY(one == 1);
+ VERIFY(1 == one);
+ VERIFY_IS_FALSE(two == 1);
+ VERIFY_IS_FALSE(1 == two);
+ VERIFY_IS_FALSE(someInvalid == 1);
+ VERIFY_IS_FALSE(1 == someInvalid);
+
+ // Check simple casting between different signedness and sizes.
+ {
+ CheckedInt<uint8_t> foo = CheckedInt<uint16_t>(2).toChecked<uint8_t>();
+ VERIFY_IS_VALID(foo);
+ VERIFY(foo == 2);
+ }
+ {
+ CheckedInt<uint8_t> foo = CheckedInt<uint16_t>(255).toChecked<uint8_t>();
+ VERIFY_IS_VALID(foo);
+ VERIFY(foo == 255);
+ }
+ {
+ CheckedInt<uint8_t> foo = CheckedInt<uint16_t>(256).toChecked<uint8_t>();
+ VERIFY_IS_INVALID(foo);
+ }
+ {
+ CheckedInt<uint8_t> foo = CheckedInt<int8_t>(-2).toChecked<uint8_t>();
+ VERIFY_IS_INVALID(foo);
+ }
+
+ // Check that construction of CheckedInt from an integer value of a mismatched type is checked
+ // Also check casting between all types.
+
+ #define VERIFY_CONSTRUCTION_FROM_INTEGER_TYPE2(U,V,PostVExpr) \
+ { \
+ bool isUSigned = detail::IsSigned<U>::value; \
+ VERIFY_IS_VALID(CheckedInt<T>(V( 0)PostVExpr)); \
+ VERIFY_IS_VALID(CheckedInt<T>(V( 1)PostVExpr)); \
+ VERIFY_IS_VALID(CheckedInt<T>(V(100)PostVExpr)); \
+ if (isUSigned) \
+ VERIFY_IS_VALID_IF(CheckedInt<T>(V(-1)PostVExpr), isTSigned); \
+ if (sizeof(U) > sizeof(T)) \
+ VERIFY_IS_INVALID(CheckedInt<T>(V(detail::MaxValue<T>::value)PostVExpr + one.value())); \
+ VERIFY_IS_VALID_IF(CheckedInt<T>(detail::MaxValue<U>::value), \
+ (sizeof(T) > sizeof(U) || ((sizeof(T) == sizeof(U)) && (isUSigned || !isTSigned)))); \
+ VERIFY_IS_VALID_IF(CheckedInt<T>(detail::MinValue<U>::value), \
+ isUSigned == false ? 1 \
+ : bool(isTSigned) == false ? 0 \
+ : sizeof(T) >= sizeof(U)); \
+ }
+ #define VERIFY_CONSTRUCTION_FROM_INTEGER_TYPE(U) \
+ VERIFY_CONSTRUCTION_FROM_INTEGER_TYPE2(U,U,+0) \
+ VERIFY_CONSTRUCTION_FROM_INTEGER_TYPE2(U,CheckedInt<U>,.toChecked<T>())
+
+ VERIFY_CONSTRUCTION_FROM_INTEGER_TYPE(int8_t)
+ VERIFY_CONSTRUCTION_FROM_INTEGER_TYPE(uint8_t)
+ VERIFY_CONSTRUCTION_FROM_INTEGER_TYPE(int16_t)
+ VERIFY_CONSTRUCTION_FROM_INTEGER_TYPE(uint16_t)
+ VERIFY_CONSTRUCTION_FROM_INTEGER_TYPE(int32_t)
+ VERIFY_CONSTRUCTION_FROM_INTEGER_TYPE(uint32_t)
+ VERIFY_CONSTRUCTION_FROM_INTEGER_TYPE(int64_t)
+ VERIFY_CONSTRUCTION_FROM_INTEGER_TYPE(uint64_t)
+
+ typedef signed char signedChar;
+ typedef unsigned char unsignedChar;
+ typedef unsigned short unsignedShort;
+ typedef unsigned int unsignedInt;
+ typedef unsigned long unsignedLong;
+ typedef long long longLong;
+ typedef unsigned long long unsignedLongLong;
+
+ VERIFY_CONSTRUCTION_FROM_INTEGER_TYPE(char)
+ VERIFY_CONSTRUCTION_FROM_INTEGER_TYPE(signedChar)
+ VERIFY_CONSTRUCTION_FROM_INTEGER_TYPE(unsignedChar)
+ VERIFY_CONSTRUCTION_FROM_INTEGER_TYPE(short)
+ VERIFY_CONSTRUCTION_FROM_INTEGER_TYPE(unsignedShort)
+ VERIFY_CONSTRUCTION_FROM_INTEGER_TYPE(int)
+ VERIFY_CONSTRUCTION_FROM_INTEGER_TYPE(unsignedInt)
+ VERIFY_CONSTRUCTION_FROM_INTEGER_TYPE(long)
+ VERIFY_CONSTRUCTION_FROM_INTEGER_TYPE(unsignedLong)
+ VERIFY_CONSTRUCTION_FROM_INTEGER_TYPE(longLong)
+ VERIFY_CONSTRUCTION_FROM_INTEGER_TYPE(unsignedLongLong)
+
+ /* Test increment/decrement operators */
+
+ CheckedInt<T> x, y;
+ x = one;
+ y = x++;
+ VERIFY(x == two);
+ VERIFY(y == one);
+ x = one;
+ y = ++x;
+ VERIFY(x == two);
+ VERIFY(y == two);
+ x = one;
+ y = x--;
+ VERIFY(x == zero);
+ VERIFY(y == one);
+ x = one;
+ y = --x;
+ VERIFY(x == zero);
+ VERIFY(y == zero);
+ x = max;
+ VERIFY_IS_VALID(x++);
+ x = max;
+ VERIFY_IS_INVALID(++x);
+ x = min;
+ VERIFY_IS_VALID(x--);
+ x = min;
+ VERIFY_IS_INVALID(--x);
+
+ gIntegerTypesTested++;
+}
+
+int main()
+{
+ test<int8_t>();
+ test<uint8_t>();
+ test<int16_t>();
+ test<uint16_t>();
+ test<int32_t>();
+ test<uint32_t>();
+ test<int64_t>();
+ test<uint64_t>();
+
+ test<char>();
+ test<signed char>();
+ test<unsigned char>();
+ test<short>();
+ test<unsigned short>();
+ test<int>();
+ test<unsigned int>();
+ test<long>();
+ test<unsigned long>();
+ test<long long>();
+ test<unsigned long long>();
+
+ const int MIN_TYPES_TESTED = 9;
+ if (gIntegerTypesTested < MIN_TYPES_TESTED) {
+ std::cerr << "Only " << gIntegerTypesTested << " have been tested. "
+ << "This should not be less than " << MIN_TYPES_TESTED << "."
+ << std::endl;
+ gTestsFailed++;
+ }
+
+ std::cerr << gTestsFailed << " tests failed, "
+ << gTestsPassed << " tests passed out of "
+ << gTestsFailed + gTestsPassed
+ << " tests, covering " << gIntegerTypesTested
+ << " distinct integer types." << std::endl;
+
+ return gTestsFailed > 0;
+}
diff --git a/mfbt/tests/TestEndian.cpp b/mfbt/tests/TestEndian.cpp
new file mode 100644
index 0000000..1ec520d
--- /dev/null
+++ b/mfbt/tests/TestEndian.cpp
@@ -0,0 +1,398 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#include "mozilla/Assertions.h"
+#include "mozilla/DebugOnly.h"
+#include "mozilla/Endian.h"
+
+using mozilla::BigEndian;
+using mozilla::DebugOnly;
+using mozilla::LittleEndian;
+using mozilla::NativeEndian;
+
+template<typename T>
+void
+TestSingleSwap(T value, T swappedValue)
+{
+#if MOZ_LITTLE_ENDIAN
+ MOZ_ASSERT(NativeEndian::swapToBigEndian(value) == swappedValue);
+ MOZ_ASSERT(NativeEndian::swapFromBigEndian(value) == swappedValue);
+ MOZ_ASSERT(NativeEndian::swapToNetworkOrder(value) == swappedValue);
+ MOZ_ASSERT(NativeEndian::swapFromNetworkOrder(value) == swappedValue);
+#else
+ MOZ_ASSERT(NativeEndian::swapToLittleEndian(value) == swappedValue);
+ MOZ_ASSERT(NativeEndian::swapFromLittleEndian(value) == swappedValue);
+#endif
+}
+
+template<typename T>
+void
+TestSingleNoSwap(T value, T notSwappedValue)
+{
+#if MOZ_LITTLE_ENDIAN
+ MOZ_ASSERT(NativeEndian::swapToLittleEndian(value) == notSwappedValue);
+ MOZ_ASSERT(NativeEndian::swapFromLittleEndian(value) == notSwappedValue);
+#else
+ MOZ_ASSERT(NativeEndian::swapToBigEndian(value) == notSwappedValue);
+ MOZ_ASSERT(NativeEndian::swapFromBigEndian(value) == notSwappedValue);
+ MOZ_ASSERT(NativeEndian::swapToNetworkOrder(value) == notSwappedValue);
+ MOZ_ASSERT(NativeEndian::swapFromNetworkOrder(value) == notSwappedValue);
+#endif
+}
+
+// Endian.h functions are declared as protected in an base class and
+// then re-exported as public in public derived classes. The
+// standardese around explicit instantiation of templates is not clear
+// in such cases. Provide these wrappers to make things more explicit.
+// For your own enlightenment, you may wish to peruse:
+// http://gcc.gnu.org/bugzilla/show_bug.cgi?id=56152 and subsequently
+// http://j.mp/XosS6S .
+#define WRAP_COPYTO(NAME) \
+ template<typename T> \
+ void \
+ NAME(void* dst, const T* src, unsigned int count) \
+ { \
+ NativeEndian::NAME<T>(dst, src, count); \
+ }
+
+WRAP_COPYTO(copyAndSwapToLittleEndian)
+WRAP_COPYTO(copyAndSwapToBigEndian)
+WRAP_COPYTO(copyAndSwapToNetworkOrder)
+
+#define WRAP_COPYFROM(NAME) \
+ template<typename T> \
+ void \
+ NAME(T* dst, const void* src, unsigned int count) \
+ { \
+ NativeEndian::NAME<T>(dst, src, count); \
+ }
+
+WRAP_COPYFROM(copyAndSwapFromLittleEndian)
+WRAP_COPYFROM(copyAndSwapFromBigEndian)
+WRAP_COPYFROM(copyAndSwapFromNetworkOrder)
+
+#define WRAP_IN_PLACE(NAME) \
+ template<typename T> \
+ void \
+ NAME(T* p, unsigned int count) \
+ { \
+ NativeEndian::NAME<T>(p, count); \
+ }
+WRAP_IN_PLACE(swapToLittleEndianInPlace)
+WRAP_IN_PLACE(swapFromLittleEndianInPlace)
+WRAP_IN_PLACE(swapToBigEndianInPlace)
+WRAP_IN_PLACE(swapFromBigEndianInPlace)
+WRAP_IN_PLACE(swapToNetworkOrderInPlace)
+WRAP_IN_PLACE(swapFromNetworkOrderInPlace)
+
+enum SwapExpectation {
+ Swap,
+ NoSwap
+};
+
+template<typename T, size_t count>
+void
+TestBulkSwapToSub(enum SwapExpectation expectSwap,
+ const T (&values)[count],
+ void (*swapperFunc)(void*, const T*, unsigned int),
+ T (*readerFunc)(const void*))
+{
+ const size_t arraySize = 2 * count;
+ const size_t bufferSize = arraySize * sizeof(T);
+ static uint8_t buffer[bufferSize];
+ const uint8_t fillValue = 0xa5;
+ static uint8_t checkBuffer[bufferSize];
+
+ MOZ_ASSERT(bufferSize > 2 * sizeof(T));
+
+ memset(checkBuffer, fillValue, bufferSize);
+
+ for (size_t startPosition = 0; startPosition < sizeof(T); ++startPosition) {
+ for (size_t nValues = 0; nValues < count; ++nValues) {
+ memset(buffer, fillValue, bufferSize);
+ swapperFunc(buffer + startPosition, values, nValues);
+
+ MOZ_ASSERT(memcmp(buffer, checkBuffer, startPosition) == 0);
+ DebugOnly<size_t> valuesEndPosition = startPosition + sizeof(T) * nValues;
+ MOZ_ASSERT(memcmp(buffer + valuesEndPosition,
+ checkBuffer + valuesEndPosition,
+ bufferSize - valuesEndPosition) == 0);
+ if (expectSwap == NoSwap) {
+ MOZ_ASSERT(memcmp(buffer + startPosition, values,
+ nValues * sizeof(T)) == 0);
+ }
+ for (size_t i = 0; i < nValues; ++i) {
+ MOZ_ASSERT(readerFunc(buffer + startPosition + sizeof(T) * i) ==
+ values[i]);
+ }
+ }
+ }
+}
+
+template<typename T, size_t count>
+void
+TestBulkSwapFromSub(enum SwapExpectation expectSwap,
+ const T (&values)[count],
+ void (*swapperFunc)(T*, const void*, unsigned int),
+ T (*readerFunc)(const void*))
+{
+ const size_t arraySize = 2 * count;
+ const size_t bufferSize = arraySize * sizeof(T);
+ static T buffer[arraySize];
+ const uint8_t fillValue = 0xa5;
+ static T checkBuffer[arraySize];
+
+ memset(checkBuffer, fillValue, bufferSize);
+
+ for (size_t startPosition = 0; startPosition < count; ++startPosition) {
+ for (size_t nValues = 0; nValues < (count - startPosition); ++nValues) {
+ memset(buffer, fillValue, bufferSize);
+ swapperFunc(buffer + startPosition, values, nValues);
+
+ MOZ_ASSERT(memcmp(buffer, checkBuffer, startPosition * sizeof(T)) == 0);
+ DebugOnly<size_t> valuesEndPosition = startPosition + nValues;
+ MOZ_ASSERT(memcmp(buffer + valuesEndPosition,
+ checkBuffer + valuesEndPosition,
+ (arraySize - valuesEndPosition) * sizeof(T)) == 0);
+ if (expectSwap == NoSwap) {
+ MOZ_ASSERT(memcmp(buffer + startPosition, values,
+ nValues * sizeof(T)) == 0);
+ }
+ for (size_t i = 0; i < nValues; ++i)
+ MOZ_ASSERT(readerFunc(buffer + startPosition + i) == values[i]);
+ }
+ }
+}
+
+
+template<typename T, size_t count>
+void
+TestBulkInPlaceSub(enum SwapExpectation expectSwap,
+ const T (&values)[count],
+ void (*swapperFunc)(T* p, unsigned int),
+ T (*readerFunc)(const void*))
+{
+ const size_t bufferCount = 4 * count;
+ const size_t bufferSize = bufferCount * sizeof(T);
+ static T buffer[bufferCount];
+ const T fillValue = 0xa5;
+ static T checkBuffer[bufferCount];
+
+ MOZ_ASSERT(bufferSize > 2 * sizeof(T));
+
+ memset(checkBuffer, fillValue, bufferSize);
+
+ for (size_t startPosition = 0; startPosition < count; ++startPosition) {
+ for (size_t nValues = 0; nValues < count; ++nValues) {
+ memset(buffer, fillValue, bufferSize);
+ memcpy(buffer + startPosition, values, nValues * sizeof(T));
+ swapperFunc(buffer + startPosition, nValues);
+
+ MOZ_ASSERT(memcmp(buffer, checkBuffer, startPosition * sizeof(T)) == 0);
+ DebugOnly<size_t> valuesEndPosition = startPosition + nValues;
+ MOZ_ASSERT(memcmp(buffer + valuesEndPosition,
+ checkBuffer + valuesEndPosition,
+ bufferSize - valuesEndPosition * sizeof(T)) == 0);
+ if (expectSwap == NoSwap) {
+ MOZ_ASSERT(memcmp(buffer + startPosition, values,
+ nValues * sizeof(T)) == 0);
+ }
+ for (size_t i = 0; i < nValues; ++i)
+ MOZ_ASSERT(readerFunc(buffer + startPosition + i) == values[i]);
+ }
+ }
+}
+
+template<typename T>
+struct Reader
+{
+};
+
+#define SPECIALIZE_READER(TYPE, READ_FUNC) \
+ template<> \
+ struct Reader<TYPE> \
+ { \
+ static TYPE readLE(const void* p) { return LittleEndian::READ_FUNC(p); } \
+ static TYPE readBE(const void* p) { return BigEndian::READ_FUNC(p); } \
+ };
+
+SPECIALIZE_READER(uint16_t, readUint16)
+SPECIALIZE_READER(uint32_t, readUint32)
+SPECIALIZE_READER(uint64_t, readUint64)
+SPECIALIZE_READER(int16_t, readInt16)
+SPECIALIZE_READER(int32_t, readInt32)
+SPECIALIZE_READER(int64_t, readInt64)
+
+template<typename T, size_t count>
+void
+TestBulkSwap(const T (&bytes)[count])
+{
+#if MOZ_LITTLE_ENDIAN
+ TestBulkSwapToSub(Swap, bytes, copyAndSwapToBigEndian<T>, Reader<T>::readBE);
+ TestBulkSwapFromSub(Swap, bytes, copyAndSwapFromBigEndian<T>, Reader<T>::readBE);
+ TestBulkSwapToSub(Swap, bytes, copyAndSwapToNetworkOrder<T>, Reader<T>::readBE);
+ TestBulkSwapFromSub(Swap, bytes, copyAndSwapFromNetworkOrder<T>, Reader<T>::readBE);
+#else
+ TestBulkSwapToSub(Swap, bytes, copyAndSwapToLittleEndian<T>, Reader<T>::readLE);
+ TestBulkSwapFromSub(Swap, bytes, copyAndSwapFromLittleEndian<T>, Reader<T>::readLE);
+#endif
+}
+
+template<typename T, size_t count>
+void
+TestBulkNoSwap(const T (&bytes)[count])
+{
+#if MOZ_LITTLE_ENDIAN
+ TestBulkSwapToSub(NoSwap, bytes, copyAndSwapToLittleEndian<T>, Reader<T>::readLE);
+ TestBulkSwapFromSub(NoSwap, bytes, copyAndSwapFromLittleEndian<T>, Reader<T>::readLE);
+#else
+ TestBulkSwapToSub(NoSwap, bytes, copyAndSwapToBigEndian<T>, Reader<T>::readBE);
+ TestBulkSwapFromSub(NoSwap, bytes, copyAndSwapFromBigEndian<T>, Reader<T>::readBE);
+ TestBulkSwapToSub(NoSwap, bytes, copyAndSwapToNetworkOrder<T>, Reader<T>::readBE);
+ TestBulkSwapFromSub(NoSwap, bytes, copyAndSwapFromNetworkOrder<T>, Reader<T>::readBE);
+#endif
+}
+
+template<typename T, size_t count>
+void
+TestBulkInPlaceSwap(const T (&bytes)[count])
+{
+#if MOZ_LITTLE_ENDIAN
+ TestBulkInPlaceSub(Swap, bytes, swapToBigEndianInPlace<T>, Reader<T>::readBE);
+ TestBulkInPlaceSub(Swap, bytes, swapFromBigEndianInPlace<T>, Reader<T>::readBE);
+ TestBulkInPlaceSub(Swap, bytes, swapToNetworkOrderInPlace<T>, Reader<T>::readBE);
+ TestBulkInPlaceSub(Swap, bytes, swapFromNetworkOrderInPlace<T>, Reader<T>::readBE);
+#else
+ TestBulkInPlaceSub(Swap, bytes, swapToLittleEndianInPlace<T>, Reader<T>::readLE);
+ TestBulkInPlaceSub(Swap, bytes, swapFromLittleEndianInPlace<T>, Reader<T>::readLE);
+#endif
+}
+
+template<typename T, size_t count>
+void
+TestBulkInPlaceNoSwap(const T (&bytes)[count])
+{
+#if MOZ_LITTLE_ENDIAN
+ TestBulkInPlaceSub(NoSwap, bytes, swapToLittleEndianInPlace<T>, Reader<T>::readLE);
+ TestBulkInPlaceSub(NoSwap, bytes, swapFromLittleEndianInPlace<T>, Reader<T>::readLE);
+#else
+ TestBulkInPlaceSub(NoSwap, bytes, swapToBigEndianInPlace<T>, Reader<T>::readBE);
+ TestBulkInPlaceSub(NoSwap, bytes, swapFromBigEndianInPlace<T>, Reader<T>::readBE);
+ TestBulkInPlaceSub(NoSwap, bytes, swapToNetworkOrderInPlace<T>, Reader<T>::readBE);
+ TestBulkInPlaceSub(NoSwap, bytes, swapFromNetworkOrderInPlace<T>, Reader<T>::readBE);
+#endif
+}
+
+int
+main()
+{
+ static const uint8_t unsigned_bytes[16] = { 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8,
+ 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8 };
+ static const int8_t signed_bytes[16] = { -0x0f, -0x0e, -0x0d, -0x0c, -0x0b, -0x0a, -0x09, -0x08,
+ -0x0f, -0x0e, -0x0d, -0x0c, -0x0b, -0x0a, -0x09, -0x08 };
+ static const uint16_t uint16_values[8] = { 0x102, 0x304, 0x506, 0x708, 0x102, 0x304, 0x506, 0x708 };
+ static const int16_t int16_values[8] = { int16_t(0xf1f2), int16_t(0xf3f4), int16_t(0xf5f6), int16_t(0xf7f8),
+ int16_t(0xf1f2), int16_t(0xf3f4), int16_t(0xf5f6), int16_t(0xf7f8) };
+ static const uint32_t uint32_values[4] = { 0x1020304, 0x5060708, 0x1020304, 0x5060708 };
+ static const int32_t int32_values[4] = { int32_t(0xf1f2f3f4), int32_t(0xf5f6f7f8),
+ int32_t(0xf1f2f3f4), int32_t(0xf5f6f7f8) };
+ static const uint64_t uint64_values[2] = { 0x102030405060708, 0x102030405060708 };
+ static const int64_t int64_values[2] = { int64_t(0xf1f2f3f4f5f6f7f8),
+ int64_t(0xf1f2f3f4f5f6f7f8) };
+ uint8_t buffer[8];
+
+ MOZ_ASSERT(LittleEndian::readUint16(&unsigned_bytes[0]) == 0x201);
+ MOZ_ASSERT(BigEndian::readUint16(&unsigned_bytes[0]) == 0x102);
+
+ MOZ_ASSERT(LittleEndian::readUint32(&unsigned_bytes[0]) == 0x4030201U);
+ MOZ_ASSERT(BigEndian::readUint32(&unsigned_bytes[0]) == 0x1020304U);
+
+ MOZ_ASSERT(LittleEndian::readUint64(&unsigned_bytes[0]) == 0x807060504030201ULL);
+ MOZ_ASSERT(BigEndian::readUint64(&unsigned_bytes[0]) == 0x102030405060708ULL);
+
+ LittleEndian::writeUint16(&buffer[0], 0x201);
+ MOZ_ASSERT(memcmp(&unsigned_bytes[0], &buffer[0], sizeof(uint16_t)) == 0);
+ BigEndian::writeUint16(&buffer[0], 0x102);
+ MOZ_ASSERT(memcmp(&unsigned_bytes[0], &buffer[0], sizeof(uint16_t)) == 0);
+
+ LittleEndian::writeUint32(&buffer[0], 0x4030201U);
+ MOZ_ASSERT(memcmp(&unsigned_bytes[0], &buffer[0], sizeof(uint32_t)) == 0);
+ BigEndian::writeUint32(&buffer[0], 0x1020304U);
+ MOZ_ASSERT(memcmp(&unsigned_bytes[0], &buffer[0], sizeof(uint32_t)) == 0);
+
+ LittleEndian::writeUint64(&buffer[0], 0x807060504030201ULL);
+ MOZ_ASSERT(memcmp(&unsigned_bytes[0], &buffer[0], sizeof(uint64_t)) == 0);
+ BigEndian::writeUint64(&buffer[0], 0x102030405060708ULL);
+ MOZ_ASSERT(memcmp(&unsigned_bytes[0], &buffer[0], sizeof(uint64_t)) == 0);
+
+ MOZ_ASSERT(LittleEndian::readInt16(&signed_bytes[0]) == int16_t(0xf2f1));
+ MOZ_ASSERT(BigEndian::readInt16(&signed_bytes[0]) == int16_t(0xf1f2));
+
+ MOZ_ASSERT(LittleEndian::readInt32(&signed_bytes[0]) == int32_t(0xf4f3f2f1));
+ MOZ_ASSERT(BigEndian::readInt32(&signed_bytes[0]) == int32_t(0xf1f2f3f4));
+
+ MOZ_ASSERT(LittleEndian::readInt64(&signed_bytes[0]) == int64_t(0xf8f7f6f5f4f3f2f1LL));
+ MOZ_ASSERT(BigEndian::readInt64(&signed_bytes[0]) == int64_t(0xf1f2f3f4f5f6f7f8LL));
+
+ LittleEndian::writeInt16(&buffer[0], 0xf2f1);
+ MOZ_ASSERT(memcmp(&signed_bytes[0], &buffer[0], sizeof(int16_t)) == 0);
+ BigEndian::writeInt16(&buffer[0], 0xf1f2);
+ MOZ_ASSERT(memcmp(&signed_bytes[0], &buffer[0], sizeof(int16_t)) == 0);
+
+ LittleEndian::writeInt32(&buffer[0], 0xf4f3f2f1);
+ MOZ_ASSERT(memcmp(&signed_bytes[0], &buffer[0], sizeof(int32_t)) == 0);
+ BigEndian::writeInt32(&buffer[0], 0xf1f2f3f4);
+ MOZ_ASSERT(memcmp(&signed_bytes[0], &buffer[0], sizeof(int32_t)) == 0);
+
+ LittleEndian::writeInt64(&buffer[0], 0xf8f7f6f5f4f3f2f1LL);
+ MOZ_ASSERT(memcmp(&signed_bytes[0], &buffer[0], sizeof(int64_t)) == 0);
+ BigEndian::writeInt64(&buffer[0], 0xf1f2f3f4f5f6f7f8LL);
+ MOZ_ASSERT(memcmp(&signed_bytes[0], &buffer[0], sizeof(int64_t)) == 0);
+
+ TestSingleSwap(uint16_t(0xf2f1), uint16_t(0xf1f2));
+ TestSingleSwap(uint32_t(0xf4f3f2f1), uint32_t(0xf1f2f3f4));
+ TestSingleSwap(uint64_t(0xf8f7f6f5f4f3f2f1), uint64_t(0xf1f2f3f4f5f6f7f8));
+
+ TestSingleSwap(int16_t(0xf2f1), int16_t(0xf1f2));
+ TestSingleSwap(int32_t(0xf4f3f2f1), int32_t(0xf1f2f3f4));
+ TestSingleSwap(int64_t(0xf8f7f6f5f4f3f2f1), int64_t(0xf1f2f3f4f5f6f7f8));
+
+ TestSingleNoSwap(uint16_t(0xf2f1), uint16_t(0xf2f1));
+ TestSingleNoSwap(uint32_t(0xf4f3f2f1), uint32_t(0xf4f3f2f1));
+ TestSingleNoSwap(uint64_t(0xf8f7f6f5f4f3f2f1), uint64_t(0xf8f7f6f5f4f3f2f1));
+
+ TestSingleNoSwap(int16_t(0xf2f1), int16_t(0xf2f1));
+ TestSingleNoSwap(int32_t(0xf4f3f2f1), int32_t(0xf4f3f2f1));
+ TestSingleNoSwap(int64_t(0xf8f7f6f5f4f3f2f1), int64_t(0xf8f7f6f5f4f3f2f1));
+
+ TestBulkSwap(uint16_values);
+ TestBulkSwap(int16_values);
+ TestBulkSwap(uint32_values);
+ TestBulkSwap(int32_values);
+ TestBulkSwap(uint64_values);
+ TestBulkSwap(int64_values);
+
+ TestBulkNoSwap(uint16_values);
+ TestBulkNoSwap(int16_values);
+ TestBulkNoSwap(uint32_values);
+ TestBulkNoSwap(int32_values);
+ TestBulkNoSwap(uint64_values);
+ TestBulkNoSwap(int64_values);
+
+ TestBulkInPlaceSwap(uint16_values);
+ TestBulkInPlaceSwap(int16_values);
+ TestBulkInPlaceSwap(uint32_values);
+ TestBulkInPlaceSwap(int32_values);
+ TestBulkInPlaceSwap(uint64_values);
+ TestBulkInPlaceSwap(int64_values);
+
+ TestBulkInPlaceNoSwap(uint16_values);
+ TestBulkInPlaceNoSwap(int16_values);
+ TestBulkInPlaceNoSwap(uint32_values);
+ TestBulkInPlaceNoSwap(int32_values);
+ TestBulkInPlaceNoSwap(uint64_values);
+ TestBulkInPlaceNoSwap(int64_values);
+
+ return 0;
+}
diff --git a/mfbt/tests/TestEnumSet.cpp b/mfbt/tests/TestEnumSet.cpp
new file mode 100644
index 0000000..dc43fe3
--- /dev/null
+++ b/mfbt/tests/TestEnumSet.cpp
@@ -0,0 +1,232 @@
+/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#include "mozilla/EnumSet.h"
+
+using namespace mozilla;
+
+enum SeaBird {
+ PENGUIN,
+ ALBATROSS,
+ FULMAR,
+ PRION,
+ SHEARWATER,
+ GADFLY_PETREL,
+ TRUE_PETREL,
+ DIVING_PETREL,
+ STORM_PETREL,
+ PELICAN,
+ GANNET,
+ BOOBY,
+ CORMORANT,
+ FRIGATEBIRD,
+ TROPICBIRD,
+ SKUA,
+ GULL,
+ TERN,
+ SKIMMER,
+ AUK
+};
+
+class EnumSetSuite {
+ public:
+ EnumSetSuite()
+ : mAlcidae(),
+ mDiomedeidae(ALBATROSS),
+ mPetrelProcellariidae(GADFLY_PETREL, TRUE_PETREL),
+ mNonPetrelProcellariidae(FULMAR, PRION, SHEARWATER),
+ mPetrels(GADFLY_PETREL, TRUE_PETREL, DIVING_PETREL, STORM_PETREL)
+ { }
+
+ void runTests() {
+ testSize();
+ testContains();
+ testAddTo();
+ testAdd();
+ testAddAll();
+ testUnion();
+ testRemoveFrom();
+ testRemove();
+ testRemoveAllFrom();
+ testRemoveAll();
+ testIntersect();
+ testInsersection();
+ testEquality();
+ testDuplicates();
+ }
+
+ private:
+ void testSize() {
+ MOZ_ASSERT(mAlcidae.size() == 0);
+ MOZ_ASSERT(mDiomedeidae.size() == 1);
+ MOZ_ASSERT(mPetrelProcellariidae.size() == 2);
+ MOZ_ASSERT(mNonPetrelProcellariidae.size() == 3);
+ MOZ_ASSERT(mPetrels.size() == 4);
+ }
+
+ void testContains() {
+ MOZ_ASSERT(!mPetrels.contains(PENGUIN));
+ MOZ_ASSERT(!mPetrels.contains(ALBATROSS));
+ MOZ_ASSERT(!mPetrels.contains(FULMAR));
+ MOZ_ASSERT(!mPetrels.contains(PRION));
+ MOZ_ASSERT(!mPetrels.contains(SHEARWATER));
+ MOZ_ASSERT(mPetrels.contains(GADFLY_PETREL));
+ MOZ_ASSERT(mPetrels.contains(TRUE_PETREL));
+ MOZ_ASSERT(mPetrels.contains(DIVING_PETREL));
+ MOZ_ASSERT(mPetrels.contains(STORM_PETREL));
+ MOZ_ASSERT(!mPetrels.contains(PELICAN));
+ MOZ_ASSERT(!mPetrels.contains(GANNET));
+ MOZ_ASSERT(!mPetrels.contains(BOOBY));
+ MOZ_ASSERT(!mPetrels.contains(CORMORANT));
+ MOZ_ASSERT(!mPetrels.contains(FRIGATEBIRD));
+ MOZ_ASSERT(!mPetrels.contains(TROPICBIRD));
+ MOZ_ASSERT(!mPetrels.contains(SKUA));
+ MOZ_ASSERT(!mPetrels.contains(GULL));
+ MOZ_ASSERT(!mPetrels.contains(TERN));
+ MOZ_ASSERT(!mPetrels.contains(SKIMMER));
+ MOZ_ASSERT(!mPetrels.contains(AUK));
+ }
+
+ void testCopy() {
+ EnumSet<SeaBird> likes = mPetrels;
+ likes -= TRUE_PETREL;
+ MOZ_ASSERT(mPetrels.size() == 4);
+ MOZ_ASSERT(mPetrels.contains(TRUE_PETREL));
+
+ MOZ_ASSERT(likes.size() == 3);
+ MOZ_ASSERT(likes.contains(GADFLY_PETREL));
+ MOZ_ASSERT(likes.contains(DIVING_PETREL));
+ MOZ_ASSERT(likes.contains(STORM_PETREL));
+ }
+
+ void testAddTo() {
+ EnumSet<SeaBird> seen = mPetrels;
+ seen += CORMORANT;
+ seen += TRUE_PETREL;
+ MOZ_ASSERT(mPetrels.size() == 4);
+ MOZ_ASSERT(!mPetrels.contains(CORMORANT));
+ MOZ_ASSERT(seen.size() == 5);
+ MOZ_ASSERT(seen.contains(GADFLY_PETREL));
+ MOZ_ASSERT(seen.contains(TRUE_PETREL));
+ MOZ_ASSERT(seen.contains(DIVING_PETREL));
+ MOZ_ASSERT(seen.contains(STORM_PETREL));
+ MOZ_ASSERT(seen.contains(CORMORANT));
+ }
+
+ void testAdd() {
+ EnumSet<SeaBird> seen = mPetrels + CORMORANT +
+ STORM_PETREL;
+ MOZ_ASSERT(mPetrels.size() == 4);
+ MOZ_ASSERT(!mPetrels.contains(CORMORANT));
+ MOZ_ASSERT(seen.size() == 5);
+ MOZ_ASSERT(seen.contains(GADFLY_PETREL));
+ MOZ_ASSERT(seen.contains(TRUE_PETREL));
+ MOZ_ASSERT(seen.contains(DIVING_PETREL));
+ MOZ_ASSERT(seen.contains(STORM_PETREL));
+ MOZ_ASSERT(seen.contains(CORMORANT));
+ }
+
+ void testAddAll() {
+ EnumSet<SeaBird> procellariidae;
+ procellariidae += mPetrelProcellariidae;
+ procellariidae += mNonPetrelProcellariidae;
+ MOZ_ASSERT(procellariidae.size() == 5);
+
+ // Both procellariidae and mPetrels include GADFLY_PERTEL and TRUE_PETREL
+ EnumSet<SeaBird> procellariiformes;
+ procellariiformes += mDiomedeidae;
+ procellariiformes += procellariidae;
+ procellariiformes += mPetrels;
+ MOZ_ASSERT(procellariiformes.size() == 8);
+ }
+
+ void testUnion() {
+ EnumSet<SeaBird> procellariidae = mPetrelProcellariidae +
+ mNonPetrelProcellariidae;
+ MOZ_ASSERT(procellariidae.size() == 5);
+
+ // Both procellariidae and mPetrels include GADFLY_PETREL and TRUE_PETREL
+ EnumSet<SeaBird> procellariiformes = mDiomedeidae + procellariidae +
+ mPetrels;
+ MOZ_ASSERT(procellariiformes.size() == 8);
+ }
+
+ void testRemoveFrom() {
+ EnumSet<SeaBird> likes = mPetrels;
+ likes -= TRUE_PETREL;
+ likes -= DIVING_PETREL;
+ MOZ_ASSERT(likes.size() == 2);
+ MOZ_ASSERT(likes.contains(GADFLY_PETREL));
+ MOZ_ASSERT(likes.contains(STORM_PETREL));
+ }
+
+ void testRemove() {
+ EnumSet<SeaBird> likes = mPetrels - TRUE_PETREL -
+ DIVING_PETREL;
+ MOZ_ASSERT(likes.size() == 2);
+ MOZ_ASSERT(likes.contains(GADFLY_PETREL));
+ MOZ_ASSERT(likes.contains(STORM_PETREL));
+ }
+
+ void testRemoveAllFrom() {
+ EnumSet<SeaBird> likes = mPetrels;
+ likes -= mPetrelProcellariidae;
+ MOZ_ASSERT(likes.size() == 2);
+ MOZ_ASSERT(likes.contains(DIVING_PETREL));
+ MOZ_ASSERT(likes.contains(STORM_PETREL));
+ }
+
+ void testRemoveAll() {
+ EnumSet<SeaBird> likes = mPetrels - mPetrelProcellariidae;
+ MOZ_ASSERT(likes.size() == 2);
+ MOZ_ASSERT(likes.contains(DIVING_PETREL));
+ MOZ_ASSERT(likes.contains(STORM_PETREL));
+ }
+
+ void testIntersect() {
+ EnumSet<SeaBird> likes = mPetrels;
+ likes &= mPetrelProcellariidae;
+ MOZ_ASSERT(likes.size() == 2);
+ MOZ_ASSERT(likes.contains(GADFLY_PETREL));
+ MOZ_ASSERT(likes.contains(TRUE_PETREL));
+ }
+
+ void testInsersection() {
+ EnumSet<SeaBird> likes = mPetrels & mPetrelProcellariidae;
+ MOZ_ASSERT(likes.size() == 2);
+ MOZ_ASSERT(likes.contains(GADFLY_PETREL));
+ MOZ_ASSERT(likes.contains(TRUE_PETREL));
+ }
+
+ void testEquality() {
+ EnumSet<SeaBird> likes = mPetrels & mPetrelProcellariidae;
+ MOZ_ASSERT(likes == EnumSet<SeaBird>(GADFLY_PETREL,
+ TRUE_PETREL));
+ }
+
+ void testDuplicates() {
+ EnumSet<SeaBird> likes = mPetrels;
+ likes += GADFLY_PETREL;
+ likes += TRUE_PETREL;
+ likes += DIVING_PETREL;
+ likes += STORM_PETREL;
+ MOZ_ASSERT(likes.size() == 4);
+ MOZ_ASSERT(likes == mPetrels);
+ }
+
+
+ EnumSet<SeaBird> mAlcidae;
+ EnumSet<SeaBird> mDiomedeidae;
+ EnumSet<SeaBird> mPetrelProcellariidae;
+ EnumSet<SeaBird> mNonPetrelProcellariidae;
+ EnumSet<SeaBird> mPetrels;
+};
+
+int main()
+{
+ EnumSetSuite suite;
+ suite.runTests();
+ return 0;
+}
diff --git a/mfbt/tests/TestPoisonArea.cpp b/mfbt/tests/TestPoisonArea.cpp
new file mode 100644
index 0000000..cf2417a
--- /dev/null
+++ b/mfbt/tests/TestPoisonArea.cpp
@@ -0,0 +1,654 @@
+/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim:set ts=2 sw=2 sts=2 et cindent: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/.
+ */
+
+/* Code in this file needs to be kept in sync with code in nsPresArena.cpp.
+ *
+ * We want to use a fixed address for frame poisoning so that it is readily
+ * identifiable in crash dumps. Whether such an address is available
+ * without any special setup depends on the system configuration.
+ *
+ * All current 64-bit CPUs (with the possible exception of PowerPC64)
+ * reserve the vast majority of the virtual address space for future
+ * hardware extensions; valid addresses must be below some break point
+ * between 2**48 and 2**54, depending on exactly which chip you have. Some
+ * chips (notably amd64) also allow the use of the *highest* 2**48 -- 2**54
+ * addresses. Thus, if user space pointers are 64 bits wide, we can just
+ * use an address outside this range, and no more is required. To
+ * accommodate the chips that allow very high addresses to be valid, the
+ * value chosen is close to 2**63 (that is, in the middle of the space).
+ *
+ * In most cases, a purely 32-bit operating system must reserve some
+ * fraction of the address space for its own use. Contemporary 32-bit OSes
+ * tend to take the high gigabyte or so (0xC000_0000 on up). If we can
+ * prove that high addresses are reserved to the kernel, we can use an
+ * address in that region. Unfortunately, not all 32-bit OSes do this;
+ * OSX 10.4 might not, and it is unclear what mobile OSes are like
+ * (some 32-bit CPUs make it very easy for the kernel to exist in its own
+ * private address space).
+ *
+ * Furthermore, when a 32-bit user space process is running on a 64-bit
+ * kernel, the operating system has no need to reserve any of the space that
+ * the process can see, and generally does not do so. This is the scenario
+ * of greatest concern, since it covers all contemporary OSX iterations
+ * (10.5+) as well as Windows Vista and 7 on newer amd64 hardware. Linux on
+ * amd64 is generally run as a pure 64-bit environment, but its 32-bit
+ * compatibility mode also has this property.
+ *
+ * Thus, when user space pointers are 32 bits wide, we need to validate
+ * our chosen address, and possibly *make* it a good poison address by
+ * allocating a page around it and marking it inaccessible. The algorithm
+ * for this is:
+ *
+ * 1. Attempt to make the page surrounding the poison address a reserved,
+ * inaccessible memory region using OS primitives. On Windows, this is
+ * done with VirtualAlloc(MEM_RESERVE); on Unix, mmap(PROT_NONE).
+ *
+ * 2. If mmap/VirtualAlloc failed, there are two possible reasons: either
+ * the region is reserved to the kernel and no further action is
+ * required, or there is already usable memory in this area and we have
+ * to pick a different address. The tricky part is knowing which case
+ * we have, without attempting to access the region. On Windows, we
+ * rely on GetSystemInfo()'s reported upper and lower bounds of the
+ * application memory area. On Unix, there is nothing devoted to the
+ * purpose, but seeing if madvise() fails is close enough (it *might*
+ * disrupt someone else's use of the memory region, but not by as much
+ * as anything else available).
+ *
+ * Be aware of these gotchas:
+ *
+ * 1. We cannot use mmap() with MAP_FIXED. MAP_FIXED is defined to
+ * _replace_ any existing mapping in the region, if necessary to satisfy
+ * the request. Obviously, as we are blindly attempting to acquire a
+ * page at a constant address, we must not do this, lest we overwrite
+ * someone else's allocation.
+ *
+ * 2. For the same reason, we cannot blindly use mprotect() if mmap() fails.
+ *
+ * 3. madvise() may fail when applied to a 'magic' memory region provided as
+ * a kernel/user interface. Fortunately, the only such case I know about
+ * is the "vsyscall" area (not to be confused with the "vdso" area) for
+ * *64*-bit processes on Linux - and we don't even run this code for
+ * 64-bit processes.
+ *
+ * 4. VirtualQuery() does not produce any useful information if
+ * applied to kernel memory - in fact, it doesn't write its output
+ * at all. Thus, it is not used here.
+ */
+
+// MAP_ANON(YMOUS) is not in any standard, and the C99 PRI* macros are
+// not in C++98. Add defines as necessary.
+#define __STDC_FORMAT_MACROS
+#define _GNU_SOURCE 1
+#define _DARWIN_C_SOURCE 1
+
+#include <stddef.h>
+
+#ifndef _WIN32
+#include <inttypes.h>
+#else
+#define PRIxPTR "Ix"
+typedef unsigned int uint32_t;
+// MSVC defines uintptr_t in <crtdefs.h> which is brought in implicitly
+#endif
+
+#include <errno.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+#ifdef _WIN32
+#include <windows.h>
+#elif defined(__OS2__)
+#include <sys/types.h>
+#include <unistd.h>
+#include <setjmp.h>
+#define INCL_DOS
+#include <os2.h>
+#else
+#include <sys/types.h>
+#include <fcntl.h>
+#include <signal.h>
+#include <unistd.h>
+#include <sys/stat.h>
+#include <sys/wait.h>
+
+#include <sys/mman.h>
+#ifndef MAP_ANON
+#ifdef MAP_ANONYMOUS
+#define MAP_ANON MAP_ANONYMOUS
+#else
+#error "Don't know how to get anonymous memory"
+#endif
+#endif
+#endif
+
+#define SIZxPTR ((int)(sizeof(uintptr_t)*2))
+
+/* This program assumes that a whole number of return instructions fit into
+ * 32 bits, and that 32-bit alignment is sufficient for a branch destination.
+ * For architectures where this is not true, fiddling with RETURN_INSTR_TYPE
+ * can be enough.
+ */
+
+#if defined __i386__ || defined __x86_64__ || \
+ defined __i386 || defined __x86_64 || \
+ defined _M_IX86 || defined _M_AMD64
+#define RETURN_INSTR 0xC3C3C3C3 /* ret; ret; ret; ret */
+
+#elif defined __arm__ || defined _M_ARM
+#define RETURN_INSTR 0xE12FFF1E /* bx lr */
+
+// PPC has its own style of CPU-id #defines. There is no Windows for
+// PPC as far as I know, so no _M_ variant.
+#elif defined _ARCH_PPC || defined _ARCH_PWR || defined _ARCH_PWR2
+#define RETURN_INSTR 0x4E800020 /* blr */
+
+#elif defined __sparc || defined __sparcv9
+#define RETURN_INSTR 0x81c3e008 /* retl */
+
+#elif defined __alpha
+#define RETURN_INSTR 0x6bfa8001 /* ret */
+
+#elif defined __hppa
+#define RETURN_INSTR 0xe840c002 /* bv,n r0(rp) */
+
+#elif defined __mips
+#define RETURN_INSTR 0x03e00008 /* jr ra */
+
+#ifdef __MIPSEL
+/* On mipsel, jr ra needs to be followed by a nop.
+ 0x03e00008 as a 64 bits integer just does that */
+#define RETURN_INSTR_TYPE uint64_t
+#endif
+
+#elif defined __s390__
+#define RETURN_INSTR 0x07fe0000 /* br %r14 */
+
+#elif defined __ia64
+struct ia64_instr { uint32_t i[4]; };
+static const ia64_instr _return_instr =
+ {{ 0x00000011, 0x00000001, 0x80000200, 0x00840008 }}; /* br.ret.sptk.many b0 */
+
+#define RETURN_INSTR _return_instr
+#define RETURN_INSTR_TYPE ia64_instr
+
+#else
+#error "Need return instruction for this architecture"
+#endif
+
+#ifndef RETURN_INSTR_TYPE
+#define RETURN_INSTR_TYPE uint32_t
+#endif
+
+// Miscellaneous Windows/Unix portability gumph
+
+#ifdef _WIN32
+// Uses of this function deliberately leak the string.
+static LPSTR
+StrW32Error(DWORD errcode)
+{
+ LPSTR errmsg;
+ FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER |
+ FORMAT_MESSAGE_FROM_SYSTEM |
+ FORMAT_MESSAGE_IGNORE_INSERTS,
+ NULL, errcode, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
+ (LPSTR) &errmsg, 0, NULL);
+
+ // FormatMessage puts an unwanted newline at the end of the string
+ size_t n = strlen(errmsg)-1;
+ while (errmsg[n] == '\r' || errmsg[n] == '\n') n--;
+ errmsg[n+1] = '\0';
+ return errmsg;
+}
+#define LastErrMsg() (StrW32Error(GetLastError()))
+
+// Because we use VirtualAlloc in MEM_RESERVE mode, the "page size" we want
+// is the allocation granularity.
+static SYSTEM_INFO _sinfo;
+#undef PAGESIZE
+#define PAGESIZE (_sinfo.dwAllocationGranularity)
+
+
+static void *
+ReserveRegion(uintptr_t request, bool accessible)
+{
+ return VirtualAlloc((void *)request, PAGESIZE,
+ accessible ? MEM_RESERVE|MEM_COMMIT : MEM_RESERVE,
+ accessible ? PAGE_EXECUTE_READWRITE : PAGE_NOACCESS);
+}
+
+static void
+ReleaseRegion(void *page)
+{
+ VirtualFree(page, PAGESIZE, MEM_RELEASE);
+}
+
+static bool
+ProbeRegion(uintptr_t page)
+{
+ if (page >= (uintptr_t)_sinfo.lpMaximumApplicationAddress &&
+ page + PAGESIZE >= (uintptr_t)_sinfo.lpMaximumApplicationAddress) {
+ return true;
+ } else {
+ return false;
+ }
+}
+
+static bool
+MakeRegionExecutable(void *)
+{
+ return false;
+}
+
+#undef MAP_FAILED
+#define MAP_FAILED 0
+
+#elif defined(__OS2__)
+
+// page size is always 4k
+#undef PAGESIZE
+#define PAGESIZE 0x1000
+static unsigned long rc = 0;
+
+char * LastErrMsg()
+{
+ char * errmsg = (char *)malloc(16);
+ sprintf(errmsg, "rc= %ld", rc);
+ rc = 0;
+ return errmsg;
+}
+
+static void *
+ReserveRegion(uintptr_t request, bool accessible)
+{
+ // OS/2 doesn't support allocation at an arbitrary address,
+ // so return an address that is known to be invalid.
+ if (request) {
+ return (void*)0xFFFD0000;
+ }
+ void * mem = 0;
+ rc = DosAllocMem(&mem, PAGESIZE,
+ (accessible ? PAG_COMMIT : 0) | PAG_READ | PAG_WRITE);
+ return rc ? 0 : mem;
+}
+
+static void
+ReleaseRegion(void *page)
+{
+ return;
+}
+
+static bool
+ProbeRegion(uintptr_t page)
+{
+ // There's no reliable way to probe an address in the system
+ // arena other than by touching it and seeing if a trap occurs.
+ return false;
+}
+
+static bool
+MakeRegionExecutable(void *page)
+{
+ rc = DosSetMem(page, PAGESIZE, PAG_READ | PAG_WRITE | PAG_EXECUTE);
+ return rc ? true : false;
+}
+
+typedef struct _XCPT {
+ EXCEPTIONREGISTRATIONRECORD regrec;
+ jmp_buf jmpbuf;
+} XCPT;
+
+static unsigned long _System
+ExceptionHandler(PEXCEPTIONREPORTRECORD pReport,
+ PEXCEPTIONREGISTRATIONRECORD pRegRec,
+ PCONTEXTRECORD pContext, PVOID pVoid)
+{
+ if (pReport->fHandlerFlags == 0) {
+ longjmp(((XCPT*)pRegRec)->jmpbuf, pReport->ExceptionNum);
+ }
+ return XCPT_CONTINUE_SEARCH;
+}
+
+#undef MAP_FAILED
+#define MAP_FAILED 0
+
+#else // Unix
+
+#define LastErrMsg() (strerror(errno))
+
+static unsigned long _pagesize;
+#define PAGESIZE _pagesize
+
+static void *
+ReserveRegion(uintptr_t request, bool accessible)
+{
+ return mmap(reinterpret_cast<void*>(request), PAGESIZE,
+ accessible ? PROT_READ|PROT_WRITE : PROT_NONE,
+ MAP_PRIVATE|MAP_ANON, -1, 0);
+}
+
+static void
+ReleaseRegion(void *page)
+{
+ munmap(page, PAGESIZE);
+}
+
+static bool
+ProbeRegion(uintptr_t page)
+{
+ if (madvise(reinterpret_cast<void*>(page), PAGESIZE, MADV_NORMAL)) {
+ return true;
+ } else {
+ return false;
+ }
+}
+
+static int
+MakeRegionExecutable(void *page)
+{
+ return mprotect((caddr_t)page, PAGESIZE, PROT_READ|PROT_WRITE|PROT_EXEC);
+}
+
+#endif
+
+static uintptr_t
+ReservePoisonArea()
+{
+ if (sizeof(uintptr_t) == 8) {
+ // Use the hardware-inaccessible region.
+ // We have to avoid 64-bit constants and shifts by 32 bits, since this
+ // code is compiled in 32-bit mode, although it is never executed there.
+ uintptr_t result = (((uintptr_t(0x7FFFFFFFu) << 31) << 1 |
+ uintptr_t(0xF0DEAFFFu)) &
+ ~uintptr_t(PAGESIZE-1));
+ printf("INFO | poison area assumed at 0x%.*" PRIxPTR "\n", SIZxPTR, result);
+ return result;
+ } else {
+ // First see if we can allocate the preferred poison address from the OS.
+ uintptr_t candidate = (0xF0DEAFFF & ~(PAGESIZE-1));
+ void *result = ReserveRegion(candidate, false);
+ if (result == (void *)candidate) {
+ // success - inaccessible page allocated
+ printf("INFO | poison area allocated at 0x%.*" PRIxPTR
+ " (preferred addr)\n", SIZxPTR, (uintptr_t)result);
+ return candidate;
+ }
+
+ // That didn't work, so see if the preferred address is within a range
+ // of permanently inacessible memory.
+ if (ProbeRegion(candidate)) {
+ // success - selected page cannot be usable memory
+ if (result != MAP_FAILED)
+ ReleaseRegion(result);
+ printf("INFO | poison area assumed at 0x%.*" PRIxPTR
+ " (preferred addr)\n", SIZxPTR, candidate);
+ return candidate;
+ }
+
+ // The preferred address is already in use. Did the OS give us a
+ // consolation prize?
+ if (result != MAP_FAILED) {
+ printf("INFO | poison area allocated at 0x%.*" PRIxPTR
+ " (consolation prize)\n", SIZxPTR, (uintptr_t)result);
+ return (uintptr_t)result;
+ }
+
+ // It didn't, so try to allocate again, without any constraint on
+ // the address.
+ result = ReserveRegion(0, false);
+ if (result != MAP_FAILED) {
+ printf("INFO | poison area allocated at 0x%.*" PRIxPTR
+ " (fallback)\n", SIZxPTR, (uintptr_t)result);
+ return (uintptr_t)result;
+ }
+
+ printf("ERROR | no usable poison area found\n");
+ return 0;
+ }
+}
+
+/* The "positive control" area confirms that we can allocate a page with the
+ * proper characteristics.
+ */
+static uintptr_t
+ReservePositiveControl()
+{
+
+ void *result = ReserveRegion(0, false);
+ if (result == MAP_FAILED) {
+ printf("ERROR | allocating positive control | %s\n", LastErrMsg());
+ return 0;
+ }
+ printf("INFO | positive control allocated at 0x%.*" PRIxPTR "\n",
+ SIZxPTR, (uintptr_t)result);
+ return (uintptr_t)result;
+}
+
+/* The "negative control" area confirms that our probe logic does detect a
+ * page that is readable, writable, or executable.
+ */
+static uintptr_t
+ReserveNegativeControl()
+{
+ void *result = ReserveRegion(0, true);
+ if (result == MAP_FAILED) {
+ printf("ERROR | allocating negative control | %s\n", LastErrMsg());
+ return 0;
+ }
+
+ // Fill the page with return instructions.
+ RETURN_INSTR_TYPE *p = (RETURN_INSTR_TYPE *)result;
+ RETURN_INSTR_TYPE *limit = (RETURN_INSTR_TYPE *)(((char *)result) + PAGESIZE);
+ while (p < limit)
+ *p++ = RETURN_INSTR;
+
+ // Now mark it executable as well as readable and writable.
+ // (mmap(PROT_EXEC) may fail when applied to anonymous memory.)
+
+ if (MakeRegionExecutable(result)) {
+ printf("ERROR | making negative control executable | %s\n", LastErrMsg());
+ return 0;
+ }
+
+ printf("INFO | negative control allocated at 0x%.*" PRIxPTR "\n",
+ SIZxPTR, (uintptr_t)result);
+ return (uintptr_t)result;
+}
+
+static void
+JumpTo(uintptr_t opaddr)
+{
+#ifdef __ia64
+ struct func_call {
+ uintptr_t func;
+ uintptr_t gp;
+ } call = { opaddr, };
+ ((void (*)())&call)();
+#else
+ ((void (*)())opaddr)();
+#endif
+}
+
+#ifdef _WIN32
+static BOOL
+IsBadExecPtr(uintptr_t ptr)
+{
+ BOOL ret = false;
+
+#ifdef _MSC_VER
+ __try {
+ JumpTo(ptr);
+ } __except (EXCEPTION_EXECUTE_HANDLER) {
+ ret = true;
+ }
+#else
+ printf("INFO | exec test not supported on MinGW build\n");
+ // We do our best
+ ret = IsBadReadPtr((const void*)ptr, 1);
+#endif
+ return ret;
+}
+#endif
+
+/* Test each page. */
+static bool
+TestPage(const char *pagelabel, uintptr_t pageaddr, int should_succeed)
+{
+ const char *oplabel;
+ uintptr_t opaddr;
+
+ bool failed = false;
+ for (unsigned int test = 0; test < 3; test++) {
+ switch (test) {
+ // The execute test must be done before the write test, because the
+ // write test will clobber memory at the target address.
+ case 0: oplabel = "reading"; opaddr = pageaddr + PAGESIZE/2 - 1; break;
+ case 1: oplabel = "executing"; opaddr = pageaddr + PAGESIZE/2; break;
+ case 2: oplabel = "writing"; opaddr = pageaddr + PAGESIZE/2 - 1; break;
+ default: abort();
+ }
+
+#ifdef _WIN32
+ BOOL badptr;
+
+ switch (test) {
+ case 0: badptr = IsBadReadPtr((const void*)opaddr, 1); break;
+ case 1: badptr = IsBadExecPtr(opaddr); break;
+ case 2: badptr = IsBadWritePtr((void*)opaddr, 1); break;
+ default: abort();
+ }
+
+ if (badptr) {
+ if (should_succeed) {
+ printf("TEST-UNEXPECTED-FAIL | %s %s\n", oplabel, pagelabel);
+ failed = true;
+ } else {
+ printf("TEST-PASS | %s %s\n", oplabel, pagelabel);
+ }
+ } else {
+ // if control reaches this point the probe succeeded
+ if (should_succeed) {
+ printf("TEST-PASS | %s %s\n", oplabel, pagelabel);
+ } else {
+ printf("TEST-UNEXPECTED-FAIL | %s %s\n", oplabel, pagelabel);
+ failed = true;
+ }
+ }
+#elif defined(__OS2__)
+ XCPT xcpt;
+ volatile int code = setjmp(xcpt.jmpbuf);
+
+ if (!code) {
+ xcpt.regrec.prev_structure = 0;
+ xcpt.regrec.ExceptionHandler = ExceptionHandler;
+ DosSetExceptionHandler(&xcpt.regrec);
+ unsigned char scratch;
+ switch (test) {
+ case 0: scratch = *(volatile unsigned char *)opaddr; break;
+ case 1: ((void (*)())opaddr)(); break;
+ case 2: *(volatile unsigned char *)opaddr = 0; break;
+ default: abort();
+ }
+ }
+
+ if (code) {
+ if (should_succeed) {
+ printf("TEST-UNEXPECTED-FAIL | %s %s | exception code %x\n",
+ oplabel, pagelabel, code);
+ failed = true;
+ } else {
+ printf("TEST-PASS | %s %s | exception code %x\n",
+ oplabel, pagelabel, code);
+ }
+ } else {
+ if (should_succeed) {
+ printf("TEST-PASS | %s %s\n", oplabel, pagelabel);
+ } else {
+ printf("TEST-UNEXPECTED-FAIL | %s %s\n", oplabel, pagelabel);
+ failed = true;
+ }
+ DosUnsetExceptionHandler(&xcpt.regrec);
+ }
+#else
+ pid_t pid = fork();
+ if (pid == -1) {
+ printf("ERROR | %s %s | fork=%s\n", oplabel, pagelabel,
+ LastErrMsg());
+ exit(2);
+ } else if (pid == 0) {
+ volatile unsigned char scratch;
+ switch (test) {
+ case 0: scratch = *(volatile unsigned char *)opaddr; break;
+ case 1: JumpTo(opaddr); break;
+ case 2: *(volatile unsigned char *)opaddr = 0; break;
+ default: abort();
+ }
+ (void)scratch;
+ _exit(0);
+ } else {
+ int status;
+ if (waitpid(pid, &status, 0) != pid) {
+ printf("ERROR | %s %s | wait=%s\n", oplabel, pagelabel,
+ LastErrMsg());
+ exit(2);
+ }
+
+ if (WIFEXITED(status) && WEXITSTATUS(status) == 0) {
+ if (should_succeed) {
+ printf("TEST-PASS | %s %s\n", oplabel, pagelabel);
+ } else {
+ printf("TEST-UNEXPECTED-FAIL | %s %s | unexpected successful exit\n",
+ oplabel, pagelabel);
+ failed = true;
+ }
+ } else if (WIFEXITED(status)) {
+ printf("ERROR | %s %s | unexpected exit code %d\n",
+ oplabel, pagelabel, WEXITSTATUS(status));
+ exit(2);
+ } else if (WIFSIGNALED(status)) {
+ if (should_succeed) {
+ printf("TEST-UNEXPECTED-FAIL | %s %s | unexpected signal %d\n",
+ oplabel, pagelabel, WTERMSIG(status));
+ failed = true;
+ } else {
+ printf("TEST-PASS | %s %s | signal %d (as expected)\n",
+ oplabel, pagelabel, WTERMSIG(status));
+ }
+ } else {
+ printf("ERROR | %s %s | unexpected exit status %d\n",
+ oplabel, pagelabel, status);
+ exit(2);
+ }
+ }
+#endif
+ }
+ return failed;
+}
+
+int
+main()
+{
+#ifdef _WIN32
+ GetSystemInfo(&_sinfo);
+#elif !defined(__OS2__)
+ _pagesize = sysconf(_SC_PAGESIZE);
+#endif
+
+ uintptr_t ncontrol = ReserveNegativeControl();
+ uintptr_t pcontrol = ReservePositiveControl();
+ uintptr_t poison = ReservePoisonArea();
+
+ if (!ncontrol || !pcontrol || !poison)
+ return 2;
+
+ bool failed = false;
+ failed |= TestPage("negative control", ncontrol, 1);
+ failed |= TestPage("positive control", pcontrol, 0);
+ failed |= TestPage("poison area", poison, 0);
+
+ return failed ? 1 : 0;
+}
diff --git a/mfbt/tests/TestSHA1.cpp b/mfbt/tests/TestSHA1.cpp
new file mode 100644
index 0000000..0d30dbe
--- /dev/null
+++ b/mfbt/tests/TestSHA1.cpp
@@ -0,0 +1,204 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#include "mozilla/Assertions.h"
+#include "mozilla/SHA1.h"
+
+using mozilla::SHA1Sum;
+
+static unsigned int testV[1024] = {
+ 0x048edc1a, 0x4345588c, 0x0ef03cbf, 0x1d6438f5, 0x094e0a1e, 0x68535f60,
+ 0x14e8c927, 0x60190043, 0x5d640ab7, 0x73dc7c62, 0x364223f9, 0x47320292,
+ 0x3924cae0, 0x5f6b26d3, 0x5efa04ef, 0x7aab361e, 0x2773b1aa, 0x1631b07d,
+ 0x385b5dd1, 0x26c809b0, 0x28ad3a9f, 0x0315292a, 0x1a544e67, 0x1e79dcb9,
+ 0x787683e8, 0x3a591c75, 0x1dd338c7, 0x01c539e5, 0x1c15b23e, 0x0697c25c,
+ 0x4df5fd45, 0x672aa324, 0x39f74e6e, 0x269cdd5f, 0x087b6fce, 0x293509db,
+ 0x0aef54a9, 0x210c4cc5, 0x29d6dc4a, 0x16320825, 0x3ab7b181, 0x56d6fd25,
+ 0x6837fda2, 0x3e7994c2, 0x37f77529, 0x48c85472, 0x424fd84d, 0x00aba7fa,
+ 0x6d8475de, 0x354634a7, 0x0c73bb49, 0x0a335de6, 0x0a9ea542, 0x5ffb31f1,
+ 0x00a6a3f2, 0x76b14a03, 0x1e436a37, 0x173b766a, 0x33cf3ca0, 0x34eb0f1a,
+ 0x4ca073ee, 0x27591fe6, 0x5eaf3356, 0x10c24493, 0x1bad88b6, 0x676f2309,
+ 0x7f5e2d91, 0x74bd4c83, 0x66549b43, 0x52ffdf24, 0x2dfa0a83, 0x7c3e1cbf,
+ 0x1edf87fc, 0x1f6fa930, 0x7c29bc74, 0x374bcd2f, 0x5b43de94, 0x0d09a3a6,
+ 0x7437ecb0, 0x635117f8, 0x2aa78f65, 0x2c788958, 0x098cb9f3, 0x13ed5b3f,
+ 0x41b7c7ba, 0x696b2d88, 0x42e20d63, 0x69585b1d, 0x4a9b027c, 0x0c761cba,
+ 0x563bdbc4, 0x3bde2f5b, 0x0bab9730, 0x7740104c, 0x11641702, 0x26f03c32,
+ 0x011a87c6, 0x2c5e4e6c, 0x46c34200, 0x6a167e84, 0x34205728, 0x0e8a6152,
+ 0x0014604b, 0x6793bacd, 0x442bca9c, 0x6f2018ce, 0x4313e07e, 0x77f2c69c,
+ 0x62621441, 0x47bf6358, 0x59c45e04, 0x16ba3426, 0x6ac0c19d, 0x20218c6b,
+ 0x510b4ddc, 0x585f6c9d, 0x1ed02b0c, 0x366bf0a9, 0x131c7f59, 0x0ebcd320,
+ 0x00ca858a, 0x5efbcb77, 0x2a7a1859, 0x64bb5afd, 0x76258886, 0x6505c895,
+ 0x602cfa32, 0x17040942, 0x783df744, 0x3838e0ae, 0x6a021e39, 0x4c8c9c5a,
+ 0x4a5e96b6, 0x10f4477d, 0x247fda4f, 0x4c390400, 0x0cbe048c, 0x7b547d26,
+ 0x1e2e6897, 0x4ba7e01b, 0x5cfea1bb, 0x39a2d199, 0x45aee64a, 0x12615500,
+ 0x0151615f, 0x1a9f5d33, 0x4542ed44, 0x101357eb, 0x35a16b1f, 0x3420b3e1,
+ 0x6442bac7, 0x1c0f2a8c, 0x68d642f1, 0x45744fc4, 0x048e60cb, 0x5f217f44,
+ 0x6cc7d151, 0x27f41984, 0x2d01eb09, 0x2bb15aea, 0x6dda49f8, 0x590dd6bc,
+ 0x280cc20b, 0x7e2592b5, 0x043642f0, 0x292b5d29, 0x2e0a9b69, 0x41162471,
+ 0x1e55db6b, 0x648b96fe, 0x05f8f9d1, 0x4a9d4cbb, 0x38517039, 0x2b0f8917,
+ 0x4d1e67bb, 0x713e0974, 0x64fdf214, 0x11223963, 0x2bd09d24, 0x19924092,
+ 0x4b4a70f0, 0x1ece6b03, 0x1780c9c1, 0x09b4c3ac, 0x58ac7e73, 0x5c9a4747,
+ 0x321f943b, 0x41167667, 0x3a19cf8c, 0x53f4144d, 0x03a498de, 0x6fb4b742,
+ 0x54d793cb, 0x7ee164e2, 0x501af74c, 0x43201e7f, 0x0ad581be, 0x497f046a,
+ 0x3b1d2a9f, 0x53b88eb0, 0x2c3a26c5, 0x5ae970ba, 0x7d7ee4ff, 0x471366c5,
+ 0x46119703, 0x3bfc2e58, 0x456d6c4f, 0x4b6bb181, 0x45d7c872, 0x0d023221,
+ 0x021176d1, 0x4195ad44, 0x4621ec90, 0x3ae68279, 0x57952f71, 0x1796080c,
+ 0x228077bb, 0x5e2b7fee, 0x3d71dd88, 0x4a651849, 0x7f1c8081, 0x04c333fc,
+ 0x1f99bff6, 0x11b7754c, 0x740be324, 0x069bf2e2, 0x0802f3e0, 0x371cf30e,
+ 0x1d44dda5, 0x6033b9e5, 0x5639a9b0, 0x6526bfff, 0x14d7d9b7, 0x4182b6a7,
+ 0x01a5fa76, 0x7aa5e581, 0x762465e6, 0x386b3a2e, 0x495a3ab0, 0x04421b2e,
+ 0x46e04591, 0x472af458, 0x6a007dd3, 0x2e8be484, 0x18660abe, 0x7969af82,
+ 0x5a242a83, 0x581b5f72, 0x5f0eff6d, 0x38aea98c, 0x2acb5853, 0x6d650b35,
+ 0x10b750d7, 0x18fdcd14, 0x09b4816c, 0x3ceef016, 0x6957153c, 0x27cf39fb,
+ 0x60e3495d, 0x381e1da6, 0x4b5be02d, 0x14b6f309, 0x6380c589, 0x1a31f436,
+ 0x4b5e50c1, 0x493ac048, 0x314baad1, 0x71e24ab7, 0x718af49c, 0x022f4658,
+ 0x1a419d5b, 0x1854610d, 0x2ec4e99a, 0x7096ce50, 0x5467ba00, 0x404aab4c,
+ 0x1a5ab015, 0x217580f7, 0x2d50071e, 0x71a9f437, 0x27f758b5, 0x11cd8b3f,
+ 0x63b089c9, 0x53c860c1, 0x2fa6b7d7, 0x61e54771, 0x5c0ba6b9, 0x3138f796,
+ 0x5c7359cd, 0x4c2c5654, 0x549d581c, 0x3129ebf7, 0x4958a248, 0x1a460541,
+ 0x68e64964, 0x597c0609, 0x57afcbab, 0x2f1c6479, 0x57a0ad5c, 0x5936938f,
+ 0x536a5cbe, 0x29aacf0b, 0x43eca70d, 0x6e7a3e4e, 0x563c1e3b, 0x32f23909,
+ 0x12faa42d, 0x28b0bbde, 0x797e2842, 0x1b827bdf, 0x0df96a6e, 0x542ef7f4,
+ 0x6226d368, 0x01cb4258, 0x77bcba08, 0x7e6dc041, 0x0571eda3, 0x0fdf5065,
+ 0x5c9b9f7a, 0x2b496dd6, 0x02d3b40b, 0x3a5752db, 0x4843a293, 0x6fdc9c3f,
+ 0x42963996, 0x39c9e4eb, 0x01db58ad, 0x7e79381c, 0x5bb207bb, 0x2df5de51,
+ 0x1549ec82, 0x64f01e70, 0x536eb0d0, 0x10fa6e03, 0x5b7f9a20, 0x2d8b625d,
+ 0x397410c7, 0x7778284e, 0x1ab75170, 0x254f304e, 0x395ba877, 0x0c2e2815,
+ 0x5c723dec, 0x63b91327, 0x7c5954b5, 0x67dd69a3, 0x21d220c7, 0x5a287fcd,
+ 0x0d0b9c59, 0x22444c9f, 0x6305cb43, 0x12f717cc, 0x77c11945, 0x0e79bda8,
+ 0x6e014391, 0x441d0179, 0x5e17dd2f, 0x53e57a5c, 0x692f4b9a, 0x76c1e94b,
+ 0x5a872d81, 0x044f7e7e, 0x0970844f, 0x25e34e73, 0x57865d3c, 0x640771d2,
+ 0x12d410ed, 0x1424e079, 0x3e1c7fd7, 0x0e89295a, 0x48dcf262, 0x55a29550,
+ 0x0fd4d360, 0x7494d449, 0x41e6f260, 0x2230d4e7, 0x5ad1cd49, 0x7f8dd428,
+ 0x7722b48a, 0x7a14848d, 0x2a83335a, 0x548c0d9b, 0x24f5d43b, 0x33a417cb,
+ 0x3061e078, 0x1a1bc935, 0x5aedb5df, 0x6755f3e4, 0x795e4cdb, 0x64dfcd1c,
+ 0x6d5164fc, 0x34a3df0e, 0x2cc92142, 0x2569127d, 0x130f3d86, 0x43617cc2,
+ 0x25eaf1fa, 0x044ae792, 0x4b47ee17, 0x6879ea87, 0x7eb455fa, 0x54481e19,
+ 0x13bba2f0, 0x6da3fe79, 0x19c306ff, 0x42591e38, 0x2b0e205d, 0x60bd48bc,
+ 0x550aa0ce, 0x2296a6ef, 0x551eb052, 0x76df1b8e, 0x242a2d22, 0x0ada0b06,
+ 0x58b661ec, 0x490bec94, 0x20bd7c59, 0x760de8c3, 0x7a048ee8, 0x44ba6dcd,
+ 0x3816abd9, 0x47e8527e, 0x2194a188, 0x6967a480, 0x7f7e2083, 0x0ec455f3,
+ 0x78198eab, 0x3d710773, 0x05969198, 0x76ffcffe, 0x54be4797, 0x11105781,
+ 0x3a851719, 0x516284b8, 0x4295de1c, 0x3905be43, 0x6d4e7d6a, 0x0877796d,
+ 0x0b9e986a, 0x5e2b853f, 0x7e6c79cd, 0x4a44a54c, 0x1e28b9a2, 0x5b1e408e,
+ 0x6a1c8eac, 0x62a87929, 0x4f075dac, 0x5c030e8c, 0x3df73ce9, 0x321c3c69,
+ 0x2325cc45, 0x4eaf0759, 0x486a31fb, 0x12d04b94, 0x714e15d5, 0x420d1910,
+ 0x092dc45b, 0x0119beac, 0x68b2bfdb, 0x74863a17, 0x3c7ab8e5, 0x035bc2df,
+ 0x4e7a7965, 0x017f58d6, 0x6414074e, 0x3a1e64ae, 0x2d6725d8, 0x0f22f82a,
+ 0x0a0affa0, 0x4159f31e, 0x4002cb9d, 0x234e393f, 0x6028169f, 0x3b804078,
+ 0x0c16e2e1, 0x0e198020, 0x24b13c40, 0x1ceb2143, 0x38dd4246, 0x6f483590,
+ 0x69b20a6e, 0x105580b1, 0x5d60f184, 0x065d18eb, 0x09a28739, 0x70345728,
+ 0x595a5934, 0x14a78a43, 0x449f05c7, 0x6556fcfc, 0x260bc0b2, 0x3afb600e,
+ 0x1f47bb91, 0x145c14b6, 0x541832fe, 0x54f10f23, 0x3013650e, 0x6c0d32ba,
+ 0x4f202c8d, 0x66bcc661, 0x6131dc7f, 0x04828b25, 0x1737565d, 0x520e967f,
+ 0x16cf0438, 0x6f2bc19e, 0x553c3dda, 0x356906b0, 0x333916d5, 0x2887c195,
+ 0x11e7440b, 0x6354f182, 0x06b2f977, 0x6d2c9a5c, 0x2d02bfb7, 0x74fafcf6,
+ 0x2b955161, 0x74035c38, 0x6e9bc991, 0x09a3a5b9, 0x460f416a, 0x11afabfc,
+ 0x66e32d10, 0x4a56ac6e, 0x6448afa8, 0x680b0044, 0x05d0e296, 0x49569eac,
+ 0x0adb563b, 0x4a9da168, 0x4f857004, 0x0f234600, 0x6db386ec, 0x280b94bf,
+ 0x7cd258a5, 0x6165fd88, 0x3bf2aac9, 0x2cb47c44, 0x2381c2a4, 0x4fe42552,
+ 0x21d4c81e, 0x24baa9af, 0x365231cb, 0x11b7fc81, 0x419748fb, 0x38ff637e,
+ 0x065f3365, 0x21f1aba8, 0x2df41ace, 0x5cec1d95, 0x22c078a8, 0x7bb894fc,
+ 0x2d66fc53, 0x7ed82ccc, 0x4485c9d7, 0x1af210fc, 0x5d2faa09, 0x3b33412e,
+ 0x79d12ea8, 0x7bb8103b, 0x5cea1a7b, 0x2779db45, 0x1250ed5b, 0x0c4d8964,
+ 0x6c18e9f5, 0x501ddc60, 0x3de43ae4, 0x6c0e8577, 0x0adfb426, 0x7ec718f5,
+ 0x1991f387, 0x101ccb9c, 0x632360b4, 0x7d52ce4d, 0x0b58c91c, 0x1fa59d53,
+ 0x0b0b48b0, 0x297315d0, 0x7f3132ff, 0x323b85d1, 0x2f852141, 0x23e84bdc,
+ 0x3732cb25, 0x1274eb57, 0x21a882c3, 0x095288a9, 0x2120e253, 0x617799ce,
+ 0x5e4926b3, 0x52575363, 0x696722e0, 0x509c9117, 0x3b60f14f, 0x423310fa,
+ 0x4e694e80, 0x000a647e, 0x453e283a, 0x3f1d21ef, 0x527c91f0, 0x7ac2e88a,
+ 0x1ba3b840, 0x1c3f253a, 0x04c40280, 0x437dc361, 0x7247859c, 0x61e5b34c,
+ 0x20746a53, 0x58cfc2df, 0x79edf48e, 0x5b48e723, 0x7b08baac, 0x1d1035ea,
+ 0x023fc918, 0x2de0427c, 0x71540904, 0x4030e8f5, 0x2b0961f6, 0x4ec98ef0,
+ 0x781076ee, 0x0dac959b, 0x16f66214, 0x273411e5, 0x02334297, 0x3b568cd1,
+ 0x7cf4e8c0, 0x0f4c2c91, 0x2d8dd28e, 0x4a7b3fb0, 0x237969ae, 0x363d6cb6,
+ 0x75fee60a, 0x5825f4df, 0x29f79f9d, 0x22de4f33, 0x2309590e, 0x1977c2bd,
+ 0x67f7bebe, 0x452b8330, 0x5dc70832, 0x5cddbea4, 0x59091e0b, 0x4d287830,
+ 0x2bbc2ce6, 0x420ee023, 0x02d6e086, 0x228a7a14, 0x48207207, 0x1d5ccc5a,
+ 0x37d32cdc, 0x50dc6508, 0x0b795304, 0x5b9fd543, 0x2a3f2925, 0x72e71606,
+ 0x0dc8ba42, 0x3279a910, 0x6bd2c2e2, 0x775065d8, 0x547c59a6, 0x4b5374cf,
+ 0x0c45cd18, 0x532096d6, 0x351c9bd1, 0x107fdce0, 0x3ae69075, 0x5dddd5de,
+ 0x3bb0ba8b, 0x0b1a0019, 0x6c226525, 0x109e9002, 0x312191be, 0x16fa3de8,
+ 0x4a5197aa, 0x0931b2d2, 0x79ee6e1b, 0x657a142b, 0x6ab74d38, 0x77440cff,
+ 0x11e37956, 0x5c335799, 0x269d3be3, 0x18923cfd, 0x4dd71b00, 0x77c58014,
+ 0x07145324, 0x1678546a, 0x5dfd4f6a, 0x207f4e13, 0x6b0a98c0, 0x015bc2cf,
+ 0x1636d8fe, 0x7bc5f038, 0x183a0661, 0x573ec5f3, 0x54cf2255, 0x2fcc905c,
+ 0x71bb70b9, 0x2b122a89, 0x59f86e5b, 0x5528273d, 0x464cf857, 0x27efdeec,
+ 0x1d0bcfcc, 0x64d7837f, 0x1e7a659a, 0x02aa611c, 0x53969ad5, 0x0e83f59f,
+ 0x50a6d11b, 0x79513c59, 0x0e5c3c98, 0x2ed7bbcf, 0x117de9d9, 0x375ec696,
+ 0x19c830aa, 0x66950511, 0x2b6dbbaa, 0x5ca18c9b, 0x0a487514, 0x6f44a887,
+ 0x6921bc6e, 0x3ef8130b, 0x26f6cde3, 0x686d7605, 0x6583553a, 0x29bcf7cc,
+ 0x55d42201, 0x1c93497c, 0x64c53231, 0x32088f6e, 0x381c5770, 0x617574d8,
+ 0x09757952, 0x1a616eb0, 0x1140e8aa, 0x0ff66ffb, 0x32039001, 0x5a455e7c,
+ 0x0027b906, 0x21cf154c, 0x67d3527f, 0x56fd7602, 0x150f8b25, 0x2ae8e4c8,
+ 0x0bf10aec, 0x3d26a40f, 0x5c4c8ffc, 0x3c291322, 0x737fd02c, 0x4b506209,
+ 0x484ddaa4, 0x00b44669, 0x5974bdd1, 0x7d39d617, 0x12995404, 0x48f00bbe,
+ 0x44f7c59a, 0x23cb9292, 0x6476f20b, 0x034fbd59, 0x2893161c, 0x1dbae8c0,
+ 0x50348c2e, 0x797f0957, 0x685ddeaf, 0x36fb8a2e, 0x0fceb6f4, 0x10347ab4,
+ 0x72720bfc, 0x292a4304, 0x0cbf8a27, 0x3cea6db7, 0x4b0c6b15, 0x57e8e716,
+ 0x4e9c54cc, 0x4fc7f7ca, 0x49a6d3e2, 0x10fc2df3, 0x73db387e, 0x72cb89c3,
+ 0x71dba437, 0x4b14048c, 0x6e1af265, 0x1084b213, 0x3842107d, 0x6ecdc171,
+ 0x647919b2, 0x41a80841, 0x7b387c76, 0x46bc094b, 0x331b312a, 0x2f140cc4,
+ 0x355d0a11, 0x19390200, 0x69b05263, 0x582963fa, 0x44897e31, 0x66a473f0,
+ 0x0374f08d, 0x35879e45, 0x5e1dd7ef, 0x34d6a311, 0x6e4e18eb, 0x7b44734b,
+ 0x0e421333, 0x3da026d8, 0x5becbf4b, 0x56db4a1f, 0x1f2089bc, 0x28c733f2,
+ 0x04b0975d, 0x6156f224, 0x12d1f40f, 0x7f4d30f4, 0x2c0b9861, 0x769a083b,
+ 0x739544fb, 0x1dbd1067, 0x0e8cd717, 0x4c246fb2, 0x115eff39, 0x19e22f2a,
+ 0x4563ba61, 0x5d33a617, 0x54af83cf, 0x030bde73, 0x54b4736d, 0x0f01dfec,
+ 0x08869c01, 0x4e9e4d7b, 0x4739855a, 0x62d964a3, 0x26948fde, 0x30adf212,
+ 0x1f57b400, 0x3766c914, 0x1e7f9d1c, 0x33258b59, 0x522ab2c2, 0x3dc99798,
+ 0x15f53fe2, 0x05636669, 0x354b59c3, 0x1c37ebd4, 0x0bb7ebf9, 0x0e4e87f9,
+ 0x680d3124, 0x2770d549, 0x0c5e112e, 0x74aaa7ed, 0x06c0b550, 0x342b5922,
+ 0x4532ab5b, 0x4257dbee, 0x087f32a9, 0x45ada3e3, 0x7a854272, 0x061625f2,
+ 0x47c85a91, 0x25ad375d, 0x2809bd9d, 0x168b9348, 0x4381b0a3, 0x6f2dc6ca,
+ 0x122e54f6, 0x6c3228a6, 0x653c1652, 0x60b60584, 0x1d304b77, 0x4cc74c58,
+ 0x087e3dd5, 0x79bd540e, 0x79ab7a70, 0x26fcd1c9, 0x342abaaf, 0x644716b0,
+ 0x01f076cb, 0x73628937, 0x20b01ff8, 0x5832b80b, 0x2f77fc92, 0x4468d962,
+ 0x2bac2679, 0x7f850778, 0x47d2997c, 0x02690cb7, 0x7de54951, 0x54d80b14,
+ 0x5e0c6854, 0x313cc749, 0x622b86ba, 0x38dbf6d3, 0x045d3e52, 0x574f87fd,
+ 0x09f1b078, 0x31784f71, 0x4f01dd2f, 0x1874c9f9, 0x5837c7af, 0x2372f768,
+ 0x531bd1e8, 0x61816c0b, 0x4592995f, 0x156463c0, 0x250c5afe, 0x40c83178,
+ 0x4396f6b7, 0x29bdbec0, 0x43ea8ca5, 0x5c474696, 0x2c869192, 0x2ff2f51a,
+ 0x7c963fe5, 0x294319c1, 0x019fbe26, 0x72fa8e68, 0x245ca463, 0x4ca88208,
+ 0x72ac845a, 0x25307181, 0x2cdf88f7, 0x0adbfebd, 0x2eea465b, 0x52e4eee0,
+ 0x084daacd, 0x717ce67e, 0x594087c2, 0x2b8ee5c7, 0x4558f811, 0x76b65ba4,
+ 0x5de05e09, 0x3db76e27, 0x3c75110d, 0x04ca67e7, 0x51cd6d09, 0x7b4e9c3e,
+ 0x7cdda4d2, 0x674fb021, 0x7d372d2d, 0x13f7978b, 0x5fb106b1, 0x034377d1,
+ 0x2e5336f3, 0x099bb17d, 0x04e6755e, 0x34f73c1e, 0x004e0a0d, 0x7f2c32e2,
+ 0x1fc8f910, 0x67d0859d, 0x76462b25, 0x59fa9a17, 0x028e53ef, 0x3d6d5fdd,
+ 0x79a4671e, 0x5cbec506, 0x2c23ee6d, 0x628a2c1e, 0x4dae87bd, 0x07a189ea,
+ 0x3a414a96, 0x5915f622, 0x6bea011e, 0x412674cf, 0x07ecc314, 0x6a7dbce8,
+ 0x7e176f10, 0x68e60d47, 0x079ea970, 0x79f3b55c, 0x65a46098, 0x56155533,
+ 0x7e5d0272, 0x795bfad5, 0x094da770, 0x05ba427c, 0x152e430e, 0x187d8470,
+ 0x08e607bc, 0x45ce5ef9, 0x654231ae, 0x38d8cb48, 0x605632f8, 0x25cf8ee9,
+ 0x11497170, 0x171a3b00, 0x0f103d49, 0x24826483, 0x2848e187, 0x7498919b,
+ 0x1bb788cb, 0x791ad5c7, 0x5129330e, 0x016c4436, 0x430f05bf, 0x1f06b5cd,
+ 0x62df1378, 0x0423b9b4, 0x0341acaf, 0x3189543c, 0x7b96b2ea, 0x6c4865c3,
+ 0x4cc7adc3, 0x78a2bff6, 0x642db7c7, 0x70d02300, 0x7cd43ac0, 0x4f5fe414,
+ 0x333b52c2, 0x500d3c74, 0x65782c01, 0x3f72a2c5, 0x278f59d8, 0x493bf7f8,
+ 0x16bf51a0, 0x6cc70ced, 0x6ed15979, 0x1a77abae, 0x08cadbb7, 0x2f2e0bc0,
+ 0x236f5e8d, 0x1a4b4495, 0x360bd008, 0x32227d40
+};
+
+int
+main()
+{
+ SHA1Sum sum;
+ SHA1Sum::Hash hash;
+ sum.update(reinterpret_cast<const uint8_t*>(testV), sizeof(testV));
+ sum.finish(hash);
+
+ static const uint8_t expected[20] =
+ { 0xc8, 0xf2, 0x09, 0x59, 0x4e, 0x64, 0x40, 0xaa, 0x7b, 0xf7, 0xb8, 0xe0,
+ 0xfa, 0x44, 0xb2, 0x31, 0x95, 0xad, 0x94, 0x81 };
+
+ MOZ_STATIC_ASSERT(sizeof(expected) == sizeof(SHA1Sum::Hash),
+ "expected-data size should be the same as the actual hash "
+ "size");
+
+ for (size_t i = 0; i < SHA1Sum::HashSize; i++)
+ MOZ_ASSERT(hash[i] == expected[i]);
+
+ return 0;
+}
diff --git a/mfbt/tests/TestTypeTraits.cpp b/mfbt/tests/TestTypeTraits.cpp
new file mode 100644
index 0000000..6c424ed
--- /dev/null
+++ b/mfbt/tests/TestTypeTraits.cpp
@@ -0,0 +1,213 @@
+/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#include "mozilla/Assertions.h"
+#include "mozilla/TypeTraits.h"
+
+using mozilla::IsBaseOf;
+using mozilla::IsConvertible;
+using mozilla::IsSame;
+using mozilla::IsSigned;
+using mozilla::IsUnsigned;
+using mozilla::MakeSigned;
+using mozilla::MakeUnsigned;
+
+MOZ_STATIC_ASSERT(!IsSigned<bool>::value, "bool shouldn't be signed");
+MOZ_STATIC_ASSERT(IsUnsigned<bool>::value, "bool should be unsigned");
+
+MOZ_STATIC_ASSERT(!IsSigned<const bool>::value, "const bool shouldn't be signed");
+MOZ_STATIC_ASSERT(IsUnsigned<const bool>::value, "const bool should be unsigned");
+
+MOZ_STATIC_ASSERT(!IsSigned<volatile bool>::value, "volatile bool shouldn't be signed");
+MOZ_STATIC_ASSERT(IsUnsigned<volatile bool>::value, "volatile bool should be unsigned");
+
+MOZ_STATIC_ASSERT(!IsSigned<unsigned char>::value, "unsigned char shouldn't be signed");
+MOZ_STATIC_ASSERT(IsUnsigned<unsigned char>::value, "unsigned char should be unsigned");
+MOZ_STATIC_ASSERT(IsSigned<signed char>::value, "signed char should be signed");
+MOZ_STATIC_ASSERT(!IsUnsigned<signed char>::value, "signed char shouldn't be unsigned");
+
+MOZ_STATIC_ASSERT(!IsSigned<unsigned short>::value, "unsigned short shouldn't be signed");
+MOZ_STATIC_ASSERT(IsUnsigned<unsigned short>::value, "unsigned short should be unsigned");
+MOZ_STATIC_ASSERT(IsSigned<short>::value, "short should be signed");
+MOZ_STATIC_ASSERT(!IsUnsigned<short>::value, "short shouldn't be unsigned");
+
+MOZ_STATIC_ASSERT(!IsSigned<unsigned int>::value, "unsigned int shouldn't be signed");
+MOZ_STATIC_ASSERT(IsUnsigned<unsigned int>::value, "unsigned int should be unsigned");
+MOZ_STATIC_ASSERT(IsSigned<int>::value, "int should be signed");
+MOZ_STATIC_ASSERT(!IsUnsigned<int>::value, "int shouldn't be unsigned");
+
+MOZ_STATIC_ASSERT(!IsSigned<unsigned long>::value, "unsigned long shouldn't be signed");
+MOZ_STATIC_ASSERT(IsUnsigned<unsigned long>::value, "unsigned long should be unsigned");
+MOZ_STATIC_ASSERT(IsSigned<long>::value, "long should be signed");
+MOZ_STATIC_ASSERT(!IsUnsigned<long>::value, "long shouldn't be unsigned");
+
+MOZ_STATIC_ASSERT(IsSigned<float>::value, "float should be signed");
+MOZ_STATIC_ASSERT(!IsUnsigned<float>::value, "float shouldn't be unsigned");
+
+MOZ_STATIC_ASSERT(IsSigned<const float>::value, "const float should be signed");
+MOZ_STATIC_ASSERT(!IsUnsigned<const float>::value, "const float shouldn't be unsigned");
+
+MOZ_STATIC_ASSERT(IsSigned<double>::value, "double should be signed");
+MOZ_STATIC_ASSERT(!IsUnsigned<double>::value, "double shouldn't be unsigned");
+
+MOZ_STATIC_ASSERT(IsSigned<volatile double>::value, "volatile double should be signed");
+MOZ_STATIC_ASSERT(!IsUnsigned<volatile double>::value, "volatile double shouldn't be unsigned");
+
+MOZ_STATIC_ASSERT(IsSigned<long double>::value, "long double should be signed");
+MOZ_STATIC_ASSERT(!IsUnsigned<long double>::value, "long double shouldn't be unsigned");
+
+MOZ_STATIC_ASSERT(IsSigned<const volatile long double>::value,
+ "const volatile long double should be signed");
+MOZ_STATIC_ASSERT(!IsUnsigned<const volatile long double>::value,
+ "const volatile long double shouldn't be unsigned");
+
+namespace CPlusPlus11IsBaseOf {
+
+// Adapted from C++11 ยง 20.9.6.
+struct B {};
+struct B1 : B {};
+struct B2 : B {};
+struct D : private B1, private B2 {};
+
+static void
+StandardIsBaseOfTests()
+{
+ MOZ_ASSERT((IsBaseOf<B, D>::value) == true);
+ MOZ_ASSERT((IsBaseOf<const B, D>::value) == true);
+ MOZ_ASSERT((IsBaseOf<B, const D>::value) == true);
+ MOZ_ASSERT((IsBaseOf<B, const B>::value) == true);
+ MOZ_ASSERT((IsBaseOf<D, B>::value) == false);
+ MOZ_ASSERT((IsBaseOf<B&, D&>::value) == false);
+ MOZ_ASSERT((IsBaseOf<B[3], D[3]>::value) == false);
+ // We fail at the following test. To fix it, we need to specialize IsBaseOf
+ // for all built-in types.
+ // MOZ_ASSERT((IsBaseOf<int, int>::value) == false);
+}
+
+} /* namespace CPlusPlus11IsBaseOf */
+
+class A { };
+class B : public A { };
+class C : private A { };
+class D { };
+class E : public A { };
+class F : public B, public E { };
+
+static void
+TestIsBaseOf()
+{
+ MOZ_ASSERT((IsBaseOf<A, B>::value),
+ "A is a base of B");
+ MOZ_ASSERT((!IsBaseOf<B, A>::value),
+ "B is not a base of A");
+ MOZ_ASSERT((IsBaseOf<A, C>::value),
+ "A is a base of C");
+ MOZ_ASSERT((!IsBaseOf<C, A>::value),
+ "C is not a base of A");
+ MOZ_ASSERT((IsBaseOf<A, F>::value),
+ "A is a base of F");
+ MOZ_ASSERT((!IsBaseOf<F, A>::value),
+ "F is not a base of A");
+ MOZ_ASSERT((!IsBaseOf<A, D>::value),
+ "A is not a base of D");
+ MOZ_ASSERT((!IsBaseOf<D, A>::value),
+ "D is not a base of A");
+ MOZ_ASSERT((IsBaseOf<B, B>::value),
+ "B is the same as B (and therefore, a base of B)");
+}
+
+static void
+TestIsConvertible()
+{
+ // Pointer type convertibility
+ MOZ_ASSERT((IsConvertible<A*, A*>::value),
+ "A* should convert to A*");
+ MOZ_ASSERT((IsConvertible<B*, A*>::value),
+ "B* should convert to A*");
+ MOZ_ASSERT((!IsConvertible<A*, B*>::value),
+ "A* shouldn't convert to B*");
+ MOZ_ASSERT((!IsConvertible<A*, C*>::value),
+ "A* shouldn't convert to C*");
+ MOZ_ASSERT((!IsConvertible<A*, D*>::value),
+ "A* shouldn't convert to unrelated D*");
+ MOZ_ASSERT((!IsConvertible<D*, A*>::value),
+ "D* shouldn't convert to unrelated A*");
+
+ // Instance type convertibility
+ MOZ_ASSERT((IsConvertible<A, A>::value),
+ "A is A");
+ MOZ_ASSERT((IsConvertible<B, A>::value),
+ "B converts to A");
+ MOZ_ASSERT((!IsConvertible<D, A>::value),
+ "D and A are unrelated");
+ MOZ_ASSERT((!IsConvertible<A, D>::value),
+ "A and D are unrelated");
+
+ // These cases seem to require C++11 support to properly implement them, so
+ // for now just disable them.
+ //MOZ_ASSERT((!IsConvertible<C*, A*>::value),
+ // "C* shouldn't convert to A* (private inheritance)");
+ //MOZ_ASSERT((!IsConvertible<C, A>::value),
+ // "C doesn't convert to A (private inheritance)");
+}
+
+MOZ_STATIC_ASSERT((IsSame<MakeSigned<const unsigned char>::Type, const signed char>::value),
+ "const unsigned char won't signify correctly");
+MOZ_STATIC_ASSERT((IsSame<MakeSigned<volatile unsigned short>::Type, volatile signed short>::value),
+ "volatile unsigned short won't signify correctly");
+MOZ_STATIC_ASSERT((IsSame<MakeSigned<const volatile unsigned int>::Type, const volatile signed int>::value),
+ "const volatile unsigned int won't signify correctly");
+MOZ_STATIC_ASSERT((IsSame<MakeSigned<unsigned long>::Type, signed long>::value),
+ "unsigned long won't signify correctly");
+MOZ_STATIC_ASSERT((IsSame<MakeSigned<const signed char>::Type, const signed char>::value),
+ "const signed char won't signify correctly");
+
+MOZ_STATIC_ASSERT((IsSame<MakeSigned<volatile signed short>::Type, volatile signed short>::value),
+ "volatile signed short won't signify correctly");
+MOZ_STATIC_ASSERT((IsSame<MakeSigned<const volatile signed int>::Type, const volatile signed int>::value),
+ "const volatile signed int won't signify correctly");
+MOZ_STATIC_ASSERT((IsSame<MakeSigned<signed long>::Type, signed long>::value),
+ "signed long won't signify correctly");
+
+MOZ_STATIC_ASSERT((IsSame<MakeSigned<char>::Type, signed char>::value),
+ "char won't signify correctly");
+MOZ_STATIC_ASSERT((IsSame<MakeSigned<volatile char>::Type, volatile signed char>::value),
+ "volatile char won't signify correctly");
+MOZ_STATIC_ASSERT((IsSame<MakeSigned<const char>::Type, const signed char>::value),
+ "const char won't signify correctly");
+
+MOZ_STATIC_ASSERT((IsSame<MakeUnsigned<const signed char>::Type, const unsigned char>::value),
+ "const signed char won't unsignify correctly");
+MOZ_STATIC_ASSERT((IsSame<MakeUnsigned<volatile signed short>::Type, volatile unsigned short>::value),
+ "volatile signed short won't unsignify correctly");
+MOZ_STATIC_ASSERT((IsSame<MakeUnsigned<const volatile signed int>::Type, const volatile unsigned int>::value),
+ "const volatile signed int won't unsignify correctly");
+MOZ_STATIC_ASSERT((IsSame<MakeUnsigned<signed long>::Type, unsigned long>::value),
+ "signed long won't unsignify correctly");
+
+MOZ_STATIC_ASSERT((IsSame<MakeUnsigned<const unsigned char>::Type, const unsigned char>::value),
+ "const unsigned char won't unsignify correctly");
+
+MOZ_STATIC_ASSERT((IsSame<MakeUnsigned<volatile unsigned short>::Type, volatile unsigned short>::value),
+ "volatile unsigned short won't unsignify correctly");
+MOZ_STATIC_ASSERT((IsSame<MakeUnsigned<const volatile unsigned int>::Type, const volatile unsigned int>::value),
+ "const volatile unsigned int won't unsignify correctly");
+MOZ_STATIC_ASSERT((IsSame<MakeUnsigned<unsigned long>::Type, unsigned long>::value),
+ "signed long won't unsignify correctly");
+
+MOZ_STATIC_ASSERT((IsSame<MakeUnsigned<char>::Type, unsigned char>::value),
+ "char won't unsignify correctly");
+MOZ_STATIC_ASSERT((IsSame<MakeUnsigned<volatile char>::Type, volatile unsigned char>::value),
+ "volatile char won't unsignify correctly");
+MOZ_STATIC_ASSERT((IsSame<MakeUnsigned<const char>::Type, const unsigned char>::value),
+ "const char won't unsignify correctly");
+
+int
+main()
+{
+ CPlusPlus11IsBaseOf::StandardIsBaseOfTests();
+ TestIsBaseOf();
+ TestIsConvertible();
+}
diff --git a/mfbt/tests/TestWeakPtr.cpp b/mfbt/tests/TestWeakPtr.cpp
new file mode 100644
index 0000000..510dd06
--- /dev/null
+++ b/mfbt/tests/TestWeakPtr.cpp
@@ -0,0 +1,77 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#include "mozilla/WeakPtr.h"
+
+using mozilla::SupportsWeakPtr;
+using mozilla::WeakPtr;
+
+// To have a class C support weak pointers, inherit from SupportsWeakPtr<C>.
+class C : public SupportsWeakPtr<C>
+{
+ public:
+ int num;
+ void act() {}
+};
+
+static void
+Example()
+{
+
+ C* ptr = new C();
+
+ // Get weak pointers to ptr. The first time asWeakPtr is called
+ // a reference counted WeakReference object is created that
+ // can live beyond the lifetime of 'ptr'. The WeakReference
+ // object will be notified of 'ptr's destruction.
+ WeakPtr<C> weak = ptr->asWeakPtr();
+ WeakPtr<C> other = ptr->asWeakPtr();
+
+ // Test a weak pointer for validity before using it.
+ if (weak) {
+ weak->num = 17;
+ weak->act();
+ }
+
+ // Destroying the underlying object clears weak pointers to it.
+ delete ptr;
+
+ MOZ_ASSERT(!weak, "Deleting |ptr| clears weak pointers to it.");
+ MOZ_ASSERT(!other, "Deleting |ptr| clears all weak pointers to it.");
+}
+
+struct A : public SupportsWeakPtr<A>
+{
+ int data;
+};
+
+
+int
+main()
+{
+
+ A* a = new A;
+
+ // a2 is unused to test the case when we haven't initialized
+ // the internal WeakReference pointer.
+ A* a2 = new A;
+
+ a->data = 5;
+ WeakPtr<A> ptr = a->asWeakPtr();
+ {
+ WeakPtr<A> ptr2 = a->asWeakPtr();
+ MOZ_ASSERT(ptr->data == 5);
+ WeakPtr<A> ptr3 = a->asWeakPtr();
+ MOZ_ASSERT(ptr->data == 5);
+ }
+
+ delete a;
+ MOZ_ASSERT(!ptr);
+
+ delete a2;
+
+ Example();
+
+ return 0;
+}
diff --git a/mfbt/tests/moz.build b/mfbt/tests/moz.build
new file mode 100644
index 0000000..895d119
--- /dev/null
+++ b/mfbt/tests/moz.build
@@ -0,0 +1,6 @@
+# -*- Mode: python; c-basic-offset: 4; indent-tabs-mode: nil; tab-width: 40 -*-
+# vim: set filetype=python:
+# This Source Code Form is subject to the terms of the Mozilla Public
+# License, v. 2.0. If a copy of the MPL was not distributed with this
+# file, You can obtain one at http://mozilla.org/MPL/2.0/.
+