/*
 * Copyright (C) 2015 Andy VanWagoner (thetalecrafter@gmail.com)
 * Copyright (C) 2016 Sukolsak Sakshuwong (sukolsak@gmail.com)
 * Copyright (C) 2016-2020 Apple Inc. All rights reserved.
 * Copyright (C) 2020 Sony Interactive Entertainment Inc.
 *
 * 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.
 */

#include "config.h"
#include "IntlNumberFormat.h"

#if ENABLE(INTL)

#include "Error.h"
#include "IdentifierInlines.h"
#include "IntlNumberFormatConstructor.h"
#include "IntlObject.h"
#include "JSArray.h"
#include "JSBoundFunction.h"
#include "JSCJSValueInlines.h"
#include "JSCellInlines.h"
#include "JSObjectInlines.h"
#include "ObjectConstructor.h"
#include "SlotVisitorInlines.h"
#include "StructureInlines.h"
#include <wtf/ASCIICType.h>
#include <wtf/unicode/icu/ICUHelpers.h>

namespace WTF {

template <>
ALWAYS_INLINE void deleteOwnedPtr<UNumberFormat>(UNumberFormat* numberFormat)
{
    if (numberFormat)
        unum_close(numberFormat);
}

template <>
ALWAYS_INLINE void deleteOwnedPtr<UFieldPositionIterator>(UFieldPositionIterator* iterator)
{
    if (iterator)
        ufieldpositer_close(iterator);
}

}

