1 /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 /* This Source Code Form is subject to the terms of the Mozilla Public
3 * License, v. 2.0. If a copy of the MPL was not distributed with this
4 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
6 #ifndef MOZ_DECIMAL_UTILS_H
7 #define MOZ_DECIMAL_UTILS_H
9 // This file contains extra includes, defines and typedefs to allow compilation
10 // of Decimal.cpp under the Mozilla source without blink core dependencies. Do
11 // not include it into any file other than Decimal.cpp.
13 #include "double-conversion/double-conversion.h"
14 #include "mozilla/ArrayUtils.h"
15 #include "mozilla/Casting.h"
16 #include "mozilla/FloatingPoint.h"
17 #include "mozilla/Span.h"
26 // For Android toolchain
27 #define UINT64_C(c) (c ## ULL)
33 #define ASSERT MOZ_ASSERT
35 #define ASSERT_NOT_REACHED() MOZ_ASSERT_UNREACHABLE("moz-decimal-utils.h")
37 #define STACK_ALLOCATED() DISALLOW_NEW()
39 #define WTF_MAKE_NONCOPYABLE(ClassName) \
41 ClassName(const ClassName&) = delete; \
42 void operator=(const ClassName&) = delete;
44 typedef std::string String
;
46 double mozToDouble(mozilla::Span
<const char> aStr
, bool *valid
) {
47 double_conversion::StringToDoubleConverter
converter(
48 double_conversion::StringToDoubleConverter::NO_FLAGS
,
49 mozilla::UnspecifiedNaN
<double>(), mozilla::UnspecifiedNaN
<double>(), nullptr, nullptr);
50 const char* str
= aStr
.Elements();
51 int length
= mozilla::AssertedCast
<int>(aStr
.Length());
52 int processed_char_count
; // unused - NO_FLAGS requires the whole string to parse
53 double result
= converter
.StringToDouble(str
, length
, &processed_char_count
);
54 *valid
= std::isfinite(result
);
58 double mozToDouble(const String
&aStr
, bool *valid
) {
59 return mozToDouble(mozilla::MakeStringSpan(aStr
.c_str()), valid
);
62 String
mozToString(double aNum
) {
64 int buffer_length
= std::size(buffer
);
65 const double_conversion::DoubleToStringConverter
& converter
=
66 double_conversion::DoubleToStringConverter::EcmaScriptConverter();
67 double_conversion::StringBuilder
builder(buffer
, buffer_length
);
68 converter
.ToShortest(aNum
, &builder
);
69 return String(builder
.Finalize());
72 String
mozToString(int64_t aNum
) {
74 o
<< std::setprecision(std::numeric_limits
<int64_t>::digits10
) << aNum
;
78 String
mozToString(uint64_t aNum
) {
80 o
<< std::setprecision(std::numeric_limits
<uint64_t>::digits10
) << aNum
;
84 namespace moz_decimal_utils
{
92 void appendLiteral(const char *aStr
) {
95 void appendNumber(int aNum
) {
96 mStr
+= mozToString(int64_t(aNum
));
98 void append(const String
& aStr
) {
101 std::string
toString() const {
108 } // namespace moz_decimal_utils