Bug 1846847 [wpt PR 41301] - [FedCM] Don't omit schemes when formatting URLs, a=testonly
[gecko.git] / js / src / jsnum.cpp
blobc6194196c6998c3c5449a4818efa40946fc886fc
1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*-
2 * vim: set ts=8 sts=2 et sw=2 tw=80:
3 * This Source Code Form is subject to the terms of the Mozilla Public
4 * License, v. 2.0. If a copy of the MPL was not distributed with this
5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
7 /*
8 * JS number type and wrapper class.
9 */
11 #include "jsnum.h"
13 #include "mozilla/Casting.h"
14 #include "mozilla/FloatingPoint.h"
15 #include "mozilla/Maybe.h"
16 #include "mozilla/RangedPtr.h"
17 #include "mozilla/TextUtils.h"
18 #include "mozilla/Utf8.h"
20 #include <algorithm>
21 #include <iterator>
22 #include <limits>
23 #ifdef HAVE_LOCALECONV
24 # include <locale.h>
25 #endif
26 #include <math.h>
27 #include <string.h> // memmove
28 #include <string_view>
30 #include "jstypes.h"
32 #include "double-conversion/double-conversion.h"
33 #include "frontend/ParserAtom.h" // frontend::{ParserAtomsTable, TaggedParserAtomIndex}
34 #include "jit/InlinableNatives.h"
35 #include "js/CharacterEncoding.h"
36 #include "js/Conversions.h"
37 #include "js/friend/ErrorMessages.h" // js::GetErrorMessage, JSMSG_*
38 #include "js/GCAPI.h"
39 #if !JS_HAS_INTL_API
40 # include "js/LocaleSensitive.h"
41 #endif
42 #include "js/PropertyAndElement.h" // JS_DefineFunctions
43 #include "js/PropertySpec.h"
44 #include "util/DoubleToString.h"
45 #include "util/Memory.h"
46 #include "util/StringBuffer.h"
47 #include "vm/BigIntType.h"
48 #include "vm/GlobalObject.h"
49 #include "vm/JSAtomUtils.h" // Atomize, AtomizeString
50 #include "vm/JSContext.h"
51 #include "vm/JSObject.h"
52 #include "vm/StaticStrings.h"
53 #include "vm/WellKnownAtom.h" // js_*_str
55 #include "vm/Compartment-inl.h" // For js::UnwrapAndTypeCheckThis
56 #include "vm/GeckoProfiler-inl.h"
57 #include "vm/JSAtomUtils-inl.h" // BackfillIndexInCharBuffer
58 #include "vm/NativeObject-inl.h"
59 #include "vm/NumberObject-inl.h"
60 #include "vm/StringType-inl.h"
62 using namespace js;
64 using mozilla::Abs;
65 using mozilla::AsciiAlphanumericToNumber;
66 using mozilla::IsAsciiAlphanumeric;
67 using mozilla::IsAsciiDigit;
68 using mozilla::Maybe;
69 using mozilla::MinNumberValue;
70 using mozilla::NegativeInfinity;
71 using mozilla::NumberEqualsInt32;
72 using mozilla::PositiveInfinity;
73 using mozilla::RangedPtr;
74 using mozilla::Utf8AsUnsignedChars;
75 using mozilla::Utf8Unit;
77 using JS::AutoCheckCannotGC;
78 using JS::GenericNaN;
79 using JS::ToInt16;
80 using JS::ToInt32;
81 using JS::ToInt64;
82 using JS::ToInt8;
83 using JS::ToUint16;
84 using JS::ToUint32;
85 using JS::ToUint64;
86 using JS::ToUint8;
88 static bool EnsureDtoaState(JSContext* cx) {
89 if (!cx->dtoaState) {
90 cx->dtoaState = NewDtoaState();
91 if (!cx->dtoaState) {
92 return false;
95 return true;
98 template <typename CharT>
99 static inline void AssertWellPlacedNumericSeparator(const CharT* s,
100 const CharT* start,
101 const CharT* end) {
102 MOZ_ASSERT(start < end, "string is non-empty");
103 MOZ_ASSERT(s > start, "number can't start with a separator");
104 MOZ_ASSERT(s + 1 < end,
105 "final character in a numeric literal can't be a separator");
106 MOZ_ASSERT(*(s + 1) != '_',
107 "separator can't be followed by another separator");
108 MOZ_ASSERT(*(s - 1) != '_',
109 "separator can't be preceded by another separator");
112 namespace {
114 template <typename CharT>
115 class BinaryDigitReader {
116 const int base; /* Base of number; must be a power of 2 */
117 int digit; /* Current digit value in radix given by base */
118 int digitMask; /* Mask to extract the next bit from digit */
119 const CharT* cur; /* Pointer to the remaining digits */
120 const CharT* start; /* Pointer to the start of the string */
121 const CharT* end; /* Pointer to first non-digit */
123 public:
124 BinaryDigitReader(int base, const CharT* start, const CharT* end)
125 : base(base),
126 digit(0),
127 digitMask(0),
128 cur(start),
129 start(start),
130 end(end) {}
132 /* Return the next binary digit from the number, or -1 if done. */
133 int nextDigit() {
134 if (digitMask == 0) {
135 if (cur == end) {
136 return -1;
139 int c = *cur++;
140 if (c == '_') {
141 AssertWellPlacedNumericSeparator(cur - 1, start, end);
142 c = *cur++;
145 MOZ_ASSERT(IsAsciiAlphanumeric(c));
146 digit = AsciiAlphanumericToNumber(c);
147 digitMask = base >> 1;
150 int bit = (digit & digitMask) != 0;
151 digitMask >>= 1;
152 return bit;
156 } /* anonymous namespace */
159 * The fast result might also have been inaccurate for power-of-two bases. This
160 * happens if the addition in value * 2 + digit causes a round-down to an even
161 * least significant mantissa bit when the first dropped bit is a one. If any
162 * of the following digits in the number (which haven't been added in yet) are
163 * nonzero, then the correct action would have been to round up instead of
164 * down. An example occurs when reading the number 0x1000000000000081, which
165 * rounds to 0x1000000000000000 instead of 0x1000000000000100.
167 template <typename CharT>
168 static double ComputeAccurateBinaryBaseInteger(const CharT* start,
169 const CharT* end, int base) {
170 BinaryDigitReader<CharT> bdr(base, start, end);
172 /* Skip leading zeroes. */
173 int bit;
174 do {
175 bit = bdr.nextDigit();
176 } while (bit == 0);
178 MOZ_ASSERT(bit == 1); // guaranteed by Get{Prefix,Decimal}Integer
180 /* Gather the 53 significant bits (including the leading 1). */
181 double value = 1.0;
182 for (int j = 52; j > 0; j--) {
183 bit = bdr.nextDigit();
184 if (bit < 0) {
185 return value;
187 value = value * 2 + bit;
190 /* bit2 is the 54th bit (the first dropped from the mantissa). */
191 int bit2 = bdr.nextDigit();
192 if (bit2 >= 0) {
193 double factor = 2.0;
194 int sticky = 0; /* sticky is 1 if any bit beyond the 54th is 1 */
195 int bit3;
197 while ((bit3 = bdr.nextDigit()) >= 0) {
198 sticky |= bit3;
199 factor *= 2;
201 value += bit2 & (bit | sticky);
202 value *= factor;
205 return value;
208 template <typename CharT>
209 double js::ParseDecimalNumber(const mozilla::Range<const CharT> chars) {
210 MOZ_ASSERT(chars.length() > 0);
211 uint64_t dec = 0;
212 RangedPtr<const CharT> s = chars.begin(), end = chars.end();
213 do {
214 CharT c = *s;
215 MOZ_ASSERT('0' <= c && c <= '9');
216 uint8_t digit = c - '0';
217 uint64_t next = dec * 10 + digit;
218 MOZ_ASSERT(next < DOUBLE_INTEGRAL_PRECISION_LIMIT,
219 "next value won't be an integrally-precise double");
220 dec = next;
221 } while (++s < end);
222 return static_cast<double>(dec);
225 template double js::ParseDecimalNumber(
226 const mozilla::Range<const Latin1Char> chars);
228 template double js::ParseDecimalNumber(
229 const mozilla::Range<const char16_t> chars);
231 template <typename CharT>
232 static bool GetPrefixIntegerImpl(const CharT* start, const CharT* end, int base,
233 IntegerSeparatorHandling separatorHandling,
234 const CharT** endp, double* dp) {
235 MOZ_ASSERT(start <= end);
236 MOZ_ASSERT(2 <= base && base <= 36);
238 const CharT* s = start;
239 double d = 0.0;
240 for (; s < end; s++) {
241 CharT c = *s;
242 if (!IsAsciiAlphanumeric(c)) {
243 if (c == '_' &&
244 separatorHandling == IntegerSeparatorHandling::SkipUnderscore) {
245 AssertWellPlacedNumericSeparator(s, start, end);
246 continue;
248 break;
251 uint8_t digit = AsciiAlphanumericToNumber(c);
252 if (digit >= base) {
253 break;
256 d = d * base + digit;
259 *endp = s;
260 *dp = d;
262 /* If we haven't reached the limit of integer precision, we're done. */
263 if (d < DOUBLE_INTEGRAL_PRECISION_LIMIT) {
264 return true;
268 * Otherwise compute the correct integer from the prefix of valid digits
269 * if we're computing for base ten or a power of two. Don't worry about
270 * other bases; see ES2018, 18.2.5 `parseInt(string, radix)`, step 13.
272 if (base == 10) {
273 return false;
276 if ((base & (base - 1)) == 0) {
277 *dp = ComputeAccurateBinaryBaseInteger(start, s, base);
280 return true;
283 template <typename CharT>
284 bool js::GetPrefixInteger(const CharT* start, const CharT* end, int base,
285 IntegerSeparatorHandling separatorHandling,
286 const CharT** endp, double* dp) {
287 if (GetPrefixIntegerImpl(start, end, base, separatorHandling, endp, dp)) {
288 return true;
291 // Can only fail for base 10.
292 MOZ_ASSERT(base == 10);
294 // If we're accumulating a decimal number and the number is >= 2^53, then the
295 // fast result from the loop in GetPrefixIntegerImpl may be inaccurate. Call
296 // GetDecimal to get the correct answer.
297 return GetDecimal(start, *endp, dp);
300 namespace js {
302 template bool GetPrefixInteger(const char16_t* start, const char16_t* end,
303 int base,
304 IntegerSeparatorHandling separatorHandling,
305 const char16_t** endp, double* dp);
307 template bool GetPrefixInteger(const Latin1Char* start, const Latin1Char* end,
308 int base,
309 IntegerSeparatorHandling separatorHandling,
310 const Latin1Char** endp, double* dp);
312 } // namespace js
314 template <typename CharT>
315 bool js::GetDecimalInteger(const CharT* start, const CharT* end, double* dp) {
316 MOZ_ASSERT(start <= end);
318 double d = 0.0;
319 for (const CharT* s = start; s < end; s++) {
320 CharT c = *s;
321 if (c == '_') {
322 AssertWellPlacedNumericSeparator(s, start, end);
323 continue;
325 MOZ_ASSERT(IsAsciiDigit(c));
326 int digit = c - '0';
327 d = d * 10 + digit;
330 // If we haven't reached the limit of integer precision, we're done.
331 if (d < DOUBLE_INTEGRAL_PRECISION_LIMIT) {
332 *dp = d;
333 return true;
336 // Otherwise compute the correct integer using GetDecimal.
337 return GetDecimal(start, end, dp);
340 namespace js {
342 template bool GetDecimalInteger(const char16_t* start, const char16_t* end,
343 double* dp);
345 template bool GetDecimalInteger(const Latin1Char* start, const Latin1Char* end,
346 double* dp);
348 template <>
349 bool GetDecimalInteger<Utf8Unit>(const Utf8Unit* start, const Utf8Unit* end,
350 double* dp) {
351 return GetDecimalInteger(Utf8AsUnsignedChars(start), Utf8AsUnsignedChars(end),
352 dp);
355 } // namespace js
357 template <typename CharT>
358 bool js::GetDecimal(const CharT* start, const CharT* end, double* dp) {
359 MOZ_ASSERT(start <= end);
361 size_t length = end - start;
363 auto convert = [](auto* chars, size_t length) -> double {
364 using SToDConverter = double_conversion::StringToDoubleConverter;
365 SToDConverter converter(/* flags = */ 0, /* empty_string_value = */ 0.0,
366 /* junk_string_value = */ 0.0,
367 /* infinity_symbol = */ nullptr,
368 /* nan_symbol = */ nullptr);
369 int lengthInt = mozilla::AssertedCast<int>(length);
370 int processed = 0;
371 double d = converter.StringToDouble(chars, lengthInt, &processed);
372 MOZ_ASSERT(processed >= 0);
373 MOZ_ASSERT(size_t(processed) == length);
374 return d;
377 // If there are no underscores, we don't need to copy the chars.
378 bool hasUnderscore = std::any_of(start, end, [](auto c) { return c == '_'; });
379 if (!hasUnderscore) {
380 if constexpr (std::is_same_v<CharT, char16_t>) {
381 *dp = convert(reinterpret_cast<const uc16*>(start), length);
382 } else {
383 static_assert(std::is_same_v<CharT, Latin1Char>);
384 *dp = convert(reinterpret_cast<const char*>(start), length);
386 return true;
389 Vector<char, 32, SystemAllocPolicy> chars;
390 if (!chars.growByUninitialized(length)) {
391 return false;
394 const CharT* s = start;
395 size_t i = 0;
396 for (; s < end; s++) {
397 CharT c = *s;
398 if (c == '_') {
399 AssertWellPlacedNumericSeparator(s, start, end);
400 continue;
402 MOZ_ASSERT(IsAsciiDigit(c) || c == '.' || c == 'e' || c == 'E' ||
403 c == '+' || c == '-');
404 chars[i++] = char(c);
407 *dp = convert(chars.begin(), i);
408 return true;
411 namespace js {
413 template bool GetDecimal(const char16_t* start, const char16_t* end,
414 double* dp);
416 template bool GetDecimal(const Latin1Char* start, const Latin1Char* end,
417 double* dp);
419 template <>
420 bool GetDecimal<Utf8Unit>(const Utf8Unit* start, const Utf8Unit* end,
421 double* dp) {
422 return GetDecimal(Utf8AsUnsignedChars(start), Utf8AsUnsignedChars(end), dp);
425 } // namespace js
427 static bool num_parseFloat(JSContext* cx, unsigned argc, Value* vp) {
428 CallArgs args = CallArgsFromVp(argc, vp);
430 if (args.length() == 0) {
431 args.rval().setNaN();
432 return true;
435 if (args[0].isNumber()) {
436 // ToString(-0) is "0", handle it accordingly.
437 if (args[0].isDouble() && args[0].toDouble() == 0.0) {
438 args.rval().setInt32(0);
439 } else {
440 args.rval().set(args[0]);
442 return true;
445 JSString* str = ToString<CanGC>(cx, args[0]);
446 if (!str) {
447 return false;
450 if (str->hasIndexValue()) {
451 args.rval().setNumber(str->getIndexValue());
452 return true;
455 JSLinearString* linear = str->ensureLinear(cx);
456 if (!linear) {
457 return false;
460 double d;
461 AutoCheckCannotGC nogc;
462 if (linear->hasLatin1Chars()) {
463 const Latin1Char* begin = linear->latin1Chars(nogc);
464 const Latin1Char* end;
465 d = js_strtod(begin, begin + linear->length(), &end);
466 if (end == begin) {
467 d = GenericNaN();
469 } else {
470 const char16_t* begin = linear->twoByteChars(nogc);
471 const char16_t* end;
472 d = js_strtod(begin, begin + linear->length(), &end);
473 if (end == begin) {
474 d = GenericNaN();
478 args.rval().setDouble(d);
479 return true;
482 // ES2023 draft rev 053d34c87b14d9234d6f7f45bd61074b72ca9d69
483 // 19.2.5 parseInt ( string, radix )
484 template <typename CharT>
485 static bool ParseIntImpl(JSContext* cx, const CharT* chars, size_t length,
486 bool stripPrefix, int32_t radix, double* res) {
487 // Step 2.
488 const CharT* end = chars + length;
489 const CharT* s = SkipSpace(chars, end);
491 MOZ_ASSERT(chars <= s);
492 MOZ_ASSERT(s <= end);
494 // Steps 3-4.
495 bool negative = (s != end && s[0] == '-');
497 // Step 5. */
498 if (s != end && (s[0] == '-' || s[0] == '+')) {
499 s++;
502 // Step 10.
503 if (stripPrefix) {
504 if (end - s >= 2 && s[0] == '0' && (s[1] == 'x' || s[1] == 'X')) {
505 s += 2;
506 radix = 16;
510 // Steps 11-15.
511 const CharT* actualEnd;
512 double d;
513 if (!js::GetPrefixInteger(s, end, radix, IntegerSeparatorHandling::None,
514 &actualEnd, &d)) {
515 ReportOutOfMemory(cx);
516 return false;
519 if (s == actualEnd) {
520 *res = GenericNaN();
521 } else {
522 *res = negative ? -d : d;
524 return true;
527 // ES2023 draft rev 053d34c87b14d9234d6f7f45bd61074b72ca9d69
528 // 19.2.5 parseInt ( string, radix )
529 bool js::NumberParseInt(JSContext* cx, HandleString str, int32_t radix,
530 MutableHandleValue result) {
531 // Step 7.
532 bool stripPrefix = true;
534 // Steps 8-9.
535 if (radix != 0) {
536 if (radix < 2 || radix > 36) {
537 result.setNaN();
538 return true;
541 if (radix != 16) {
542 stripPrefix = false;
544 } else {
545 radix = 10;
547 MOZ_ASSERT(2 <= radix && radix <= 36);
549 JSLinearString* linear = str->ensureLinear(cx);
550 if (!linear) {
551 return false;
554 // Steps 2-5, 10-16.
555 AutoCheckCannotGC nogc;
556 size_t length = linear->length();
557 double number;
558 if (linear->hasLatin1Chars()) {
559 if (!ParseIntImpl(cx, linear->latin1Chars(nogc), length, stripPrefix, radix,
560 &number)) {
561 return false;
563 } else {
564 if (!ParseIntImpl(cx, linear->twoByteChars(nogc), length, stripPrefix,
565 radix, &number)) {
566 return false;
570 result.setNumber(number);
571 return true;
574 // ES2023 draft rev 053d34c87b14d9234d6f7f45bd61074b72ca9d69
575 // 19.2.5 parseInt ( string, radix )
576 static bool num_parseInt(JSContext* cx, unsigned argc, Value* vp) {
577 CallArgs args = CallArgsFromVp(argc, vp);
579 /* Fast paths and exceptional cases. */
580 if (args.length() == 0) {
581 args.rval().setNaN();
582 return true;
585 if (args.length() == 1 || (args[1].isInt32() && (args[1].toInt32() == 0 ||
586 args[1].toInt32() == 10))) {
587 if (args[0].isInt32()) {
588 args.rval().set(args[0]);
589 return true;
593 * Step 1 is |inputString = ToString(string)|. When string >=
594 * 1e21, ToString(string) is in the form "NeM". 'e' marks the end of
595 * the word, which would mean the result of parseInt(string) should be |N|.
597 * To preserve this behaviour, we can't use the fast-path when string >=
598 * 1e21, or else the result would be |NeM|.
600 * The same goes for values smaller than 1.0e-6, because the string would be
601 * in the form of "Ne-M".
603 if (args[0].isDouble()) {
604 double d = args[0].toDouble();
605 if (DOUBLE_DECIMAL_IN_SHORTEST_LOW <= d &&
606 d < DOUBLE_DECIMAL_IN_SHORTEST_HIGH) {
607 args.rval().setNumber(floor(d));
608 return true;
610 if (-DOUBLE_DECIMAL_IN_SHORTEST_HIGH < d &&
611 d <= -DOUBLE_DECIMAL_IN_SHORTEST_LOW) {
612 args.rval().setNumber(-floor(-d));
613 return true;
615 if (d == 0.0) {
616 args.rval().setInt32(0);
617 return true;
621 if (args[0].isString()) {
622 JSString* str = args[0].toString();
623 if (str->hasIndexValue()) {
624 args.rval().setNumber(str->getIndexValue());
625 return true;
630 // Step 1.
631 RootedString inputString(cx, ToString<CanGC>(cx, args[0]));
632 if (!inputString) {
633 return false;
636 // Step 6.
637 int32_t radix = 0;
638 if (args.hasDefined(1)) {
639 if (!ToInt32(cx, args[1], &radix)) {
640 return false;
644 // Steps 2-5, 7-16.
645 return NumberParseInt(cx, inputString, radix, args.rval());
648 static const JSFunctionSpec number_functions[] = {
649 JS_SELF_HOSTED_FN(js_isNaN_str, "Global_isNaN", 1, JSPROP_RESOLVING),
650 JS_SELF_HOSTED_FN(js_isFinite_str, "Global_isFinite", 1, JSPROP_RESOLVING),
651 JS_FS_END};
653 const JSClass NumberObject::class_ = {
654 js_Number_str,
655 JSCLASS_HAS_RESERVED_SLOTS(1) | JSCLASS_HAS_CACHED_PROTO(JSProto_Number),
656 JS_NULL_CLASS_OPS, &NumberObject::classSpec_};
658 static bool Number(JSContext* cx, unsigned argc, Value* vp) {
659 CallArgs args = CallArgsFromVp(argc, vp);
661 if (args.length() > 0) {
662 // BigInt proposal section 6.2, steps 2a-c.
663 if (!ToNumeric(cx, args[0])) {
664 return false;
666 if (args[0].isBigInt()) {
667 args[0].setNumber(BigInt::numberValue(args[0].toBigInt()));
669 MOZ_ASSERT(args[0].isNumber());
672 if (!args.isConstructing()) {
673 if (args.length() > 0) {
674 args.rval().set(args[0]);
675 } else {
676 args.rval().setInt32(0);
678 return true;
681 RootedObject proto(cx);
682 if (!GetPrototypeFromBuiltinConstructor(cx, args, JSProto_Number, &proto)) {
683 return false;
686 double d = args.length() > 0 ? args[0].toNumber() : 0;
687 JSObject* obj = NumberObject::create(cx, d, proto);
688 if (!obj) {
689 return false;
691 args.rval().setObject(*obj);
692 return true;
695 // ES2020 draft rev e08b018785606bc6465a0456a79604b149007932
696 // 20.1.3 Properties of the Number Prototype Object, thisNumberValue.
697 MOZ_ALWAYS_INLINE
698 static bool ThisNumberValue(JSContext* cx, const CallArgs& args,
699 const char* methodName, double* number) {
700 HandleValue thisv = args.thisv();
702 // Step 1.
703 if (thisv.isNumber()) {
704 *number = thisv.toNumber();
705 return true;
708 // Steps 2-3.
709 auto* obj = UnwrapAndTypeCheckThis<NumberObject>(cx, args, methodName);
710 if (!obj) {
711 return false;
714 *number = obj->unbox();
715 return true;
718 // On-off helper function for the self-hosted Number_toLocaleString method.
719 // This only exists to produce an error message with the right method name.
720 bool js::ThisNumberValueForToLocaleString(JSContext* cx, unsigned argc,
721 Value* vp) {
722 CallArgs args = CallArgsFromVp(argc, vp);
724 double d;
725 if (!ThisNumberValue(cx, args, "toLocaleString", &d)) {
726 return false;
729 args.rval().setNumber(d);
730 return true;
733 static bool num_toSource(JSContext* cx, unsigned argc, Value* vp) {
734 CallArgs args = CallArgsFromVp(argc, vp);
736 double d;
737 if (!ThisNumberValue(cx, args, "toSource", &d)) {
738 return false;
741 JSStringBuilder sb(cx);
742 if (!sb.append("(new Number(") ||
743 !NumberValueToStringBuffer(NumberValue(d), sb) || !sb.append("))")) {
744 return false;
747 JSString* str = sb.finishString();
748 if (!str) {
749 return false;
751 args.rval().setString(str);
752 return true;
755 // Subtract one from DTOSTR_STANDARD_BUFFER_SIZE to exclude the null-character.
756 static_assert(
757 double_conversion::DoubleToStringConverter::kMaxCharsEcmaScriptShortest ==
758 DTOSTR_STANDARD_BUFFER_SIZE - 1,
759 "double_conversion and dtoa both agree how large the longest string "
760 "can be");
762 static_assert(DTOSTR_STANDARD_BUFFER_SIZE <= JS::MaximumNumberToStringLength,
763 "MaximumNumberToStringLength is large enough to hold the longest "
764 "string produced by a conversion");
766 MOZ_ALWAYS_INLINE
767 static JSLinearString* LookupDtoaCache(JSContext* cx, double d) {
768 if (Realm* realm = cx->realm()) {
769 if (JSLinearString* str = realm->dtoaCache.lookup(10, d)) {
770 return str;
774 return nullptr;
777 MOZ_ALWAYS_INLINE
778 static void CacheNumber(JSContext* cx, double d, JSLinearString* str) {
779 if (Realm* realm = cx->realm()) {
780 realm->dtoaCache.cache(10, d, str);
784 MOZ_ALWAYS_INLINE
785 static JSLinearString* LookupInt32ToString(JSContext* cx, int32_t si) {
786 if (si >= 0 && StaticStrings::hasInt(si)) {
787 return cx->staticStrings().getInt(si);
790 return LookupDtoaCache(cx, si);
793 template <typename T>
794 MOZ_ALWAYS_INLINE static T* BackfillInt32InBuffer(int32_t si, T* buffer,
795 size_t size, size_t* length) {
796 uint32_t ui = Abs(si);
797 MOZ_ASSERT_IF(si == INT32_MIN, ui == uint32_t(INT32_MAX) + 1);
799 RangedPtr<T> end(buffer + size - 1, buffer, size);
800 *end = '\0';
801 RangedPtr<T> start = BackfillIndexInCharBuffer(ui, end);
802 if (si < 0) {
803 *--start = '-';
806 *length = end - start;
807 return start.get();
810 template <AllowGC allowGC>
811 JSLinearString* js::Int32ToString(JSContext* cx, int32_t si) {
812 if (JSLinearString* str = LookupInt32ToString(cx, si)) {
813 return str;
816 Latin1Char buffer[JSFatInlineString::MAX_LENGTH_LATIN1 + 1];
817 size_t length;
818 Latin1Char* start =
819 BackfillInt32InBuffer(si, buffer, std::size(buffer), &length);
821 mozilla::Range<const Latin1Char> chars(start, length);
822 JSInlineString* str =
823 NewInlineString<allowGC>(cx, chars, js::gc::Heap::Default);
824 if (!str) {
825 return nullptr;
827 if (si >= 0) {
828 str->maybeInitializeIndexValue(si);
831 CacheNumber(cx, si, str);
832 return str;
835 template JSLinearString* js::Int32ToString<CanGC>(JSContext* cx, int32_t si);
837 template JSLinearString* js::Int32ToString<NoGC>(JSContext* cx, int32_t si);
839 JSLinearString* js::Int32ToStringPure(JSContext* cx, int32_t si) {
840 AutoUnsafeCallWithABI unsafe;
841 return Int32ToString<NoGC>(cx, si);
844 JSAtom* js::Int32ToAtom(JSContext* cx, int32_t si) {
845 if (JSLinearString* str = LookupInt32ToString(cx, si)) {
846 return js::AtomizeString(cx, str);
849 char buffer[JSFatInlineString::MAX_LENGTH_TWO_BYTE + 1];
850 size_t length;
851 char* start = BackfillInt32InBuffer(
852 si, buffer, JSFatInlineString::MAX_LENGTH_TWO_BYTE + 1, &length);
854 Maybe<uint32_t> indexValue;
855 if (si >= 0) {
856 indexValue.emplace(si);
859 JSAtom* atom = Atomize(cx, start, length, indexValue);
860 if (!atom) {
861 return nullptr;
864 CacheNumber(cx, si, atom);
865 return atom;
868 frontend::TaggedParserAtomIndex js::Int32ToParserAtom(
869 FrontendContext* fc, frontend::ParserAtomsTable& parserAtoms, int32_t si) {
870 char buffer[JSFatInlineString::MAX_LENGTH_TWO_BYTE + 1];
871 size_t length;
872 char* start = BackfillInt32InBuffer(
873 si, buffer, JSFatInlineString::MAX_LENGTH_TWO_BYTE + 1, &length);
875 Maybe<uint32_t> indexValue;
876 if (si >= 0) {
877 indexValue.emplace(si);
880 return parserAtoms.internAscii(fc, start, length);
883 /* Returns a non-nullptr pointer to inside `buf`. */
884 template <typename T>
885 static char* Int32ToCStringWithBase(mozilla::Range<char> buf, T i, size_t* len,
886 int base) {
887 uint32_t u;
888 if constexpr (std::is_signed_v<T>) {
889 u = Abs(i);
890 } else {
891 u = i;
894 RangedPtr<char> cp = buf.end() - 1;
896 char* end = cp.get();
897 *cp = '\0';
899 /* Build the string from behind. */
900 switch (base) {
901 case 10:
902 cp = BackfillIndexInCharBuffer(u, cp);
903 break;
904 case 16:
905 do {
906 unsigned newu = u / 16;
907 *--cp = "0123456789abcdef"[u - newu * 16];
908 u = newu;
909 } while (u != 0);
910 break;
911 default:
912 MOZ_ASSERT(base >= 2 && base <= 36);
913 do {
914 unsigned newu = u / base;
915 *--cp = "0123456789abcdefghijklmnopqrstuvwxyz"[u - newu * base];
916 u = newu;
917 } while (u != 0);
918 break;
920 if constexpr (std::is_signed_v<T>) {
921 if (i < 0) {
922 *--cp = '-';
926 *len = end - cp.get();
927 return cp.get();
930 /* Returns a non-nullptr pointer to inside `out`. */
931 template <typename T, size_t Length>
932 static char* Int32ToCStringWithBase(char (&out)[Length], T i, size_t* len,
933 int base) {
934 // The buffer needs to be large enough to hold the largest number, including
935 // the sign and the terminating null-character.
936 static_assert(std::numeric_limits<T>::digits + (2 * std::is_signed_v<T>) <
937 Length);
939 mozilla::Range<char> buf(out, Length);
940 return Int32ToCStringWithBase(buf, i, len, base);
943 /* Returns a non-nullptr pointer to inside `out`. */
944 template <typename T, size_t Base, size_t Length>
945 static char* Int32ToCString(char (&out)[Length], T i, size_t* len) {
946 // The buffer needs to be large enough to hold the largest number, including
947 // the sign and the terminating null-character.
948 if constexpr (Base == 10) {
949 static_assert(std::numeric_limits<T>::digits10 + 1 + std::is_signed_v<T> <
950 Length);
951 } else {
952 // Compute digits16 analog to std::numeric_limits::digits10, which is
953 // defined as |std::numeric_limits::digits * std::log10(2)| for integer
954 // types.
955 // Note: log16(2) is 1/4.
956 static_assert(Base == 16);
957 static_assert(((std::numeric_limits<T>::digits + std::is_signed_v<T>) / 4 +
958 std::is_signed_v<T>) < Length);
961 mozilla::Range<char> buf(out, Length);
962 return Int32ToCStringWithBase(buf, i, len, Base);
965 /* Returns a non-nullptr pointer to inside `cbuf`. */
966 template <typename T, size_t Base = 10>
967 static char* Int32ToCString(ToCStringBuf* cbuf, T i, size_t* len) {
968 return Int32ToCString<T, Base>(cbuf->sbuf, i, len);
971 /* Returns a non-nullptr pointer to inside `cbuf`. */
972 template <typename T, size_t Base = 10>
973 static char* Int32ToCString(Int32ToCStringBuf* cbuf, T i, size_t* len) {
974 return Int32ToCString<T, Base>(cbuf->sbuf, i, len);
977 template <AllowGC allowGC>
978 static JSString* NumberToStringWithBase(JSContext* cx, double d, int base);
980 static bool num_toString(JSContext* cx, unsigned argc, Value* vp) {
981 CallArgs args = CallArgsFromVp(argc, vp);
983 double d;
984 if (!ThisNumberValue(cx, args, "toString", &d)) {
985 return false;
988 int32_t base = 10;
989 if (args.hasDefined(0)) {
990 double d2;
991 if (!ToInteger(cx, args[0], &d2)) {
992 return false;
995 if (d2 < 2 || d2 > 36) {
996 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr, JSMSG_BAD_RADIX);
997 return false;
1000 base = int32_t(d2);
1002 JSString* str = NumberToStringWithBase<CanGC>(cx, d, base);
1003 if (!str) {
1004 return false;
1006 args.rval().setString(str);
1007 return true;
1010 #if !JS_HAS_INTL_API
1011 static bool num_toLocaleString(JSContext* cx, unsigned argc, Value* vp) {
1012 AutoJSMethodProfilerEntry pseudoFrame(cx, "Number.prototype",
1013 "toLocaleString");
1014 CallArgs args = CallArgsFromVp(argc, vp);
1016 double d;
1017 if (!ThisNumberValue(cx, args, "toLocaleString", &d)) {
1018 return false;
1021 RootedString str(cx, NumberToStringWithBase<CanGC>(cx, d, 10));
1022 if (!str) {
1023 return false;
1027 * Create the string, move back to bytes to make string twiddling
1028 * a bit easier and so we can insert platform charset seperators.
1030 UniqueChars numBytes = EncodeAscii(cx, str);
1031 if (!numBytes) {
1032 return false;
1034 const char* num = numBytes.get();
1035 if (!num) {
1036 return false;
1040 * Find the first non-integer value, whether it be a letter as in
1041 * 'Infinity', a decimal point, or an 'e' from exponential notation.
1043 const char* nint = num;
1044 if (*nint == '-') {
1045 nint++;
1047 while (*nint >= '0' && *nint <= '9') {
1048 nint++;
1050 int digits = nint - num;
1051 const char* end = num + digits;
1052 if (!digits) {
1053 args.rval().setString(str);
1054 return true;
1057 JSRuntime* rt = cx->runtime();
1058 size_t thousandsLength = strlen(rt->thousandsSeparator);
1059 size_t decimalLength = strlen(rt->decimalSeparator);
1061 /* Figure out how long resulting string will be. */
1062 int buflen = strlen(num);
1063 if (*nint == '.') {
1064 buflen += decimalLength - 1; /* -1 to account for existing '.' */
1067 const char* numGrouping;
1068 const char* tmpGroup;
1069 numGrouping = tmpGroup = rt->numGrouping;
1070 int remainder = digits;
1071 if (*num == '-') {
1072 remainder--;
1075 while (*tmpGroup != CHAR_MAX && *tmpGroup != '\0') {
1076 if (*tmpGroup >= remainder) {
1077 break;
1079 buflen += thousandsLength;
1080 remainder -= *tmpGroup;
1081 tmpGroup++;
1084 int nrepeat;
1085 if (*tmpGroup == '\0' && *numGrouping != '\0') {
1086 nrepeat = (remainder - 1) / tmpGroup[-1];
1087 buflen += thousandsLength * nrepeat;
1088 remainder -= nrepeat * tmpGroup[-1];
1089 } else {
1090 nrepeat = 0;
1092 tmpGroup--;
1094 char* buf = cx->pod_malloc<char>(buflen + 1);
1095 if (!buf) {
1096 return false;
1099 char* tmpDest = buf;
1100 const char* tmpSrc = num;
1102 while (*tmpSrc == '-' || remainder--) {
1103 MOZ_ASSERT(tmpDest - buf < buflen);
1104 *tmpDest++ = *tmpSrc++;
1106 while (tmpSrc < end) {
1107 MOZ_ASSERT(tmpDest - buf + ptrdiff_t(thousandsLength) <= buflen);
1108 strcpy(tmpDest, rt->thousandsSeparator);
1109 tmpDest += thousandsLength;
1110 MOZ_ASSERT(tmpDest - buf + *tmpGroup <= buflen);
1111 js_memcpy(tmpDest, tmpSrc, *tmpGroup);
1112 tmpDest += *tmpGroup;
1113 tmpSrc += *tmpGroup;
1114 if (--nrepeat < 0) {
1115 tmpGroup--;
1119 if (*nint == '.') {
1120 MOZ_ASSERT(tmpDest - buf + ptrdiff_t(decimalLength) <= buflen);
1121 strcpy(tmpDest, rt->decimalSeparator);
1122 tmpDest += decimalLength;
1123 MOZ_ASSERT(tmpDest - buf + ptrdiff_t(strlen(nint + 1)) <= buflen);
1124 strcpy(tmpDest, nint + 1);
1125 } else {
1126 MOZ_ASSERT(tmpDest - buf + ptrdiff_t(strlen(nint)) <= buflen);
1127 strcpy(tmpDest, nint);
1130 if (cx->runtime()->localeCallbacks &&
1131 cx->runtime()->localeCallbacks->localeToUnicode) {
1132 Rooted<Value> v(cx, StringValue(str));
1133 bool ok = !!cx->runtime()->localeCallbacks->localeToUnicode(cx, buf, &v);
1134 if (ok) {
1135 args.rval().set(v);
1137 js_free(buf);
1138 return ok;
1141 str = NewStringCopyN<CanGC>(cx, buf, buflen);
1142 js_free(buf);
1143 if (!str) {
1144 return false;
1147 args.rval().setString(str);
1148 return true;
1150 #endif /* !JS_HAS_INTL_API */
1152 bool js::num_valueOf(JSContext* cx, unsigned argc, Value* vp) {
1153 CallArgs args = CallArgsFromVp(argc, vp);
1155 double d;
1156 if (!ThisNumberValue(cx, args, "valueOf", &d)) {
1157 return false;
1160 args.rval().setNumber(d);
1161 return true;
1164 static const unsigned MAX_PRECISION = 100;
1166 static bool ComputePrecisionInRange(JSContext* cx, int minPrecision,
1167 int maxPrecision, double prec,
1168 int* precision) {
1169 if (minPrecision <= prec && prec <= maxPrecision) {
1170 *precision = int(prec);
1171 return true;
1174 ToCStringBuf cbuf;
1175 char* numStr = NumberToCString(&cbuf, prec);
1176 MOZ_ASSERT(numStr);
1177 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr, JSMSG_PRECISION_RANGE,
1178 numStr);
1179 return false;
1182 static constexpr size_t DoubleToStrResultBufSize = 128;
1184 template <typename Op>
1185 [[nodiscard]] static bool DoubleToStrResult(JSContext* cx, const CallArgs& args,
1186 Op op) {
1187 char buf[DoubleToStrResultBufSize];
1189 const auto& converter =
1190 double_conversion::DoubleToStringConverter::EcmaScriptConverter();
1191 double_conversion::StringBuilder builder(buf, sizeof(buf));
1193 bool ok = op(converter, builder);
1194 MOZ_RELEASE_ASSERT(ok);
1196 size_t numStrLen = builder.position();
1197 const char* numStr = builder.Finalize();
1198 MOZ_ASSERT(numStr == buf);
1199 MOZ_ASSERT(numStrLen == strlen(numStr));
1201 JSString* str = NewStringCopyN<CanGC>(cx, numStr, numStrLen);
1202 if (!str) {
1203 return false;
1206 args.rval().setString(str);
1207 return true;
1210 // ES 2021 draft 21.1.3.3.
1211 static bool num_toFixed(JSContext* cx, unsigned argc, Value* vp) {
1212 AutoJSMethodProfilerEntry pseudoFrame(cx, "Number.prototype", "toFixed");
1213 CallArgs args = CallArgsFromVp(argc, vp);
1215 // Step 1.
1216 double d;
1217 if (!ThisNumberValue(cx, args, "toFixed", &d)) {
1218 return false;
1221 // Steps 2-5.
1222 int precision;
1223 if (args.length() == 0) {
1224 precision = 0;
1225 } else {
1226 double prec = 0;
1227 if (!ToInteger(cx, args[0], &prec)) {
1228 return false;
1231 if (!ComputePrecisionInRange(cx, 0, MAX_PRECISION, prec, &precision)) {
1232 return false;
1236 // Step 6.
1237 if (std::isnan(d)) {
1238 args.rval().setString(cx->names().NaN);
1239 return true;
1241 if (std::isinf(d)) {
1242 if (d > 0) {
1243 args.rval().setString(cx->names().Infinity);
1244 return true;
1247 args.rval().setString(cx->names().NegativeInfinity);
1248 return true;
1251 // Steps 7-10 for very large numbers.
1252 if (d <= -1e21 || d >= 1e+21) {
1253 JSString* s = NumberToString<CanGC>(cx, d);
1254 if (!s) {
1255 return false;
1258 args.rval().setString(s);
1259 return true;
1262 // Steps 7-12.
1264 // DoubleToStringConverter::ToFixed is documented as requiring a buffer size
1265 // of:
1267 // 1 + kMaxFixedDigitsBeforePoint + 1 + kMaxFixedDigitsAfterPoint + 1
1268 // (one additional character for the sign, one for the decimal point,
1269 // and one for the null terminator)
1271 // We already ensured there are at most 21 digits before the point, and
1272 // MAX_PRECISION digits after the point.
1273 static_assert(1 + 21 + 1 + MAX_PRECISION + 1 <= DoubleToStrResultBufSize);
1275 // The double-conversion library by default has a kMaxFixedDigitsAfterPoint of
1276 // 60. Assert our modified version supports at least MAX_PRECISION (100).
1277 using DToSConverter = double_conversion::DoubleToStringConverter;
1278 static_assert(DToSConverter::kMaxFixedDigitsAfterPoint >= MAX_PRECISION);
1280 return DoubleToStrResult(cx, args, [&](auto& converter, auto& builder) {
1281 return converter.ToFixed(d, precision, &builder);
1285 // ES 2021 draft 21.1.3.2.
1286 static bool num_toExponential(JSContext* cx, unsigned argc, Value* vp) {
1287 AutoJSMethodProfilerEntry pseudoFrame(cx, "Number.prototype",
1288 "toExponential");
1289 CallArgs args = CallArgsFromVp(argc, vp);
1291 // Step 1.
1292 double d;
1293 if (!ThisNumberValue(cx, args, "toExponential", &d)) {
1294 return false;
1297 // Step 2.
1298 double prec = 0;
1299 if (args.hasDefined(0)) {
1300 if (!ToInteger(cx, args[0], &prec)) {
1301 return false;
1305 // Step 3.
1306 MOZ_ASSERT_IF(!args.hasDefined(0), prec == 0);
1308 // Step 4.
1309 if (std::isnan(d)) {
1310 args.rval().setString(cx->names().NaN);
1311 return true;
1313 if (std::isinf(d)) {
1314 if (d > 0) {
1315 args.rval().setString(cx->names().Infinity);
1316 return true;
1319 args.rval().setString(cx->names().NegativeInfinity);
1320 return true;
1323 // Step 5.
1324 int precision = 0;
1325 if (!ComputePrecisionInRange(cx, 0, MAX_PRECISION, prec, &precision)) {
1326 return false;
1329 // Steps 6-15.
1331 // DoubleToStringConverter::ToExponential is documented as adding at most 8
1332 // characters on top of the requested digits: "the sign, the digit before the
1333 // decimal point, the decimal point, the exponent character, the exponent's
1334 // sign, and at most 3 exponent digits". In addition, the buffer must be able
1335 // to hold the trailing '\0' character.
1336 static_assert(MAX_PRECISION + 8 + 1 <= DoubleToStrResultBufSize);
1338 return DoubleToStrResult(cx, args, [&](auto& converter, auto& builder) {
1339 int requestedDigits = args.hasDefined(0) ? precision : -1;
1340 return converter.ToExponential(d, requestedDigits, &builder);
1344 // ES 2021 draft 21.1.3.5.
1345 static bool num_toPrecision(JSContext* cx, unsigned argc, Value* vp) {
1346 AutoJSMethodProfilerEntry pseudoFrame(cx, "Number.prototype", "toPrecision");
1347 CallArgs args = CallArgsFromVp(argc, vp);
1349 // Step 1.
1350 double d;
1351 if (!ThisNumberValue(cx, args, "toPrecision", &d)) {
1352 return false;
1355 // Step 2.
1356 if (!args.hasDefined(0)) {
1357 JSString* str = NumberToStringWithBase<CanGC>(cx, d, 10);
1358 if (!str) {
1359 return false;
1361 args.rval().setString(str);
1362 return true;
1365 // Step 3.
1366 double prec = 0;
1367 if (!ToInteger(cx, args[0], &prec)) {
1368 return false;
1371 // Step 4.
1372 if (std::isnan(d)) {
1373 args.rval().setString(cx->names().NaN);
1374 return true;
1376 if (std::isinf(d)) {
1377 if (d > 0) {
1378 args.rval().setString(cx->names().Infinity);
1379 return true;
1382 args.rval().setString(cx->names().NegativeInfinity);
1383 return true;
1386 // Step 5.
1387 int precision = 0;
1388 if (!ComputePrecisionInRange(cx, 1, MAX_PRECISION, prec, &precision)) {
1389 return false;
1392 // Steps 6-14.
1394 // DoubleToStringConverter::ToPrecision is documented as adding at most 7
1395 // characters on top of the requested digits: "the sign, the decimal point,
1396 // the exponent character, the exponent's sign, and at most 3 exponent
1397 // digits". In addition, the buffer must be able to hold the trailing '\0'
1398 // character.
1399 static_assert(MAX_PRECISION + 7 + 1 <= DoubleToStrResultBufSize);
1401 return DoubleToStrResult(cx, args, [&](auto& converter, auto& builder) {
1402 return converter.ToPrecision(d, precision, &builder);
1406 static const JSFunctionSpec number_methods[] = {
1407 JS_FN(js_toSource_str, num_toSource, 0, 0),
1408 JS_INLINABLE_FN(js_toString_str, num_toString, 1, 0, NumberToString),
1409 #if JS_HAS_INTL_API
1410 JS_SELF_HOSTED_FN(js_toLocaleString_str, "Number_toLocaleString", 0, 0),
1411 #else
1412 JS_FN(js_toLocaleString_str, num_toLocaleString, 0, 0),
1413 #endif
1414 JS_FN(js_valueOf_str, num_valueOf, 0, 0),
1415 JS_FN("toFixed", num_toFixed, 1, 0),
1416 JS_FN("toExponential", num_toExponential, 1, 0),
1417 JS_FN("toPrecision", num_toPrecision, 1, 0),
1418 JS_FS_END};
1420 bool js::IsInteger(double d) {
1421 return std::isfinite(d) && JS::ToInteger(d) == d;
1424 static const JSFunctionSpec number_static_methods[] = {
1425 JS_SELF_HOSTED_FN("isFinite", "Number_isFinite", 1, 0),
1426 JS_SELF_HOSTED_FN("isInteger", "Number_isInteger", 1, 0),
1427 JS_SELF_HOSTED_FN("isNaN", "Number_isNaN", 1, 0),
1428 JS_SELF_HOSTED_FN("isSafeInteger", "Number_isSafeInteger", 1, 0),
1429 JS_FS_END};
1431 static const JSPropertySpec number_static_properties[] = {
1432 JS_DOUBLE_PS("POSITIVE_INFINITY", mozilla::PositiveInfinity<double>(),
1433 JSPROP_READONLY | JSPROP_PERMANENT),
1434 JS_DOUBLE_PS("NEGATIVE_INFINITY", mozilla::NegativeInfinity<double>(),
1435 JSPROP_READONLY | JSPROP_PERMANENT),
1436 JS_DOUBLE_PS("MAX_VALUE", 1.7976931348623157E+308,
1437 JSPROP_READONLY | JSPROP_PERMANENT),
1438 JS_DOUBLE_PS("MIN_VALUE", MinNumberValue<double>(),
1439 JSPROP_READONLY | JSPROP_PERMANENT),
1440 /* ES6 (April 2014 draft) 20.1.2.6 */
1441 JS_DOUBLE_PS("MAX_SAFE_INTEGER", 9007199254740991,
1442 JSPROP_READONLY | JSPROP_PERMANENT),
1443 /* ES6 (April 2014 draft) 20.1.2.10 */
1444 JS_DOUBLE_PS("MIN_SAFE_INTEGER", -9007199254740991,
1445 JSPROP_READONLY | JSPROP_PERMANENT),
1446 /* ES6 (May 2013 draft) 15.7.3.7 */
1447 JS_DOUBLE_PS("EPSILON", 2.2204460492503130808472633361816e-16,
1448 JSPROP_READONLY | JSPROP_PERMANENT),
1449 JS_PS_END};
1451 bool js::InitRuntimeNumberState(JSRuntime* rt) {
1452 // XXX If JS_HAS_INTL_API becomes true all the time at some point,
1453 // js::InitRuntimeNumberState is no longer fallible, and we should
1454 // change its return type.
1455 #if !JS_HAS_INTL_API
1456 /* Copy locale-specific separators into the runtime strings. */
1457 const char* thousandsSeparator;
1458 const char* decimalPoint;
1459 const char* grouping;
1460 # ifdef HAVE_LOCALECONV
1461 struct lconv* locale = localeconv();
1462 thousandsSeparator = locale->thousands_sep;
1463 decimalPoint = locale->decimal_point;
1464 grouping = locale->grouping;
1465 # else
1466 thousandsSeparator = getenv("LOCALE_THOUSANDS_SEP");
1467 decimalPoint = getenv("LOCALE_DECIMAL_POINT");
1468 grouping = getenv("LOCALE_GROUPING");
1469 # endif
1470 if (!thousandsSeparator) {
1471 thousandsSeparator = "'";
1473 if (!decimalPoint) {
1474 decimalPoint = ".";
1476 if (!grouping) {
1477 grouping = "\3\0";
1481 * We use single malloc to get the memory for all separator and grouping
1482 * strings.
1484 size_t thousandsSeparatorSize = strlen(thousandsSeparator) + 1;
1485 size_t decimalPointSize = strlen(decimalPoint) + 1;
1486 size_t groupingSize = strlen(grouping) + 1;
1488 char* storage = js_pod_malloc<char>(thousandsSeparatorSize +
1489 decimalPointSize + groupingSize);
1490 if (!storage) {
1491 return false;
1494 js_memcpy(storage, thousandsSeparator, thousandsSeparatorSize);
1495 rt->thousandsSeparator = storage;
1496 storage += thousandsSeparatorSize;
1498 js_memcpy(storage, decimalPoint, decimalPointSize);
1499 rt->decimalSeparator = storage;
1500 storage += decimalPointSize;
1502 js_memcpy(storage, grouping, groupingSize);
1503 rt->numGrouping = grouping;
1504 #endif /* !JS_HAS_INTL_API */
1505 return true;
1508 void js::FinishRuntimeNumberState(JSRuntime* rt) {
1509 #if !JS_HAS_INTL_API
1511 * The free also releases the memory for decimalSeparator and numGrouping
1512 * strings.
1514 char* storage = const_cast<char*>(rt->thousandsSeparator.ref());
1515 js_free(storage);
1516 #endif // !JS_HAS_INTL_API
1519 JSObject* NumberObject::createPrototype(JSContext* cx, JSProtoKey key) {
1520 NumberObject* numberProto =
1521 GlobalObject::createBlankPrototype<NumberObject>(cx, cx->global());
1522 if (!numberProto) {
1523 return nullptr;
1525 numberProto->setPrimitiveValue(0);
1526 return numberProto;
1529 static bool NumberClassFinish(JSContext* cx, HandleObject ctor,
1530 HandleObject proto) {
1531 Handle<GlobalObject*> global = cx->global();
1533 if (!JS_DefineFunctions(cx, global, number_functions)) {
1534 return false;
1537 // Number.parseInt should be the same function object as global parseInt.
1538 RootedId parseIntId(cx, NameToId(cx->names().parseInt));
1539 JSFunction* parseInt =
1540 DefineFunction(cx, global, parseIntId, num_parseInt, 2, JSPROP_RESOLVING);
1541 if (!parseInt) {
1542 return false;
1544 parseInt->setJitInfo(&jit::JitInfo_NumberParseInt);
1546 RootedValue parseIntValue(cx, ObjectValue(*parseInt));
1547 if (!DefineDataProperty(cx, ctor, parseIntId, parseIntValue, 0)) {
1548 return false;
1551 // Number.parseFloat should be the same function object as global
1552 // parseFloat.
1553 RootedId parseFloatId(cx, NameToId(cx->names().parseFloat));
1554 JSFunction* parseFloat = DefineFunction(cx, global, parseFloatId,
1555 num_parseFloat, 1, JSPROP_RESOLVING);
1556 if (!parseFloat) {
1557 return false;
1559 RootedValue parseFloatValue(cx, ObjectValue(*parseFloat));
1560 if (!DefineDataProperty(cx, ctor, parseFloatId, parseFloatValue, 0)) {
1561 return false;
1564 RootedValue valueNaN(cx, JS::NaNValue());
1565 RootedValue valueInfinity(cx, JS::InfinityValue());
1567 if (!DefineDataProperty(
1568 cx, ctor, cx->names().NaN, valueNaN,
1569 JSPROP_PERMANENT | JSPROP_READONLY | JSPROP_RESOLVING)) {
1570 return false;
1573 // ES5 15.1.1.1, 15.1.1.2
1574 if (!NativeDefineDataProperty(
1575 cx, global, cx->names().NaN, valueNaN,
1576 JSPROP_PERMANENT | JSPROP_READONLY | JSPROP_RESOLVING) ||
1577 !NativeDefineDataProperty(
1578 cx, global, cx->names().Infinity, valueInfinity,
1579 JSPROP_PERMANENT | JSPROP_READONLY | JSPROP_RESOLVING)) {
1580 return false;
1583 return true;
1586 const ClassSpec NumberObject::classSpec_ = {
1587 GenericCreateConstructor<Number, 1, gc::AllocKind::FUNCTION,
1588 &jit::JitInfo_Number>,
1589 NumberObject::createPrototype,
1590 number_static_methods,
1591 number_static_properties,
1592 number_methods,
1593 nullptr,
1594 NumberClassFinish};
1596 static char* FracNumberToCString(ToCStringBuf* cbuf, double d, size_t* len) {
1597 #ifdef DEBUG
1599 int32_t _;
1600 MOZ_ASSERT(!NumberEqualsInt32(d, &_));
1602 #endif
1605 * This is V8's implementation of the algorithm described in the
1606 * following paper:
1608 * Printing floating-point numbers quickly and accurately with integers.
1609 * Florian Loitsch, PLDI 2010.
1611 const double_conversion::DoubleToStringConverter& converter =
1612 double_conversion::DoubleToStringConverter::EcmaScriptConverter();
1613 double_conversion::StringBuilder builder(cbuf->sbuf, std::size(cbuf->sbuf));
1614 converter.ToShortest(d, &builder);
1616 *len = builder.position();
1617 return builder.Finalize();
1620 void JS::NumberToString(double d, char (&out)[MaximumNumberToStringLength]) {
1621 int32_t i;
1622 if (NumberEqualsInt32(d, &i)) {
1623 Int32ToCStringBuf cbuf;
1624 size_t len;
1625 char* loc = ::Int32ToCString(&cbuf, i, &len);
1626 memmove(out, loc, len);
1627 out[len] = '\0';
1628 } else {
1629 const double_conversion::DoubleToStringConverter& converter =
1630 double_conversion::DoubleToStringConverter::EcmaScriptConverter();
1632 double_conversion::StringBuilder builder(out, sizeof(out));
1633 converter.ToShortest(d, &builder);
1635 #ifdef DEBUG
1636 char* result =
1637 #endif
1638 builder.Finalize();
1639 MOZ_ASSERT(out == result);
1643 char* js::NumberToCString(ToCStringBuf* cbuf, double d, size_t* length) {
1644 int32_t i;
1645 size_t len;
1646 char* s = NumberEqualsInt32(d, &i) ? ::Int32ToCString(cbuf, i, &len)
1647 : FracNumberToCString(cbuf, d, &len);
1648 MOZ_ASSERT(s);
1649 if (length) {
1650 *length = len;
1652 return s;
1655 char* js::Int32ToCString(Int32ToCStringBuf* cbuf, int32_t value,
1656 size_t* length) {
1657 size_t len;
1658 char* s = ::Int32ToCString(cbuf, value, &len);
1659 MOZ_ASSERT(s);
1660 if (length) {
1661 *length = len;
1663 return s;
1666 char* js::Uint32ToCString(Int32ToCStringBuf* cbuf, uint32_t value,
1667 size_t* length) {
1668 size_t len;
1669 char* s = ::Int32ToCString(cbuf, value, &len);
1670 MOZ_ASSERT(s);
1671 if (length) {
1672 *length = len;
1674 return s;
1677 char* js::Uint32ToHexCString(Int32ToCStringBuf* cbuf, uint32_t value,
1678 size_t* length) {
1679 size_t len;
1680 char* s = ::Int32ToCString<uint32_t, 16>(cbuf, value, &len);
1681 MOZ_ASSERT(s);
1682 if (length) {
1683 *length = len;
1685 return s;
1688 template <AllowGC allowGC>
1689 static JSString* NumberToStringWithBase(JSContext* cx, double d, int base) {
1690 MOZ_ASSERT(2 <= base && base <= 36);
1692 Realm* realm = cx->realm();
1694 int32_t i;
1695 if (NumberEqualsInt32(d, &i)) {
1696 bool isBase10Int = (base == 10);
1697 if (isBase10Int) {
1698 static_assert(StaticStrings::INT_STATIC_LIMIT > 10 * 10);
1699 if (StaticStrings::hasInt(i)) {
1700 return cx->staticStrings().getInt(i);
1702 } else if (unsigned(i) < unsigned(base)) {
1703 if (i < 10) {
1704 return cx->staticStrings().getInt(i);
1706 char16_t c = 'a' + i - 10;
1707 MOZ_ASSERT(StaticStrings::hasUnit(c));
1708 return cx->staticStrings().getUnit(c);
1709 } else if (unsigned(i) < unsigned(base * base)) {
1710 static constexpr char digits[] = "0123456789abcdefghijklmnopqrstuvwxyz";
1711 char chars[] = {digits[i / base], digits[i % base]};
1712 JSString* str = cx->staticStrings().lookup(chars, 2);
1713 MOZ_ASSERT(str);
1714 return str;
1717 if (JSLinearString* str = realm->dtoaCache.lookup(base, d)) {
1718 return str;
1721 // Plus three to include the largest number, the sign, and the terminating
1722 // null character.
1723 constexpr size_t MaximumLength = std::numeric_limits<int32_t>::digits + 3;
1725 char buf[MaximumLength] = {};
1726 size_t numStrLen;
1727 char* numStr = Int32ToCStringWithBase(buf, i, &numStrLen, base);
1728 MOZ_ASSERT(numStrLen == strlen(numStr));
1730 JSLinearString* s = NewStringCopyN<allowGC>(cx, numStr, numStrLen);
1731 if (!s) {
1732 return nullptr;
1735 if (isBase10Int && i >= 0) {
1736 s->maybeInitializeIndexValue(i);
1739 realm->dtoaCache.cache(base, d, s);
1740 return s;
1743 if (JSLinearString* str = realm->dtoaCache.lookup(base, d)) {
1744 return str;
1747 JSLinearString* s;
1748 if (base == 10) {
1749 // We use a faster algorithm for base 10.
1750 ToCStringBuf cbuf;
1751 size_t numStrLen;
1752 char* numStr = FracNumberToCString(&cbuf, d, &numStrLen);
1753 MOZ_ASSERT(numStr);
1754 MOZ_ASSERT(numStrLen == strlen(numStr));
1756 s = NewStringCopyN<allowGC>(cx, numStr, numStrLen);
1757 if (!s) {
1758 return nullptr;
1760 } else {
1761 if (!EnsureDtoaState(cx)) {
1762 if constexpr (allowGC) {
1763 ReportOutOfMemory(cx);
1765 return nullptr;
1768 UniqueChars numStr(js_dtobasestr(cx->dtoaState, base, d));
1769 if (!numStr) {
1770 if constexpr (allowGC) {
1771 ReportOutOfMemory(cx);
1773 return nullptr;
1776 s = NewStringCopyZ<allowGC>(cx, numStr.get());
1777 if (!s) {
1778 return nullptr;
1782 realm->dtoaCache.cache(base, d, s);
1783 return s;
1786 template <AllowGC allowGC>
1787 JSString* js::NumberToString(JSContext* cx, double d) {
1788 return NumberToStringWithBase<allowGC>(cx, d, 10);
1791 template JSString* js::NumberToString<CanGC>(JSContext* cx, double d);
1793 template JSString* js::NumberToString<NoGC>(JSContext* cx, double d);
1795 JSString* js::NumberToStringPure(JSContext* cx, double d) {
1796 AutoUnsafeCallWithABI unsafe;
1797 return NumberToString<NoGC>(cx, d);
1800 JSAtom* js::NumberToAtom(JSContext* cx, double d) {
1801 int32_t si;
1802 if (NumberEqualsInt32(d, &si)) {
1803 return Int32ToAtom(cx, si);
1806 if (JSLinearString* str = LookupDtoaCache(cx, d)) {
1807 return AtomizeString(cx, str);
1810 ToCStringBuf cbuf;
1811 size_t length;
1812 char* numStr = FracNumberToCString(&cbuf, d, &length);
1813 MOZ_ASSERT(numStr);
1814 MOZ_ASSERT(std::begin(cbuf.sbuf) <= numStr && numStr < std::end(cbuf.sbuf));
1815 MOZ_ASSERT(length == strlen(numStr));
1817 JSAtom* atom = Atomize(cx, numStr, length);
1818 if (!atom) {
1819 return nullptr;
1822 CacheNumber(cx, d, atom);
1824 return atom;
1827 frontend::TaggedParserAtomIndex js::NumberToParserAtom(
1828 FrontendContext* fc, frontend::ParserAtomsTable& parserAtoms, double d) {
1829 int32_t si;
1830 if (NumberEqualsInt32(d, &si)) {
1831 return Int32ToParserAtom(fc, parserAtoms, si);
1834 ToCStringBuf cbuf;
1835 size_t length;
1836 char* numStr = FracNumberToCString(&cbuf, d, &length);
1837 MOZ_ASSERT(numStr);
1838 MOZ_ASSERT(std::begin(cbuf.sbuf) <= numStr && numStr < std::end(cbuf.sbuf));
1839 MOZ_ASSERT(length == strlen(numStr));
1841 return parserAtoms.internAscii(fc, numStr, length);
1844 JSLinearString* js::IndexToString(JSContext* cx, uint32_t index) {
1845 if (StaticStrings::hasUint(index)) {
1846 return cx->staticStrings().getUint(index);
1849 Realm* realm = cx->realm();
1850 if (JSLinearString* str = realm->dtoaCache.lookup(10, index)) {
1851 return str;
1854 Latin1Char buffer[JSFatInlineString::MAX_LENGTH_LATIN1 + 1];
1855 RangedPtr<Latin1Char> end(buffer + JSFatInlineString::MAX_LENGTH_LATIN1,
1856 buffer, JSFatInlineString::MAX_LENGTH_LATIN1 + 1);
1857 *end = '\0';
1858 RangedPtr<Latin1Char> start = BackfillIndexInCharBuffer(index, end);
1860 mozilla::Range<const Latin1Char> chars(start.get(), end - start);
1861 JSInlineString* str =
1862 NewInlineString<CanGC>(cx, chars, js::gc::Heap::Default);
1863 if (!str) {
1864 return nullptr;
1867 realm->dtoaCache.cache(10, index, str);
1868 return str;
1871 JSString* js::Int32ToStringWithBase(JSContext* cx, int32_t i, int32_t base) {
1872 return NumberToStringWithBase<CanGC>(cx, double(i), base);
1875 bool js::NumberValueToStringBuffer(const Value& v, StringBuffer& sb) {
1876 /* Convert to C-string. */
1877 ToCStringBuf cbuf;
1878 const char* cstr;
1879 size_t cstrlen;
1880 if (v.isInt32()) {
1881 cstr = ::Int32ToCString(&cbuf, v.toInt32(), &cstrlen);
1882 } else {
1883 cstr = NumberToCString(&cbuf, v.toDouble(), &cstrlen);
1885 MOZ_ASSERT(cstr);
1886 MOZ_ASSERT(cstrlen == strlen(cstr));
1888 MOZ_ASSERT(cstrlen < std::size(cbuf.sbuf));
1889 return sb.append(cstr, cstrlen);
1892 template <typename CharT>
1893 inline double CharToNumber(CharT c) {
1894 if ('0' <= c && c <= '9') {
1895 return c - '0';
1897 if (unicode::IsSpace(c)) {
1898 return 0.0;
1900 return GenericNaN();
1903 template <typename CharT>
1904 inline bool CharsToNonDecimalNumber(const CharT* start, const CharT* end,
1905 double* result) {
1906 MOZ_ASSERT(end - start >= 2);
1907 MOZ_ASSERT(start[0] == '0');
1909 int radix = 0;
1910 if (start[1] == 'b' || start[1] == 'B') {
1911 radix = 2;
1912 } else if (start[1] == 'o' || start[1] == 'O') {
1913 radix = 8;
1914 } else if (start[1] == 'x' || start[1] == 'X') {
1915 radix = 16;
1916 } else {
1917 return false;
1920 // It's probably a non-decimal number. Accept if there's at least one digit
1921 // after the 0b|0o|0x, and if no non-whitespace characters follow all the
1922 // digits.
1923 const CharT* endptr;
1924 double d;
1925 MOZ_ALWAYS_TRUE(GetPrefixIntegerImpl(
1926 start + 2, end, radix, IntegerSeparatorHandling::None, &endptr, &d));
1927 if (endptr == start + 2 || SkipSpace(endptr, end) != end) {
1928 *result = GenericNaN();
1929 } else {
1930 *result = d;
1932 return true;
1935 template <typename CharT>
1936 double js::CharsToNumber(const CharT* chars, size_t length) {
1937 if (length == 1) {
1938 return CharToNumber(chars[0]);
1941 const CharT* end = chars + length;
1942 const CharT* start = SkipSpace(chars, end);
1944 // ECMA doesn't allow signed non-decimal numbers (bug 273467).
1945 if (end - start >= 2 && start[0] == '0') {
1946 double d;
1947 if (CharsToNonDecimalNumber(start, end, &d)) {
1948 return d;
1953 * Note that ECMA doesn't treat a string beginning with a '0' as
1954 * an octal number here. This works because all such numbers will
1955 * be interpreted as decimal by js_strtod. Also, any hex numbers
1956 * that have made it here (which can only be negative ones) will
1957 * be treated as 0 without consuming the 'x' by js_strtod.
1959 const CharT* ep;
1960 double d = js_strtod(start, end, &ep);
1961 if (SkipSpace(ep, end) != end) {
1962 return GenericNaN();
1964 return d;
1967 template double js::CharsToNumber(const Latin1Char* chars, size_t length);
1969 template double js::CharsToNumber(const char16_t* chars, size_t length);
1971 double js::LinearStringToNumber(JSLinearString* str) {
1972 if (str->hasIndexValue()) {
1973 return str->getIndexValue();
1976 AutoCheckCannotGC nogc;
1977 return str->hasLatin1Chars()
1978 ? CharsToNumber(str->latin1Chars(nogc), str->length())
1979 : CharsToNumber(str->twoByteChars(nogc), str->length());
1982 bool js::StringToNumber(JSContext* cx, JSString* str, double* result) {
1983 JSLinearString* linearStr = str->ensureLinear(cx);
1984 if (!linearStr) {
1985 return false;
1988 *result = LinearStringToNumber(linearStr);
1989 return true;
1992 bool js::StringToNumberPure(JSContext* cx, JSString* str, double* result) {
1993 // IC Code calls this directly.
1994 AutoUnsafeCallWithABI unsafe;
1996 if (!StringToNumber(cx, str, result)) {
1997 cx->recoverFromOutOfMemory();
1998 return false;
2000 return true;
2003 JS_PUBLIC_API bool js::ToNumberSlow(JSContext* cx, HandleValue v_,
2004 double* out) {
2005 RootedValue v(cx, v_);
2006 MOZ_ASSERT(!v.isNumber());
2008 if (!v.isPrimitive()) {
2009 if (!ToPrimitive(cx, JSTYPE_NUMBER, &v)) {
2010 return false;
2013 if (v.isNumber()) {
2014 *out = v.toNumber();
2015 return true;
2018 if (v.isString()) {
2019 return StringToNumber(cx, v.toString(), out);
2021 if (v.isBoolean()) {
2022 *out = v.toBoolean() ? 1.0 : 0.0;
2023 return true;
2025 if (v.isNull()) {
2026 *out = 0.0;
2027 return true;
2029 if (v.isUndefined()) {
2030 *out = GenericNaN();
2031 return true;
2033 #ifdef ENABLE_RECORD_TUPLE
2034 if (v.isExtendedPrimitive()) {
2035 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
2036 JSMSG_RECORD_TUPLE_TO_NUMBER);
2037 return false;
2039 #endif
2041 MOZ_ASSERT(v.isSymbol() || v.isBigInt());
2042 unsigned errnum = JSMSG_SYMBOL_TO_NUMBER;
2043 if (v.isBigInt()) {
2044 errnum = JSMSG_BIGINT_TO_NUMBER;
2046 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr, errnum);
2047 return false;
2050 // BigInt proposal section 3.1.6
2051 bool js::ToNumericSlow(JSContext* cx, MutableHandleValue vp) {
2052 MOZ_ASSERT(!vp.isNumeric());
2054 // Step 1.
2055 if (!vp.isPrimitive()) {
2056 if (!ToPrimitive(cx, JSTYPE_NUMBER, vp)) {
2057 return false;
2061 // Step 2.
2062 if (vp.isBigInt()) {
2063 return true;
2066 // Step 3.
2067 return ToNumber(cx, vp);
2071 * Convert a value to an int8_t, according to the WebIDL rules for byte
2072 * conversion. Return converted value in *out on success, false on failure.
2074 JS_PUBLIC_API bool js::ToInt8Slow(JSContext* cx, const HandleValue v,
2075 int8_t* out) {
2076 MOZ_ASSERT(!v.isInt32());
2077 double d;
2078 if (v.isDouble()) {
2079 d = v.toDouble();
2080 } else {
2081 if (!ToNumberSlow(cx, v, &d)) {
2082 return false;
2085 *out = ToInt8(d);
2086 return true;
2090 * Convert a value to an uint8_t, according to the ToUInt8() function in ES6
2091 * ECMA-262, 7.1.10. Return converted value in *out on success, false on
2092 * failure.
2094 JS_PUBLIC_API bool js::ToUint8Slow(JSContext* cx, const HandleValue v,
2095 uint8_t* out) {
2096 MOZ_ASSERT(!v.isInt32());
2097 double d;
2098 if (v.isDouble()) {
2099 d = v.toDouble();
2100 } else {
2101 if (!ToNumberSlow(cx, v, &d)) {
2102 return false;
2105 *out = ToUint8(d);
2106 return true;
2110 * Convert a value to an int16_t, according to the WebIDL rules for short
2111 * conversion. Return converted value in *out on success, false on failure.
2113 JS_PUBLIC_API bool js::ToInt16Slow(JSContext* cx, const HandleValue v,
2114 int16_t* out) {
2115 MOZ_ASSERT(!v.isInt32());
2116 double d;
2117 if (v.isDouble()) {
2118 d = v.toDouble();
2119 } else {
2120 if (!ToNumberSlow(cx, v, &d)) {
2121 return false;
2124 *out = ToInt16(d);
2125 return true;
2129 * Convert a value to an int64_t, according to the WebIDL rules for long long
2130 * conversion. Return converted value in *out on success, false on failure.
2132 JS_PUBLIC_API bool js::ToInt64Slow(JSContext* cx, const HandleValue v,
2133 int64_t* out) {
2134 MOZ_ASSERT(!v.isInt32());
2135 double d;
2136 if (v.isDouble()) {
2137 d = v.toDouble();
2138 } else {
2139 if (!ToNumberSlow(cx, v, &d)) {
2140 return false;
2143 *out = ToInt64(d);
2144 return true;
2148 * Convert a value to an uint64_t, according to the WebIDL rules for unsigned
2149 * long long conversion. Return converted value in *out on success, false on
2150 * failure.
2152 JS_PUBLIC_API bool js::ToUint64Slow(JSContext* cx, const HandleValue v,
2153 uint64_t* out) {
2154 MOZ_ASSERT(!v.isInt32());
2155 double d;
2156 if (v.isDouble()) {
2157 d = v.toDouble();
2158 } else {
2159 if (!ToNumberSlow(cx, v, &d)) {
2160 return false;
2163 *out = ToUint64(d);
2164 return true;
2167 JS_PUBLIC_API bool js::ToInt32Slow(JSContext* cx, const HandleValue v,
2168 int32_t* out) {
2169 MOZ_ASSERT(!v.isInt32());
2170 double d;
2171 if (v.isDouble()) {
2172 d = v.toDouble();
2173 } else {
2174 if (!ToNumberSlow(cx, v, &d)) {
2175 return false;
2178 *out = ToInt32(d);
2179 return true;
2182 bool js::ToInt32OrBigIntSlow(JSContext* cx, MutableHandleValue vp) {
2183 MOZ_ASSERT(!vp.isInt32());
2184 if (vp.isDouble()) {
2185 vp.setInt32(ToInt32(vp.toDouble()));
2186 return true;
2189 if (!ToNumeric(cx, vp)) {
2190 return false;
2193 if (vp.isBigInt()) {
2194 return true;
2197 vp.setInt32(ToInt32(vp.toNumber()));
2198 return true;
2201 JS_PUBLIC_API bool js::ToUint32Slow(JSContext* cx, const HandleValue v,
2202 uint32_t* out) {
2203 MOZ_ASSERT(!v.isInt32());
2204 double d;
2205 if (v.isDouble()) {
2206 d = v.toDouble();
2207 } else {
2208 if (!ToNumberSlow(cx, v, &d)) {
2209 return false;
2212 *out = ToUint32(d);
2213 return true;
2216 JS_PUBLIC_API bool js::ToUint16Slow(JSContext* cx, const HandleValue v,
2217 uint16_t* out) {
2218 MOZ_ASSERT(!v.isInt32());
2219 double d;
2220 if (v.isDouble()) {
2221 d = v.toDouble();
2222 } else if (!ToNumberSlow(cx, v, &d)) {
2223 return false;
2225 *out = ToUint16(d);
2226 return true;
2229 // ES2017 draft 7.1.17 ToIndex
2230 bool js::ToIndexSlow(JSContext* cx, JS::HandleValue v,
2231 const unsigned errorNumber, uint64_t* index) {
2232 MOZ_ASSERT_IF(v.isInt32(), v.toInt32() < 0);
2234 // Step 1.
2235 if (v.isUndefined()) {
2236 *index = 0;
2237 return true;
2240 // Step 2.a.
2241 double integerIndex;
2242 if (!ToInteger(cx, v, &integerIndex)) {
2243 return false;
2246 // Inlined version of ToLength.
2247 // 1. Already an integer.
2248 // 2. Step eliminates < 0, +0 == -0 with SameValueZero.
2249 // 3/4. Limit to <= 2^53-1, so everything above should fail.
2250 if (integerIndex < 0 || integerIndex >= DOUBLE_INTEGRAL_PRECISION_LIMIT) {
2251 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr, errorNumber);
2252 return false;
2255 // Step 3.
2256 *index = uint64_t(integerIndex);
2257 return true;
2260 template <typename CharT>
2261 double js_strtod(const CharT* begin, const CharT* end, const CharT** dEnd) {
2262 const CharT* s = SkipSpace(begin, end);
2263 size_t length = end - s;
2266 // StringToDouble can make indirect calls but can't trigger a GC.
2267 JS::AutoSuppressGCAnalysis nogc;
2269 using SToDConverter = double_conversion::StringToDoubleConverter;
2270 SToDConverter converter(SToDConverter::ALLOW_TRAILING_JUNK,
2271 /* empty_string_value = */ 0.0,
2272 /* junk_string_value = */ GenericNaN(),
2273 /* infinity_symbol = */ nullptr,
2274 /* nan_symbol = */ nullptr);
2275 int lengthInt = mozilla::AssertedCast<int>(length);
2276 double d;
2277 int processed = 0;
2278 if constexpr (std::is_same_v<CharT, char16_t>) {
2279 d = converter.StringToDouble(reinterpret_cast<const uc16*>(s), lengthInt,
2280 &processed);
2281 } else {
2282 static_assert(std::is_same_v<CharT, Latin1Char>);
2283 d = converter.StringToDouble(reinterpret_cast<const char*>(s), lengthInt,
2284 &processed);
2286 MOZ_ASSERT(processed >= 0);
2287 MOZ_ASSERT(processed <= lengthInt);
2289 if (processed > 0) {
2290 *dEnd = s + processed;
2291 return d;
2295 // Try to parse +Infinity, -Infinity or Infinity. Note that we do this here
2296 // instead of using StringToDoubleConverter's infinity_symbol because it's
2297 // faster: the code below is less generic and not on the fast path for regular
2298 // doubles.
2299 static constexpr std::string_view Infinity = "Infinity";
2300 if (length >= Infinity.length()) {
2301 const CharT* afterSign = s;
2302 bool negative = (*afterSign == '-');
2303 if (negative || *afterSign == '+') {
2304 afterSign++;
2306 MOZ_ASSERT(afterSign < end);
2307 if (*afterSign == 'I' && size_t(end - afterSign) >= Infinity.length() &&
2308 EqualChars(afterSign, Infinity.data(), Infinity.length())) {
2309 *dEnd = afterSign + Infinity.length();
2310 return negative ? NegativeInfinity<double>() : PositiveInfinity<double>();
2314 *dEnd = begin;
2315 return 0.0;
2318 template double js_strtod(const char16_t* begin, const char16_t* end,
2319 const char16_t** dEnd);
2321 template double js_strtod(const Latin1Char* begin, const Latin1Char* end,
2322 const Latin1Char** dEnd);