namespace JSC {

const ClassInfo IntlNumberFormat::s_info = { "Object", &Base::s_info, nullptr, CREATE_METHOD_TABLE(IntlNumberFormat) };

static const char* const relevantNumberExtensionKeys[1] = { "nu" };

IntlNumberFormat* IntlNumberFormat::create(VM& vm, Structure* structure)
{
    IntlNumberFormat* format = new (NotNull, allocateCell<IntlNumberFormat>(vm.heap)) IntlNumberFormat(vm, structure);
    format->finishCreation(vm);
    return format;
}

Structure* IntlNumberFormat::createStructure(VM& vm, JSGlobalObject* globalObject, JSValue prototype)
{
    return Structure::create(vm, globalObject, prototype, TypeInfo(ObjectType, StructureFlags), info());
}

IntlNumberFormat::IntlNumberFormat(VM& vm, Structure* structure)
    : JSDestructibleObject(vm, structure)
	, m_currencyDisplay(CurrencyDisplay::Code)
{
}

inline IntlNumberFormat::~IntlNumberFormat()
{
}

void IntlNumberFormat::finishCreation(VM& vm)
{
    Base::finishCreation(vm);
    ASSERT(inherits(info()));
}

void IntlNumberFormat::destroy(JSCell* cell)
{
    static_cast<IntlNumberFormat*>(cell)->IntlNumberFormat::~IntlNumberFormat();
}

void IntlNumberFormat::visitChildren(JSCell* cell, SlotVisitor& visitor)
{
    IntlNumberFormat* thisObject = jsCast<IntlNumberFormat*>(cell);
    ASSERT_GC_OBJECT_INHERITS(thisObject, info());

    Base::visitChildren(thisObject, visitor);

    visitor.append(&thisObject->m_boundFormat);
}

static Vector<String> localeData(const String& locale, size_t keyIndex)
{
    // 9.1 Internal slots of Service Constructors & 11.2.3 Internal slots (ECMA-402 2.0)
    ASSERT_UNUSED(keyIndex, !keyIndex); // The index of the extension key "nu" in relevantExtensionKeys is 0.
    return numberingSystemsForLocale(locale);
}

static inline unsigned computeCurrencySortKey(const String& currency)
{
    ASSERT(currency.length() == 3);
    ASSERT(currency.isAllSpecialCharacters<isASCIIUpper>());
    return (currency[0] << 16) + (currency[1] << 8) + currency[2];
}

static inline unsigned computeCurrencySortKey(const char* currency)
{
    ASSERT(strlen(currency) == 3);
    ASSERT(isAllSpecialCharacters<isASCIIUpper>(currency, 3));
    return (currency[0] << 16) + (currency[1] << 8) + currency[2];
}

static unsigned extractCurrencySortKey(std::pair<const char*, unsigned>* currencyMinorUnit)
{
    return computeCurrencySortKey(currencyMinorUnit->first);
}

static unsigned computeCurrencyDigits(const String& currency)
{
    // 11.1.1 The abstract operation CurrencyDigits (currency)
    // "If the ISO 4217 currency and funds code list contains currency as an alphabetic code,
    // then return the minor unit value corresponding to the currency from the list; else return 2.
	std::pair<const char*, unsigned> currencyMinorUnits[] = {
		{ "BHD", 3 },
		{ "BIF", 0 },
		{ "BYR", 0 },
		{ "CLF", 4 },
		{ "CLP", 0 },
		{ "DJF", 0 },
		{ "GNF", 0 },
		{ "IQD", 3 },
		{ "ISK", 0 },
		{ "JOD", 3 },
		{ "JPY", 0 },
		{ "KMF", 0 },
		{ "KRW", 0 },
		{ "KWD", 3 },
		{ "LYD", 3 },
		{ "OMR", 3 },
		{ "PYG", 0 },
		{ "RWF", 0 },
		{ "TND", 3 },
		{ "UGX", 0 },
		{ "UYI", 0 },
		{ "VND", 0 },
		{ "VUV", 0 },
		{ "XAF", 0 },
		{ "XOF", 0 },
		{ "XPF", 0 }
	};
	auto* currencyMinorUnit = tryBinarySearch<std::pair<const char*, unsigned>>(currencyMinorUnits, WTF_ARRAY_LENGTH(currencyMinorUnits), computeCurrencySortKey(currency), extractCurrencySortKey);
	if (currencyMinorUnit)
		return currencyMinorUnit->second;
	return 2;
}

void IntlNumberFormat::initializeNumberFormat(ExecState& state, JSValue locales, JSValue optionsValue)
{
    JSGlobalObject* globalObject = state.lexicalGlobalObject();
    VM& vm = globalObject->vm();
    ThrowScope scope(vm);

    // 11.1.2 InitializeNumberFormat (numberFormat, locales, options) (ECMA-402)
    // https://tc39.github.io/ecma402/#sec-initializenumberformat

    auto requestedLocales = canonicalizeLocaleList(&state, locales);
    RETURN_IF_EXCEPTION(vm, void());

    JSObject* options;
    if (optionsValue.isUndefined())
        options = constructEmptyObject(vm, globalObject->nullPrototypeObjectStructure());
    else {
        options = optionsValue.toObject(&state);
        RETURN_IF_EXCEPTION(vm, void());
    }

    HashMap<String, String> opt;

    String matcher = intlStringOption(&state, options, vm.propertyNames->localeMatcher, HashSet<String>(ASCIILiteral("lookup"), ASCIILiteral("best fit")), ASCIILiteral("localeMatcher must be either \"lookup\" or \"best fit\""), ASCIILiteral("best fit"));
    RETURN_IF_EXCEPTION(vm, void());
    opt.add(ASCIILiteral("localeMatcher"), matcher);

    String numberingSystem = intlStringOption(&state, options, vm.propertyNames->numberingSystem, HashSet<String>(), ASCIILiteral(), ASCIILiteral());
    RETURN_IF_EXCEPTION(scope, void());
    if (!numberingSystem.isNull()) {
        if (!isUnicodeLocaleIdentifierType(numberingSystem)) {
            throwRangeError(&state, vm, ASCIILiteral("numberingSystem is not a well-formed numbering system value"));
            return;
        }
        opt.add(ASCIILiteral("nu"), numberingSystem);
    }

    auto& availableLocales = intlNumberFormatAvailableLocales();
    auto result = resolveLocale(state, availableLocales, requestedLocales, opt, relevantNumberExtensionKeys, WTF_ARRAY_LENGTH(relevantNumberExtensionKeys), localeData);

    m_locale = result.get(ASCIILiteral("locale"));
    if (m_locale.isEmpty()) {
        throwTypeError(&state, vm, ASCIILiteral("failed to initialize NumberFormat due to invalid locale"));
        return;
    }

    m_numberingSystem = result.get(ASCIILiteral("nu"));

    String styleString = intlStringOption(&state, options, vm.propertyNames->style, HashSet<String>(ASCIILiteral("decimal"), ASCIILiteral("percent"), ASCIILiteral("currency")), ASCIILiteral("style must be either \"decimal\", \"percent\", or \"currency\""), ASCIILiteral("decimal"));
    RETURN_IF_EXCEPTION(vm, void());
    if (styleString == "decimal")
        m_style = Style::Decimal;
    else if (styleString == "percent")
        m_style = Style::Percent;
    else if (styleString == "currency")
        m_style = Style::Currency;
    else
        ASSERT_NOT_REACHED();

    String currency = intlStringOption(&state, options, Identifier::fromString(vm, "currency"), HashSet<String>(), ASCIILiteral(), ASCIILiteral());
    RETURN_IF_EXCEPTION(vm, void());
    if (!currency.isNull()) {
        if (currency.length() != 3 || !currency.isAllSpecialCharacters<isASCIIAlpha<UChar>>()) {
            vm.throwException(&state, createRangeError(&state, ASCIILiteral("currency is not a well-formed currency code")));
            return;
        }
    }

    unsigned currencyDigits;
    if (m_style == Style::Currency) {
        if (currency.isNull()) {
            throwTypeError(&state, vm, ASCIILiteral("currency must be a string"));
            return;
        }

        currency = currency.convertToASCIIUppercase();
        m_currency = currency;
        currencyDigits = computeCurrencyDigits(currency);
    }

    String currencyDisplayString = intlStringOption(&state, options, Identifier::fromString(vm, "currencyDisplay"), HashSet<String> { ASCIILiteral("code"), ASCIILiteral("symbol"), ASCIILiteral("name") }, ASCIILiteral("currencyDisplay must be either \"code\", \"symbol\", or \"name\""), ASCIILiteral("symbol"));
    RETURN_IF_EXCEPTION(vm, void());
    if (m_style == Style::Currency) {
        if (currencyDisplayString == "code")
            m_currencyDisplay = CurrencyDisplay::Code;
        else if (currencyDisplayString == "symbol")
            m_currencyDisplay = CurrencyDisplay::Symbol;
        else if (currencyDisplayString == "name")
            m_currencyDisplay = CurrencyDisplay::Name;
        else
            ASSERT_NOT_REACHED();
    }

    unsigned minimumIntegerDigits = intlNumberOption(state, options, Identifier::fromString(vm, "minimumIntegerDigits"), 1, 21, 1);
    RETURN_IF_EXCEPTION(vm, void());
    m_minimumIntegerDigits = minimumIntegerDigits;

    unsigned minimumFractionDigitsDefault = (m_style == Style::Currency) ? currencyDigits : 0;

    unsigned minimumFractionDigits = intlNumberOption(state, options, Identifier::fromString(vm, "minimumFractionDigits"), 0, 20, minimumFractionDigitsDefault);
    RETURN_IF_EXCEPTION(vm, void());
    m_minimumFractionDigits = minimumFractionDigits;

    unsigned maximumFractionDigitsDefault;
    if (m_style == Style::Currency)
        maximumFractionDigitsDefault = std::max(minimumFractionDigits, currencyDigits);
    else if (m_style == Style::Percent)
        maximumFractionDigitsDefault = minimumFractionDigits;
    else
        maximumFractionDigitsDefault = std::max(minimumFractionDigits, 3u);

    unsigned maximumFractionDigits = intlNumberOption(state, options, Identifier::fromString(vm, "maximumFractionDigits"), minimumFractionDigits, 20, maximumFractionDigitsDefault);
    RETURN_IF_EXCEPTION(vm, void());
    m_maximumFractionDigits = maximumFractionDigits;

    JSValue minimumSignificantDigitsValue = options->get(vm, &state, Identifier::fromString(vm, "minimumSignificantDigits"));
    RETURN_IF_EXCEPTION(vm, void());

    JSValue maximumSignificantDigitsValue = options->get(vm, &state, Identifier::fromString(vm, "maximumSignificantDigits"));
    RETURN_IF_EXCEPTION(vm, void());

    if (!minimumSignificantDigitsValue.isUndefined() || !maximumSignificantDigitsValue.isUndefined()) {
    	unsigned minimumSignificantDigits = intlDefaultNumberOption(state, minimumSignificantDigitsValue, Identifier::fromString(vm, "minimumSignificantDigits"), 1, 21, 1);
		RETURN_IF_EXCEPTION(scope, void());
		unsigned maximumSignificantDigits = intlDefaultNumberOption(state, maximumSignificantDigitsValue, Identifier::fromString(vm, "maximumSignificantDigits"), minimumSignificantDigits, 21, 21);
		RETURN_IF_EXCEPTION(scope, void());
        m_minimumSignificantDigits = minimumSignificantDigits;
        m_maximumSignificantDigits = maximumSignificantDigits;
    }

    bool usesFallback;
    bool useGrouping = intlBooleanOption(&state, options, Identifier::fromString(vm, "useGrouping"), usesFallback);
    if (usesFallback)
        useGrouping = true;
    RETURN_IF_EXCEPTION(vm, void());
    m_useGrouping = useGrouping;

    UNumberFormatStyle style;
    switch (m_style) {
    case Style::Decimal:
        style = UNUM_DECIMAL;
        break;
    case Style::Percent:
        style = UNUM_PERCENT;
        break;
    case Style::Currency:
        switch (m_currencyDisplay) {
        case CurrencyDisplay::Code:
            style = UNUM_CURRENCY_ISO;
            break;
        case CurrencyDisplay::Symbol:
            style = UNUM_CURRENCY;
            break;
        case CurrencyDisplay::Name:
            style = UNUM_CURRENCY_PLURAL;
            break;
        default:
            ASSERT_NOT_REACHED();
        }
        break;
    default:
        ASSERT_NOT_REACHED();
    }

    UErrorCode status = U_ZERO_ERROR;
    m_numberFormat = adoptPtr(unum_open(style, 0, 0, m_locale.utf8().data(), 0, &status));
    if (U_FAILURE(status)) {
		throwTypeError(&state, vm, "failed to initialize NumberFormat");
		return;
	}

    if (m_style == Style::Currency) {
        unum_setTextAttribute(m_numberFormat.get(), UNUM_CURRENCY_CODE, StringView(m_currency).upconvertedCharacters().get(), 3, &status);
        if (U_FAILURE(status)) {
			throwTypeError(&state, vm, "failed to initialize NumberFormat");
			return;
		}
	}
    if (!m_minimumSignificantDigits) {
        unum_setAttribute(m_numberFormat.get(), UNUM_MIN_INTEGER_DIGITS, m_minimumIntegerDigits);
        unum_setAttribute(m_numberFormat.get(), UNUM_MIN_FRACTION_DIGITS, m_minimumFractionDigits);
        unum_setAttribute(m_numberFormat.get(), UNUM_MAX_FRACTION_DIGITS, m_maximumFractionDigits);
    } else {
        unum_setAttribute(m_numberFormat.get(), UNUM_SIGNIFICANT_DIGITS_USED, true);
        unum_setAttribute(m_numberFormat.get(), UNUM_MIN_SIGNIFICANT_DIGITS, m_minimumSignificantDigits);
        unum_setAttribute(m_numberFormat.get(), UNUM_MAX_SIGNIFICANT_DIGITS, m_maximumSignificantDigits);
    }
    unum_setAttribute(m_numberFormat.get(), UNUM_GROUPING_USED, m_useGrouping);
    unum_setAttribute(m_numberFormat.get(), UNUM_ROUNDING_MODE, UNUM_ROUND_HALFUP);
}

// https://tc39.es/ecma402/#sec-formatnumber
JSValue IntlNumberFormat::format(ExecState& state, double value)
{
    ASSERT(m_numberFormat);

	VM& vm = state.vm();

    if (!m_numberFormat)
        return throwTypeError(&state, vm, "Intl.NumberFormat.prototype.format called on value that's not an object initialized as a NumberFormat");

    UErrorCode status = U_ZERO_ERROR;
    Vector<UChar, 32> buffer(32);
    auto length = unum_formatDouble(m_numberFormat.get(), value, buffer.data(), buffer.size(), 0, &status);
    if (needsToGrowToProduceBuffer(status)) {
        buffer.grow(length);
        status = U_ZERO_ERROR;
        unum_formatDouble(m_numberFormat.get(), value, buffer.data(), length, 0, &status);
    }
    if (U_FAILURE(status))
        return throwTypeError(&state, vm, ASCIILiteral("Failed to format a number."));

    return jsString(vm, String(buffer.data(), length));
}

JSValue IntlNumberFormat::format(ExecState& state, JSBigInt* value)
{
    ASSERT(m_numberFormat);

    VM& vm = state.vm();
    auto scope = DECLARE_THROW_SCOPE(vm);

    if (!m_numberFormat)
        return throwTypeError(&state, vm, "Intl.NumberFormat.prototype.format called on value that's not an object initialized as a NumberFormat");

    auto string = value->toString(&state, 10);
    RETURN_IF_EXCEPTION(scope, JSValue());

    ASSERT(string.is8Bit() && string.isAllASCII());
    auto* rawString = reinterpret_cast<const char*>(string.characters8());

    UErrorCode status = U_ZERO_ERROR;
    Vector<UChar, 32> buffer(32);
    auto length = unum_formatDecimal(m_numberFormat.get(), rawString, string.length(), buffer.data(), buffer.size(), nullptr, &status);
    if (status == U_BUFFER_OVERFLOW_ERROR) {
        buffer.grow(length);
        status = U_ZERO_ERROR;
        unum_formatDecimal(m_numberFormat.get(), rawString, string.length(), buffer.data(), length, nullptr, &status);
    }
    if (U_FAILURE(status))
        return throwTypeError(&state, vm, "Failed to format a BigInt.");

    return jsString(vm, String(buffer.data(), length));
}

ASCIILiteral IntlNumberFormat::styleString(Style style)
{
    switch (style) {
    case Style::Decimal:
        return ASCIILiteral("decimal");
    case Style::Percent:
        return ASCIILiteral("percent");
    case Style::Currency:
        return ASCIILiteral("currency");
    }
    ASSERT_NOT_REACHED();
    return ASCIILiteral();
}

ASCIILiteral IntlNumberFormat::currencyDisplayString(CurrencyDisplay currencyDisplay)
{
    switch (currencyDisplay) {
    case CurrencyDisplay::Code:
        return ASCIILiteral("code");
    case CurrencyDisplay::Symbol:
        return ASCIILiteral("symbol");
    case CurrencyDisplay::Name:
        return ASCIILiteral("name");
    }
    ASSERT_NOT_REACHED();
    return ASCIILiteral();
}

JSObject* IntlNumberFormat::resolvedOptions(ExecState& state)
{
    // 11.3.5 Intl.NumberFormat.prototype.resolvedOptions() (ECMA-402 2.0)
    // The function returns a new object whose properties and attributes are set as if
    // constructed by an object literal assigning to each of the following properties the
    // value of the corresponding internal slot of this NumberFormat object (see 11.4):
    // locale, numberingSystem, style, currency, currencyDisplay, minimumIntegerDigits,
    // minimumFractionDigits, maximumFractionDigits, minimumSignificantDigits,
    // maximumSignificantDigits, and useGrouping. Properties whose corresponding internal
    // slots are not present are not assigned.

    if (!m_numberFormat) {
        initializeNumberFormat(state, jsUndefined(), jsUndefined());
        ASSERT(!state.hadException());
    }

    JSGlobalObject* globalObject = state.lexicalGlobalObject();
    VM& vm = globalObject->vm();
    JSObject* options = constructEmptyObject(globalObject);
    options->putDirect(vm, vm.propertyNames->locale, jsString(vm, m_locale));
    options->putDirect(vm, vm.propertyNames->numberingSystem, jsString(vm, m_numberingSystem));
    options->putDirect(vm, vm.propertyNames->style, jsNontrivialString(vm, styleString(m_style)));
    if (m_style == Style::Currency) {
        options->putDirect(vm, Identifier::fromString(vm, "currency"), jsNontrivialString(vm, m_currency));
        options->putDirect(vm, Identifier::fromString(vm, "currencyDisplay"), jsNontrivialString(vm, currencyDisplayString(m_currencyDisplay)));
    }
    options->putDirect(vm, Identifier::fromString(vm, "minimumIntegerDigits"), jsNumber(m_minimumIntegerDigits));
    options->putDirect(vm, Identifier::fromString(vm, "minimumFractionDigits"), jsNumber(m_minimumFractionDigits));
    options->putDirect(vm, Identifier::fromString(vm, "maximumFractionDigits"), jsNumber(m_maximumFractionDigits));
    if (m_minimumSignificantDigits) {
        ASSERT(m_maximumSignificantDigits);
        options->putDirect(vm, Identifier::fromString(vm, "minimumSignificantDigits"), jsNumber(m_minimumSignificantDigits));
        options->putDirect(vm, Identifier::fromString(vm, "maximumSignificantDigits"), jsNumber(m_maximumSignificantDigits));
    }
    options->putDirect(vm, Identifier::fromString(vm, "useGrouping"), jsBoolean(m_useGrouping));
    return options;
}

void IntlNumberFormat::setBoundFormat(VM& vm, JSBoundFunction* format)
{
    m_boundFormat.set(vm, this, format);
}

static ASCIILiteral partTypeString(UNumberFormatFields field, double value)
{
    switch (field) {
    case UNUM_INTEGER_FIELD:
        if (std::isnan(value))
            return ASCIILiteral("nan");
        if (!std::isfinite(value))
            return ASCIILiteral("infinity");
        return ASCIILiteral("integer");
    case UNUM_FRACTION_FIELD:
        return ASCIILiteral("fraction");
    case UNUM_DECIMAL_SEPARATOR_FIELD:
        return ASCIILiteral("decimal");
    case UNUM_GROUPING_SEPARATOR_FIELD:
        return ASCIILiteral("group");
    case UNUM_CURRENCY_FIELD:
        return ASCIILiteral("currency");
    case UNUM_PERCENT_FIELD:
        return ASCIILiteral("percentSign");
    case UNUM_SIGN_FIELD:
        return value < 0 ? ASCIILiteral("minusSign") : ASCIILiteral("plusSign");
    // These should not show up because there is no way to specify them in NumberFormat options.
    // If they do, they don't fit well into any of known part types, so consider it an "unknown".
    case UNUM_PERMILL_FIELD:
    case UNUM_EXPONENT_SYMBOL_FIELD:
    case UNUM_EXPONENT_SIGN_FIELD:
    case UNUM_EXPONENT_FIELD:
    // Any newer additions to the UNumberFormatFields enum should just be considered an "unknown" part.
    default:
        return ASCIILiteral("unknown");
    }
    return ASCIILiteral("unknown");
}

void IntlNumberFormat::formatToPartsInternal(ExecState& exec, double value, const String& formatted, UFieldPositionIterator* iterator, JSArray* parts, JSString* unit)
{
    VM& vm = exec.vm();
    auto scope = DECLARE_THROW_SCOPE(vm);

    auto stringLength = formatted.length();

    int32_t literalFieldType = -1;
    IntlNumberFormatField literalField { literalFieldType, stringLength };
    Vector<IntlNumberFormatField, 32> fields(stringLength, literalField);
    int32_t beginIndex = 0;
    int32_t endIndex = 0;
    auto fieldType = ufieldpositer_next(iterator, &beginIndex, &endIndex);
    while (fieldType >= 0) {
        size_t size = endIndex - beginIndex;
        for (auto i = beginIndex; i < endIndex; ++i) {
            // Only override previous value if new value is more specific.
            if (fields[i].size >= size)
                fields[i] = IntlNumberFormatField { fieldType, size };
        }
        fieldType = ufieldpositer_next(iterator, &beginIndex, &endIndex);
    }

    auto literalString = jsNontrivialString(vm, ASCIILiteral("literal"));
    Identifier unitName;
    if (unit)
        unitName = Identifier::fromString(vm, "unit");

    size_t currentIndex = 0;
    while (currentIndex < stringLength) {
        auto startIndex = currentIndex;
        auto fieldType = fields[currentIndex].type;
        while (currentIndex < stringLength && fields[currentIndex].type == fieldType)
            ++currentIndex;
        auto partType = fieldType == literalFieldType ? literalString : jsString(vm, partTypeString(UNumberFormatFields(fieldType), value));
        auto partValue = jsSubstring(vm, formatted, startIndex, currentIndex - startIndex);
        JSObject* part = constructEmptyObject(exec.lexicalGlobalObject());
        part->putDirect(vm, vm.propertyNames->type, partType);
        part->putDirect(vm, vm.propertyNames->value, partValue);
        if (unit)
            part->putDirect(vm, unitName, unit);
        parts->push(&exec, part);
        RETURN_IF_EXCEPTION(scope, void());
    }
}

// https://tc39.github.io/ecma402/#sec-formatnumbertoparts
JSValue IntlNumberFormat::formatToParts(ExecState& exec, double value)
{
    ASSERT(m_numberFormat);

    VM& vm = exec.vm();
    auto scope = DECLARE_THROW_SCOPE(vm);

    if (!m_numberFormat)
        return throwTypeError(&exec, vm, "Intl.NumberFormat.prototype.formatToParts called on value that's not an object initialized as a NumberFormat");

    UErrorCode status = U_ZERO_ERROR;
    OwnPtr<UFieldPositionIterator> fieldItr = adoptPtr(ufieldpositer_open(&status));
    if (U_FAILURE(status))
        return throwTypeError(&exec, vm, "failed to open field position iterator");

    Vector<UChar, 32> result(32);
    auto resultLength = unum_formatDoubleForFields(m_numberFormat.get(), value, result.data(), result.size(), fieldItr.get(), &status);
    if (needsToGrowToProduceBuffer(status)) {
        status = U_ZERO_ERROR;
        result.grow(resultLength);
        unum_formatDoubleForFields(m_numberFormat.get(), value, result.data(), resultLength, fieldItr.get(), &status);
    }
    if (U_FAILURE(status))
        return throwTypeError(&exec, vm, "failed to format a number.");

    auto resultString = String(result.data(), resultLength);

    JSArray* parts = JSArray::tryCreate(vm, &exec, exec.lexicalGlobalObject()->arrayStructureForIndexingTypeDuringAllocation(ArrayWithContiguous), 0);
    RETURN_IF_EXCEPTION(scope, jsUndefined());

    formatToPartsInternal(exec, value, resultString, fieldItr.get(), parts);
    RETURN_IF_EXCEPTION(scope, jsUndefined());

    return parts;
}

} // namespace JSC

#endif // ENABLE(INTL)
