JSDOMConvertStrings.cpp [plain text]
#include "config.h"
#include "JSDOMConvertStrings.h"
#include "JSDOMExceptionHandling.h"
#include <JavaScriptCore/HeapInlines.h>
#include <JavaScriptCore/JSCJSValueInlines.h>
#include <wtf/text/StringBuilder.h>
#include <wtf/unicode/CharacterNames.h>
namespace WebCore {
using namespace JSC;
static inline String stringToByteString(ExecState& state, JSC::ThrowScope& scope, String&& string)
{
if (!string.isAllLatin1()) {
throwTypeError(&state, scope);
return { };
}
return WTFMove(string);
}
String identifierToByteString(ExecState& state, const Identifier& identifier)
{
VM& vm = state.vm();
auto scope = DECLARE_THROW_SCOPE(vm);
auto string = identifier.string();
return stringToByteString(state, scope, WTFMove(string));
}
String valueToByteString(ExecState& state, JSValue value)
{
VM& vm = state.vm();
auto scope = DECLARE_THROW_SCOPE(vm);
auto string = value.toWTFString(&state);
RETURN_IF_EXCEPTION(scope, { });
return stringToByteString(state, scope, WTFMove(string));
}
static inline bool hasUnpairedSurrogate(StringView string)
{
if (string.is8Bit())
return false;
for (auto codePoint : string.codePoints()) {
if (U_IS_SURROGATE(codePoint))
return true;
}
return false;
}
static inline String stringToUSVString(String&& string)
{
if (!hasUnpairedSurrogate(string))
return WTFMove(string);
StringBuilder result;
result.reserveCapacity(string.length());
StringView view { string };
for (auto codePoint : view.codePoints()) {
if (U_IS_SURROGATE(codePoint))
result.append(replacementCharacter);
else
result.append(codePoint);
}
return result.toString();
}
String identifierToUSVString(ExecState&, const Identifier& identifier)
{
auto string = identifier.string();
return stringToUSVString(WTFMove(string));
}
String valueToUSVString(ExecState& state, JSValue value)
{
VM& vm = state.vm();
auto scope = DECLARE_THROW_SCOPE(vm);
auto string = value.toWTFString(&state);
RETURN_IF_EXCEPTION(scope, { });
return stringToUSVString(WTFMove(string));
}
}