2020-03-11 18:55:01 +01:00
|
|
|
/*
|
|
|
|
* Copyright (c) 2020, Andreas Kling <kling@serenityos.org>
|
|
|
|
*
|
2021-04-22 01:24:48 -07:00
|
|
|
* SPDX-License-Identifier: BSD-2-Clause
|
2020-03-11 18:55:01 +01:00
|
|
|
*/
|
|
|
|
|
2021-07-20 10:46:53 -04:00
|
|
|
#include <AK/CharacterTypes.h>
|
|
|
|
#include <AK/Utf16View.h>
|
2020-03-16 14:20:30 +01:00
|
|
|
#include <LibJS/Runtime/PrimitiveString.h>
|
2020-09-27 20:03:42 +02:00
|
|
|
#include <LibJS/Runtime/VM.h>
|
2020-03-11 18:55:01 +01:00
|
|
|
|
|
|
|
namespace JS {
|
|
|
|
|
|
|
|
PrimitiveString::PrimitiveString(String string)
|
|
|
|
: m_string(move(string))
|
|
|
|
{
|
|
|
|
}
|
|
|
|
|
|
|
|
PrimitiveString::~PrimitiveString()
|
|
|
|
{
|
|
|
|
}
|
|
|
|
|
2021-07-20 10:46:53 -04:00
|
|
|
Vector<u16> const& PrimitiveString::utf16_string() const
|
|
|
|
{
|
|
|
|
if (m_utf16_string.is_empty() && !m_string.is_empty())
|
|
|
|
m_utf16_string = AK::utf8_to_utf16(m_string);
|
|
|
|
return m_utf16_string;
|
|
|
|
}
|
|
|
|
|
|
|
|
Utf16View PrimitiveString::utf16_string_view() const
|
|
|
|
{
|
|
|
|
return Utf16View { utf16_string() };
|
|
|
|
}
|
|
|
|
|
|
|
|
PrimitiveString* js_string(Heap& heap, Utf16View const& string)
|
|
|
|
{
|
|
|
|
if (string.is_empty())
|
|
|
|
return &heap.vm().empty_string();
|
|
|
|
|
|
|
|
if (string.length_in_code_units() == 1) {
|
|
|
|
u16 code_unit = string.code_unit_at(0);
|
|
|
|
if (is_ascii(code_unit))
|
|
|
|
return &heap.vm().single_ascii_character_string(static_cast<u8>(code_unit));
|
|
|
|
}
|
|
|
|
|
|
|
|
auto utf8_string = string.to_utf8(Utf16View::AllowInvalidCodeUnits::Yes);
|
|
|
|
return heap.allocate_without_global_object<PrimitiveString>(move(utf8_string));
|
|
|
|
}
|
|
|
|
|
|
|
|
PrimitiveString* js_string(VM& vm, Utf16View const& string)
|
|
|
|
{
|
|
|
|
return js_string(vm.heap(), string);
|
|
|
|
}
|
|
|
|
|
2020-03-11 18:55:01 +01:00
|
|
|
PrimitiveString* js_string(Heap& heap, String string)
|
|
|
|
{
|
2020-09-22 16:36:33 +02:00
|
|
|
if (string.is_empty())
|
|
|
|
return &heap.vm().empty_string();
|
2020-10-22 17:43:48 +02:00
|
|
|
|
2021-07-20 10:46:53 -04:00
|
|
|
if (string.length() == 1) {
|
|
|
|
auto ch = static_cast<u8>(string.characters()[0]);
|
|
|
|
if (is_ascii(ch))
|
|
|
|
return &heap.vm().single_ascii_character_string(ch);
|
|
|
|
}
|
|
|
|
|
2020-07-24 20:46:55 +02:00
|
|
|
return heap.allocate_without_global_object<PrimitiveString>(move(string));
|
2020-03-11 18:55:01 +01:00
|
|
|
}
|
|
|
|
|
2020-09-27 18:36:49 +02:00
|
|
|
PrimitiveString* js_string(VM& vm, String string)
|
|
|
|
{
|
|
|
|
return js_string(vm.heap(), move(string));
|
2020-04-04 12:57:37 +02:00
|
|
|
}
|
|
|
|
|
2020-03-11 18:55:01 +01:00
|
|
|
}
|