AK: Use an enum instead of a bool for String::replace(all_occurences)

This commit has no behavior changes.

In particular, this does not fix any of the wrong uses of the previous
default parameter (which used to be 'false', meaning "only replace the
first occurence in the string"). It simply replaces the default uses by
String::replace(..., ReplaceMode::FirstOnly), leaving them incorrect.
This commit is contained in:
DexesTTP 2022-07-05 22:33:15 +02:00 committed by Linus Groh
parent b2454888e8
commit 7ceeb74535
Notes: sideshowbarker 2024-07-17 09:40:48 +09:00
47 changed files with 108 additions and 102 deletions

View file

@ -291,7 +291,7 @@ public:
return { characters(), length() };
}
[[nodiscard]] String replace(StringView needle, StringView replacement, bool all_occurrences = false) const { return StringUtils::replace(*this, needle, replacement, all_occurrences); }
[[nodiscard]] String replace(StringView needle, StringView replacement, ReplaceMode replace_mode) const { return StringUtils::replace(*this, needle, replacement, replace_mode); }
[[nodiscard]] size_t count(StringView needle) const { return StringUtils::count(*this, needle); }
[[nodiscard]] String reverse() const;

View file

@ -476,13 +476,13 @@ String invert_case(StringView str)
return builder.to_string();
}
String replace(StringView str, StringView needle, StringView replacement, bool all_occurrences)
String replace(StringView str, StringView needle, StringView replacement, ReplaceMode replace_mode)
{
if (str.is_empty())
return str;
Vector<size_t> positions;
if (all_occurrences) {
if (replace_mode == ReplaceMode::All) {
positions = str.find_all(needle);
if (!positions.size())
return str;

View file

@ -22,6 +22,11 @@ enum class CaseSensitivity {
CaseSensitive,
};
enum class ReplaceMode {
All,
FirstOnly,
};
enum class TrimMode {
Left,
Right,
@ -80,7 +85,7 @@ String to_snakecase(StringView);
String to_titlecase(StringView);
String invert_case(StringView);
String replace(StringView, StringView needle, StringView replacement, bool all_occurrences = false);
String replace(StringView, StringView needle, StringView replacement, ReplaceMode);
size_t count(StringView, StringView needle);
}
@ -88,5 +93,6 @@ size_t count(StringView, StringView needle);
}
using AK::CaseSensitivity;
using AK::ReplaceMode;
using AK::TrimMode;
using AK::TrimWhitespace;

View file

@ -228,9 +228,9 @@ bool StringView::operator==(String const& string) const
String StringView::to_string() const { return String { *this }; }
String StringView::replace(StringView needle, StringView replacement, bool all_occurrences) const
String StringView::replace(StringView needle, StringView replacement, ReplaceMode replace_mode) const
{
return StringUtils::replace(*this, needle, replacement, all_occurrences);
return StringUtils::replace(*this, needle, replacement, replace_mode);
}
#endif

View file

@ -268,7 +268,7 @@ public:
}
#ifndef KERNEL
[[nodiscard]] String replace(StringView needle, StringView replacement, bool all_occurrences = false) const;
[[nodiscard]] String replace(StringView needle, StringView replacement, ReplaceMode) const;
#endif
[[nodiscard]] size_t count(StringView needle) const
{

View file

@ -245,7 +245,7 @@ URL URLParser::parse(StringView raw_input, URL const* base_url, Optional<URL> ur
// NOTE: This replaces all tab and newline characters with nothing.
if (processed_input.contains("\t") || processed_input.contains("\n")) {
report_validation_error();
processed_input = processed_input.replace("\t", "", true).replace("\n", "", true);
processed_input = processed_input.replace("\t", "", ReplaceMode::All).replace("\n", "", ReplaceMode::All);
}
State state = state_override.value_or(State::SchemeStart);

View file

@ -211,7 +211,7 @@ static void parse_dst_rule(StringView segment, TimeZoneOffset& time_zone)
static void parse_format(StringView format, TimeZoneData& time_zone_data, TimeZoneOffset& time_zone)
{
auto formats = format.replace("%s"sv, "{}"sv).split('/');
auto formats = format.replace("%s"sv, "{}"sv, ReplaceMode::FirstOnly).split('/');
VERIFY(formats.size() <= 2);
time_zone.standard_format = time_zone_data.unique_strings.ensure(formats[0]);
@ -422,8 +422,8 @@ static String format_identifier(StringView owner, String identifier)
}
}
identifier = identifier.replace("-"sv, "_"sv, true);
identifier = identifier.replace("/"sv, "_"sv, true);
identifier = identifier.replace("-"sv, "_"sv, ReplaceMode::All);
identifier = identifier.replace("/"sv, "_"sv, ReplaceMode::All);
if (all_of(identifier, is_ascii_digit))
return String::formatted("{}_{}", owner[0], identifier);
@ -690,7 +690,7 @@ Optional<Array<NamedOffset, 2>> get_named_time_zone_offsets(TimeZone time_zone,
auto format_name = [](auto format, auto offset) -> String {
if (offset == 0)
return s_string_list[format].replace("{}"sv, ""sv);
return s_string_list[format].replace("{}"sv, ""sv, ReplaceMode::FirstOnly);
return String::formatted(s_string_list[format], s_string_list[offset]);
};

View file

@ -146,8 +146,8 @@ struct UnicodeData {
static String sanitize_entry(String const& entry)
{
auto sanitized = entry.replace("-", "_", true);
sanitized = sanitized.replace(" ", "_", true);
auto sanitized = entry.replace("-", "_", ReplaceMode::All);
sanitized = sanitized.replace(" ", "_", ReplaceMode::All);
StringBuilder builder;
bool next_is_upper = true;
@ -229,7 +229,7 @@ static ErrorOr<void> parse_special_casing(Core::Stream::BufferedFile& file, Unic
if (!casing.locale.is_empty())
casing.locale = String::formatted("{:c}{}", to_ascii_uppercase(casing.locale[0]), casing.locale.substring_view(1));
casing.condition = casing.condition.replace("_", "", true);
casing.condition = casing.condition.replace("_", "", ReplaceMode::All);
if (!casing.condition.is_empty() && !unicode_data.conditions.contains_slow(casing.condition))
unicode_data.conditions.append(casing.condition);

View file

@ -1088,14 +1088,14 @@ static void generate_missing_patterns(Calendar& calendar, CalendarPatternList& f
auto time_pattern = locale_data.unique_strings.get(time_format);
auto date_pattern = locale_data.unique_strings.get(date_format);
auto new_pattern = pattern.replace("{0}", time_pattern).replace("{1}", date_pattern);
auto new_pattern = pattern.replace("{0}", time_pattern, ReplaceMode::FirstOnly).replace("{1}", date_pattern, ReplaceMode::FirstOnly);
return locale_data.unique_strings.ensure(move(new_pattern));
};
auto inject_fractional_second_digits = [&](auto format) {
auto pattern = locale_data.unique_strings.get(format);
auto new_pattern = pattern.replace("{second}"sv, "{second}{decimal}{fractionalSecondDigits}"sv);
auto new_pattern = pattern.replace("{second}"sv, "{second}{decimal}{fractionalSecondDigits}"sv, ReplaceMode::FirstOnly);
return locale_data.unique_strings.ensure(move(new_pattern));
};
@ -1606,8 +1606,8 @@ static ErrorOr<void> parse_all_locales(String core_path, String dates_path, Unic
static String format_identifier(StringView owner, String identifier)
{
identifier = identifier.replace("-"sv, "_"sv, true);
identifier = identifier.replace("/"sv, "_"sv, true);
identifier = identifier.replace("-"sv, "_"sv, ReplaceMode::All);
identifier = identifier.replace("/"sv, "_"sv, ReplaceMode::All);
if (all_of(identifier, is_ascii_digit))
return String::formatted("{}_{}", owner[0], identifier);

View file

@ -57,7 +57,7 @@ constexpr auto s_list_pattern_list_index_type = "u8"sv;
static String format_identifier(StringView owner, String identifier)
{
identifier = identifier.replace("-"sv, "_"sv, true);
identifier = identifier.replace("-"sv, "_"sv, ReplaceMode::All);
if (all_of(identifier, is_ascii_digit))
return String::formatted("{}_{}", owner[0], identifier);

View file

@ -340,7 +340,7 @@ static String parse_identifiers(String pattern, StringView replacement, UnicodeL
utf8_pattern = utf8_pattern.substring_view(*start_index, *end_index - *start_index);
utf8_pattern = utf8_pattern.trim(whitespace);
auto identifier = utf8_pattern.as_string().replace("'.'"sv, "."sv);
auto identifier = utf8_pattern.as_string().replace("'.'"sv, "."sv, ReplaceMode::FirstOnly);
auto identifier_index = locale_data.unique_strings.ensure(move(identifier));
size_t replacement_index = 0;
@ -379,7 +379,7 @@ static void parse_number_pattern(Vector<String> patterns, UnicodeLocaleData& loc
};
for (auto const& replacement : replacements)
pattern = pattern.replace(replacement.key, replacement.value, true);
pattern = pattern.replace(replacement.key, replacement.value, ReplaceMode::All);
if (auto start_number_index = pattern.find_any_of("#0"sv, String::SearchDirection::Forward); start_number_index.has_value()) {
auto end_number_index = *start_number_index + 1;
@ -415,7 +415,7 @@ static void parse_number_pattern(Vector<String> patterns, UnicodeLocaleData& loc
// This is specifically handled here rather than in the replacements HashMap above so
// that we do not errantly replace zeroes in number patterns.
if (pattern.contains(*replacements.get("E"sv)))
pattern = pattern.replace("0"sv, "{scientificExponent}"sv);
pattern = pattern.replace("0"sv, "{scientificExponent}"sv, ReplaceMode::FirstOnly);
}
if (type == NumberFormatType::Compact)
@ -677,11 +677,11 @@ static ErrorOr<void> parse_units(String locale_units_path, UnicodeLocaleData& lo
auto plurality = unit_key.substring_view(unit_pattern_prefix.length());
format.plurality = NumberFormat::plurality_from_string(plurality);
auto zero_format = pattern_value.as_string().replace("{0}"sv, "{number}"sv);
auto zero_format = pattern_value.as_string().replace("{0}"sv, "{number}"sv, ReplaceMode::FirstOnly);
zero_format = parse_identifiers(zero_format, "unitIdentifier"sv, locale_data, format);
format.positive_format_index = locale_data.unique_strings.ensure(zero_format.replace("{number}"sv, "{plusSign}{number}"sv));
format.negative_format_index = locale_data.unique_strings.ensure(zero_format.replace("{number}"sv, "{minusSign}{number}"sv));
format.positive_format_index = locale_data.unique_strings.ensure(zero_format.replace("{number}"sv, "{plusSign}{number}"sv, ReplaceMode::FirstOnly));
format.negative_format_index = locale_data.unique_strings.ensure(zero_format.replace("{number}"sv, "{minusSign}{number}"sv, ReplaceMode::FirstOnly));
format.zero_format_index = locale_data.unique_strings.ensure(move(zero_format));
formats.append(locale_data.unique_formats.ensure(move(format)));

View file

@ -464,7 +464,7 @@ void generate_mapping(SourceGenerator& generator, LocalesType const& locales, St
String mapping_name;
if constexpr (IsNullPointer<IdentifierFormatter>)
mapping_name = name.replace("-"sv, "_"sv, true);
mapping_name = name.replace("-"sv, "_"sv, ReplaceMode::All);
else
mapping_name = format_identifier(type, name);

View file

@ -51,7 +51,7 @@ String camel_casify(StringView dashy_name)
String snake_casify(String const& dashy_name)
{
return dashy_name.replace("-", "_", true);
return dashy_name.replace("-", "_", ReplaceMode::All);
}
ErrorOr<JsonValue> read_entire_file_as_json(StringView filename)

View file

@ -153,7 +153,7 @@ static String make_input_acceptable_cpp(String const& input)
return builder.to_string();
}
return input.replace("-", "_");
return input.replace("-", "_", ReplaceMode::FirstOnly);
}
static void generate_include_for_wrapper(auto& generator, auto& wrapper_name)
@ -237,7 +237,7 @@ static void emit_includes_for_all_imports(auto& interface, auto& generator, bool
if (is_iterator) {
auto iterator_name = String::formatted("{}Iterator", interface->name);
auto iterator_path = String::formatted("{}Iterator", interface->fully_qualified_name.replace("::", "/"));
auto iterator_path = String::formatted("{}Iterator", interface->fully_qualified_name.replace("::", "/", ReplaceMode::FirstOnly));
generate_include_for_iterator(generator, iterator_path, iterator_name);
}
@ -3635,7 +3635,7 @@ void generate_iterator_prototype_implementation(IDL::Interface const& interface)
generator.set("prototype_class", String::formatted("{}IteratorPrototype", interface.name));
generator.set("wrapper_class", String::formatted("{}IteratorWrapper", interface.name));
generator.set("fully_qualified_name", String::formatted("{}Iterator", interface.fully_qualified_name));
generator.set("possible_include_path", String::formatted("{}Iterator", interface.name.replace("::", "/")));
generator.set("possible_include_path", String::formatted("{}Iterator", interface.name.replace("::", "/", ReplaceMode::FirstOnly)));
generator.append(R"~~~(
#include <AK/Function.h>

View file

@ -166,20 +166,20 @@ TEST_CASE(replace)
{
String test_string = "Well, hello Friends!";
test_string = test_string.replace("Friends", "Testers");
test_string = test_string.replace("Friends", "Testers", ReplaceMode::FirstOnly);
EXPECT(test_string == "Well, hello Testers!");
test_string = test_string.replace("ell", "e're", true);
test_string = test_string.replace("ell", "e're", ReplaceMode::All);
EXPECT(test_string == "We're, he'reo Testers!");
test_string = test_string.replace("!", " :^)");
test_string = test_string.replace("!", " :^)", ReplaceMode::FirstOnly);
EXPECT(test_string == "We're, he'reo Testers :^)");
test_string = String("111._.111._.111");
test_string = test_string.replace("111", "|||", true);
test_string = test_string.replace("111", "|||", ReplaceMode::All);
EXPECT(test_string == "|||._.|||._.|||");
test_string = test_string.replace("|||", "111");
test_string = test_string.replace("|||", "111", ReplaceMode::FirstOnly);
EXPECT(test_string == "111._.|||._.|||");
}

View file

@ -43,7 +43,7 @@ namespace Browser {
URL url_from_user_input(String const& input)
{
if (input.starts_with("?") && !g_search_engine.is_empty())
return URL(g_search_engine.replace("{}", URL::percent_encode(input.substring_view(1))));
return URL(g_search_engine.replace("{}", URL::percent_encode(input.substring_view(1)), ReplaceMode::FirstOnly));
URL url_with_http_schema = URL(String::formatted("http://{}", input));
if (url_with_http_schema.is_valid() && url_with_http_schema.port().has_value())

View file

@ -79,7 +79,7 @@ Result<ByteBuffer, String> FindDialog::process_input(String text_value, OptionId
}
case OPTION_HEX_VALUE: {
auto decoded = decode_hex(text_value.replace(" ", "", true));
auto decoded = decode_hex(text_value.replace(" ", "", ReplaceMode::All));
if (decoded.is_error())
return String::formatted("Input is invalid: {}", decoded.error().string_literal());

View file

@ -128,7 +128,7 @@ GoToOffsetDialog::GoToOffsetDialog()
auto text = m_text_editor->text();
if (text.starts_with("0x")) {
m_offset_type_box->set_selected_index(1);
m_text_editor->set_text(text.replace("0x", ""));
m_text_editor->set_text(text.replace("0x", "", ReplaceMode::FirstOnly));
}
update_statusbar();
};

View file

@ -68,7 +68,7 @@ private:
while (iterator.has_next()) {
auto name = iterator.next_path();
auto basename = name.replace(".json", "");
auto basename = name.replace(".json", "", ReplaceMode::FirstOnly);
if (!selected_keymaps.find(basename).is_end())
continue;
m_character_map_files.append(basename);

View file

@ -189,7 +189,7 @@ static ErrorOr<NonnullRefPtr<GUI::Window>> create_find_window(VT::TerminalWidget
find_textbox->set_fixed_width(230);
find_textbox->set_focus(true);
if (terminal.has_selection())
find_textbox->set_text(terminal.selected_text().replace("\n", " ", true));
find_textbox->set_text(terminal.selected_text().replace("\n", " ", ReplaceMode::All));
auto find_backwards = TRY(find->try_add<GUI::Button>());
find_backwards->set_fixed_width(25);
find_backwards->set_icon(Gfx::Bitmap::try_load_from_file("/res/icons/16x16/upward-triangle.png").release_value_but_fixme_should_propagate_errors());

View file

@ -124,7 +124,7 @@ TerminalSettingsViewWidget::TerminalSettingsViewWidget()
Core::DirIterator iterator("/res/terminal-colors", Core::DirIterator::SkipParentAndBaseDir);
while (iterator.has_next()) {
auto path = iterator.next_path();
color_scheme_names.append(path.replace(".ini", ""));
color_scheme_names.append(path.replace(".ini", "", ReplaceMode::FirstOnly));
}
quick_sort(color_scheme_names);
auto& color_scheme_combo = *find_descendant_of_type_named<GUI::ComboBox>("color_scheme_combo");

View file

@ -94,7 +94,7 @@ Result<void, String> ProjectTemplate::create_project(String const& name, String
dbgln("Running post-create script '{}'", postcreate_script_path);
// Generate a namespace-safe project name (replace hyphens with underscores)
auto namespace_safe = name.replace("-", "_", true);
auto namespace_safe = name.replace("-", "_", ReplaceMode::All);
pid_t child_pid;
char const* argv[] = { postcreate_script_path.characters(), name.characters(), path.characters(), namespace_safe.characters(), nullptr };

View file

@ -27,7 +27,7 @@ public:
public:
SourceFile(StringView filename)
{
String source_file_name = filename.replace("../../", source_root_path);
String source_file_name = filename.replace("../../", source_root_path, ReplaceMode::FirstOnly);
auto maybe_file = Core::File::open(source_file_name, Core::OpenMode::ReadOnly);
if (maybe_file.is_error()) {

View file

@ -451,7 +451,7 @@ void endservent()
static bool fill_getserv_buffers(char const* line, ssize_t read)
{
// Splitting the line by tab delimiter and filling the servent buffers name, port, and protocol members.
auto split_line = StringView(line, read).replace(" ", "\t", true).split('\t');
auto split_line = StringView(line, read).replace(" ", "\t", ReplaceMode::All).split('\t');
// This indicates an incorrect file format.
// Services file entries should always at least contain
@ -474,7 +474,7 @@ static bool fill_getserv_buffers(char const* line, ssize_t read)
__getserv_port_buffer = number.value();
// Remove any annoying whitespace at the end of the protocol.
__getserv_protocol_buffer = port_protocol_split[1].replace(" ", "", true).replace("\t", "", true).replace("\n", "", true);
__getserv_protocol_buffer = port_protocol_split[1].replace(" ", "", ReplaceMode::All).replace("\t", "", ReplaceMode::All).replace("\n", "", ReplaceMode::All);
__getserv_alias_list_buffer.clear();
// If there are aliases for the service, we will fill the alias list buffer.
@ -630,7 +630,7 @@ void endprotoent()
static bool fill_getproto_buffers(char const* line, ssize_t read)
{
String string_line = String(line, read);
auto split_line = string_line.replace(" ", "\t", true).split('\t');
auto split_line = string_line.replace(" ", "\t", ReplaceMode::All).split('\t');
// This indicates an incorrect file format. Protocols file entries should
// always have at least a name and a protocol.

View file

@ -114,7 +114,7 @@ int __attribute__((weak)) tgetnum(char const* id)
static Vector<char> s_tgoto_buffer;
char* __attribute__((weak)) tgoto([[maybe_unused]] char const* cap, [[maybe_unused]] int col, [[maybe_unused]] int row)
{
auto cap_str = StringView(cap).replace("%p1%d", String::number(col)).replace("%p2%d", String::number(row));
auto cap_str = StringView(cap).replace("%p1%d", String::number(col), ReplaceMode::FirstOnly).replace("%p2%d", String::number(row), ReplaceMode::FirstOnly);
s_tgoto_buffer.clear_with_capacity();
s_tgoto_buffer.ensure_capacity(cap_str.length());

View file

@ -126,7 +126,7 @@ static Optional<String> resolve_library(String const& name, DynamicObject const&
search_paths.append("/usr/local/lib"sv);
for (auto const& search_path : search_paths) {
LexicalPath library_path(search_path.replace("$ORIGIN"sv, LexicalPath::dirname(parent_object.filepath())));
LexicalPath library_path(search_path.replace("$ORIGIN"sv, LexicalPath::dirname(parent_object.filepath()), ReplaceMode::FirstOnly));
String library_name = library_path.append(name).string();
if (access(library_name.characters(), F_OK) == 0)

View file

@ -128,7 +128,7 @@ String serialize_astring(StringView string)
// Try to quote
auto can_be_quoted = !(string.contains('\n') || string.contains('\r'));
if (can_be_quoted) {
auto escaped_str = string.replace("\\", "\\\\").replace("\"", "\\\"");
auto escaped_str = string.replace("\\", "\\\\", ReplaceMode::FirstOnly).replace("\"", "\\\"", ReplaceMode::FirstOnly);
return String::formatted("\"{}\"", escaped_str);
}

View file

@ -182,7 +182,7 @@ public:
return {};
// We need to modify the source to match what the lexer considers one line - normalizing
// line terminators to \n is easier than splitting using all different LT characters.
String source_string = source.replace("\r\n", "\n").replace("\r", "\n").replace(LINE_SEPARATOR_STRING, "\n").replace(PARAGRAPH_SEPARATOR_STRING, "\n");
String source_string = source.replace("\r\n", "\n", ReplaceMode::FirstOnly).replace("\r", "\n", ReplaceMode::FirstOnly).replace(LINE_SEPARATOR_STRING, "\n", ReplaceMode::FirstOnly).replace(PARAGRAPH_SEPARATOR_STRING, "\n", ReplaceMode::FirstOnly);
StringBuilder builder;
builder.append(source_string.split_view('\n', true)[position.value().line - 1]);
builder.append('\n');

View file

@ -217,7 +217,7 @@ Optional<Unicode::CalendarPattern> date_time_style_format(StringView data_locale
return {};
// e. Let pattern be the string connector with the substring "{0}" replaced with timeFormat.[[pattern]] and the substring "{1}" replaced with dateFormat.[[pattern]].
auto pattern = connector->pattern.replace("{0}"sv, time_format.pattern).replace("{1}"sv, date_format.pattern);
auto pattern = connector->pattern.replace("{0}"sv, time_format.pattern, ReplaceMode::FirstOnly).replace("{1}"sv, date_format.pattern, ReplaceMode::FirstOnly);
// f. Set format.[[pattern]] to pattern.
format.pattern = move(pattern);
@ -225,7 +225,7 @@ Optional<Unicode::CalendarPattern> date_time_style_format(StringView data_locale
// g. If timeFormat has a [[pattern12]] field, then
if (time_format.pattern12.has_value()) {
// i. Let pattern12 be the string connector with the substring "{0}" replaced with timeFormat.[[pattern12]] and the substring "{1}" replaced with dateFormat.[[pattern]].
auto pattern12 = connector->pattern.replace("{0}"sv, *time_format.pattern12).replace("{1}"sv, date_format.pattern);
auto pattern12 = connector->pattern.replace("{0}"sv, *time_format.pattern12, ReplaceMode::FirstOnly).replace("{1}"sv, date_format.pattern, ReplaceMode::FirstOnly);
// ii. Set format.[[pattern12]] to pattern12.
format.pattern12 = move(pattern12);
@ -1075,11 +1075,11 @@ ThrowCompletionOr<Vector<PatternPartitionWithSource>> partition_date_time_range_
auto const& pattern = date_time_format.pattern();
if (range_pattern->start_range.contains("{0}"sv)) {
range_pattern->start_range = range_pattern->start_range.replace("{0}"sv, pattern);
range_pattern->end_range = range_pattern->end_range.replace("{1}"sv, pattern);
range_pattern->start_range = range_pattern->start_range.replace("{0}"sv, pattern, ReplaceMode::FirstOnly);
range_pattern->end_range = range_pattern->end_range.replace("{1}"sv, pattern, ReplaceMode::FirstOnly);
} else {
range_pattern->start_range = range_pattern->start_range.replace("{1}"sv, pattern);
range_pattern->end_range = range_pattern->end_range.replace("{0}"sv, pattern);
range_pattern->start_range = range_pattern->start_range.replace("{1}"sv, pattern, ReplaceMode::FirstOnly);
range_pattern->end_range = range_pattern->end_range.replace("{0}"sv, pattern, ReplaceMode::FirstOnly);
}
// FIXME: The above is not sufficient. For example, if the start date is days before the end date, and only the timeStyle

View file

@ -299,10 +299,10 @@ ThrowCompletionOr<DurationUnitOptions> get_duration_unit_options(GlobalObject& g
// here, but at some point we should split the the NumberFormat exporter to export both formats of the data.
static String convert_number_format_pattern_to_duration_format_template(Unicode::NumberFormat const& number_format)
{
auto result = number_format.zero_format.replace("{number}", "{0}");
auto result = number_format.zero_format.replace("{number}", "{0}", ReplaceMode::FirstOnly);
for (size_t i = 0; i < number_format.identifiers.size(); ++i)
result = result.replace(String::formatted("{{unitIdentifier:{}}}", i), number_format.identifiers[i]);
result = result.replace(String::formatted("{{unitIdentifier:{}}}", i), number_format.identifiers[i], ReplaceMode::FirstOnly);
return result;
}

View file

@ -182,7 +182,7 @@ String RegExpObject::escape_regexp_pattern() const
if (m_pattern.is_empty())
return "(?:)";
// FIXME: Check u flag and escape accordingly
return m_pattern.replace("\n", "\\n", true).replace("\r", "\\r", true).replace(LINE_SEPARATOR_STRING, "\\u2028", true).replace(PARAGRAPH_SEPARATOR_STRING, "\\u2029", true).replace("/", "\\/", true);
return m_pattern.replace("\n", "\\n", ReplaceMode::All).replace("\r", "\\r", ReplaceMode::All).replace(LINE_SEPARATOR_STRING, "\\u2028", ReplaceMode::All).replace(PARAGRAPH_SEPARATOR_STRING, "\\u2029", ReplaceMode::All).replace("/", "\\/", ReplaceMode::All);
}
// 22.2.3.2.4 RegExpCreate ( P, F ), https://tc39.es/ecma262/#sec-regexpcreate

View file

@ -970,7 +970,7 @@ static ThrowCompletionOr<Value> create_html(GlobalObject& global_object, Value s
builder.append(' ');
builder.append(attribute);
builder.append("=\"");
builder.append(value_string.replace("\"", "&quot;", true));
builder.append(value_string.replace("\"", "&quot;", ReplaceMode::All));
builder.append('"');
}
builder.append('>');

View file

@ -213,7 +213,7 @@ String Token::string_value(StringValueStatus& status) const
// 12.8.6.2 Static Semantics: TRV, https://tc39.es/ecma262/#sec-static-semantics-trv
String Token::raw_template_value() const
{
return value().replace("\r\n", "\n", true).replace("\r", "\n", true);
return value().replace("\r\n", "\n", ReplaceMode::All).replace("\r", "\n", ReplaceMode::All);
}
bool Token::bool_value() const

View file

@ -246,7 +246,7 @@ static Optional<String> format_time_zone_offset(StringView locale, CalendarPatte
// The digits used for hours, minutes and seconds fields in this format are the locale's default decimal digits.
auto result = replace_digits_for_number_system(*number_system, builder.build());
return formats->gmt_format.replace("{0}"sv, result);
return formats->gmt_format.replace("{0}"sv, result, ReplaceMode::FirstOnly);
}
// https://unicode.org/reports/tr35/tr35-dates.html#Time_Zone_Format_Terminology

View file

@ -816,7 +816,7 @@ Optional<String> format_locale_for_display(StringView locale, LocaleID locale_id
Optional<String> secondary_tag;
if (script.has_value() && region.has_value())
secondary_tag = patterns->locale_separator.replace("{0}"sv, *script).replace("{1}"sv, *region);
secondary_tag = patterns->locale_separator.replace("{0}"sv, *script, ReplaceMode::FirstOnly).replace("{1}"sv, *region, ReplaceMode::FirstOnly);
else if (script.has_value())
secondary_tag = *script;
else if (region.has_value())
@ -825,7 +825,7 @@ Optional<String> format_locale_for_display(StringView locale, LocaleID locale_id
if (!secondary_tag.has_value())
return primary_tag;
return patterns->locale_pattern.replace("{0}"sv, primary_tag).replace("{1}"sv, *secondary_tag);
return patterns->locale_pattern.replace("{0}"sv, primary_tag, ReplaceMode::FirstOnly).replace("{1}"sv, *secondary_tag, ReplaceMode::FirstOnly);
}
Optional<ListPatterns> __attribute__((weak)) get_locale_list_patterns(StringView, StringView, Style) { return {}; }

View file

@ -105,7 +105,7 @@ Optional<String> augment_currency_format_pattern([[maybe_unused]] StringView cur
}
if (currency_key_with_spacing.has_value())
return base_pattern.replace(currency_key, *currency_key_with_spacing);
return base_pattern.replace(currency_key, *currency_key_with_spacing, ReplaceMode::FirstOnly);
#endif
return {};

View file

@ -2883,7 +2883,7 @@ Optional<UnicodeRange> Parser::parse_unicode_range(StringView text)
// 2. Interpret the consumed code points as a hexadecimal number,
// with the U+003F QUESTION MARK (?) code points replaced by U+0030 DIGIT ZERO (0) code points.
// This is the start value.
auto start_value_string = start_value_code_points.replace("?", "0", true);
auto start_value_string = start_value_code_points.replace("?", "0", ReplaceMode::All);
auto maybe_start_value = AK::StringUtils::convert_to_uint_from_hex<u32>(start_value_string);
if (!maybe_start_value.has_value()) {
dbgln_if(CSS_PARSER_DEBUG, "CSSParser: <urange> ?-converted start value did not parse as hex number.");
@ -2894,7 +2894,7 @@ Optional<UnicodeRange> Parser::parse_unicode_range(StringView text)
// 3. Interpret the consumed code points as a hexadecimal number again,
// with the U+003F QUESTION MARK (?) code points replaced by U+0046 LATIN CAPITAL LETTER F (F) code points.
// This is the end value.
auto end_value_string = start_value_code_points.replace("?", "F", true);
auto end_value_string = start_value_code_points.replace("?", "F", ReplaceMode::All);
auto maybe_end_value = AK::StringUtils::convert_to_uint_from_hex<u32>(end_value_string);
if (!maybe_end_value.has_value()) {
dbgln_if(CSS_PARSER_DEBUG, "CSSParser: <urange> ?-converted end value did not parse as hex number.");

View file

@ -276,16 +276,16 @@ static DOM::ExceptionOr<String> serialize_an_attribute_value(String const& attri
auto final_attribute_value = attribute_value;
// 1. "&" with "&amp;"
final_attribute_value = final_attribute_value.replace("&"sv, "&amp;"sv, true);
final_attribute_value = final_attribute_value.replace("&"sv, "&amp;"sv, ReplaceMode::All);
// 2. """ with "&quot;"
final_attribute_value = final_attribute_value.replace("\""sv, "&quot;"sv, true);
final_attribute_value = final_attribute_value.replace("\""sv, "&quot;"sv, ReplaceMode::All);
// 3. "<" with "&lt;"
final_attribute_value = final_attribute_value.replace("<"sv, "&lt;"sv, true);
final_attribute_value = final_attribute_value.replace("<"sv, "&lt;"sv, ReplaceMode::All);
// 4. ">" with "&gt;"
final_attribute_value = final_attribute_value.replace(">"sv, "&gt;"sv, true);
final_attribute_value = final_attribute_value.replace(">"sv, "&gt;"sv, ReplaceMode::All);
return final_attribute_value;
}
@ -736,13 +736,13 @@ static DOM::ExceptionOr<String> serialize_text(DOM::Text const& text, [[maybe_un
String markup = text.data();
// 3. Replace any occurrences of "&" in markup by "&amp;".
markup = markup.replace("&"sv, "&amp;"sv, true);
markup = markup.replace("&"sv, "&amp;"sv, ReplaceMode::All);
// 4. Replace any occurrences of "<" in markup by "&lt;".
markup = markup.replace("<"sv, "&lt;"sv, true);
markup = markup.replace("<"sv, "&lt;"sv, ReplaceMode::All);
// 5. Replace any occurrences of ">" in markup by "&gt;".
markup = markup.replace(">"sv, "&gt;"sv, true);
markup = markup.replace(">"sv, "&gt;"sv, ReplaceMode::All);
// 6. Return the value of markup.
return markup;

View file

@ -54,7 +54,7 @@ Vector<QueryParam> url_decode(StringView input)
}
// 4. Replace any 0x2B (+) in name and value with 0x20 (SP).
auto space_decoded_name = name.replace("+"sv, " "sv, true);
auto space_decoded_name = name.replace("+"sv, " "sv, ReplaceMode::All);
// 5. Let nameString and valueString be the result of running UTF-8 decode without BOM on the percent-decoding of name and value, respectively.
auto name_string = AK::URL::percent_decode(space_decoded_name);

View file

@ -150,7 +150,7 @@ private:
[this, position = m_lexer.tell(), location] {
m_lexer.retreat(m_lexer.tell() - position);
(void)location;
dbgln_if(XML_PARSER_DEBUG, "{:->{}}FAIL @ {} -- \x1b[31m{}\x1b[0m", " ", s_debug_indent_level * 2, location, m_lexer.remaining().substring_view(0, min(16, m_lexer.tell_remaining())).replace("\n", "\\n", true));
dbgln_if(XML_PARSER_DEBUG, "{:->{}}FAIL @ {} -- \x1b[31m{}\x1b[0m", " ", s_debug_indent_level * 2, location, m_lexer.remaining().substring_view(0, min(16, m_lexer.tell_remaining())).replace("\n", "\\n", ReplaceMode::All));
}
};
}

View file

@ -95,7 +95,7 @@ void LookupServer::load_etc_hosts()
if (original_line.is_empty())
break;
auto trimmed_line = original_line.view().trim_whitespace();
auto replaced_line = trimmed_line.replace(" ", "\t", true);
auto replaced_line = trimmed_line.replace(" ", "\t", ReplaceMode::All);
auto fields = replaced_line.split_view('\t', false);
if (fields.size() < 2) {

View file

@ -137,7 +137,7 @@ OwnPtr<QuickLaunchEntry> QuickLaunchEntry::create_from_path(StringView path)
static String sanitize_entry_name(String const& name)
{
return name.replace(" ", "", true).replace("=", "", true);
return name.replace(" ", "", ReplaceMode::All).replace("=", "", ReplaceMode::All);
}
void QuickLaunchWidget::add_or_adjust_button(String const& button_name, NonnullOwnPtr<QuickLaunchEntry>&& entry)

View file

@ -1183,7 +1183,7 @@ void Window::set_modified(bool modified)
String Window::computed_title() const
{
String title = m_title.replace("[*]", is_modified() ? " (*)" : "");
String title = m_title.replace("[*]", is_modified() ? " (*)" : "", ReplaceMode::FirstOnly);
if (client() && client()->is_unresponsive())
return String::formatted("{} (Not responding)", title);
return title;

View file

@ -105,7 +105,7 @@ ErrorOr<int> serenity_main(Main::Arguments arguments)
if (pager)
pager_command = pager;
else
pager_command = String::formatted("less -P 'Manual Page {}({}) line %l?e (END):.'", StringView(name).replace("'", "'\\''"), StringView(section).replace("'", "'\\''"));
pager_command = String::formatted("less -P 'Manual Page {}({}) line %l?e (END):.'", StringView(name).replace("'", "'\\''", ReplaceMode::FirstOnly), StringView(section).replace("'", "'\\''", ReplaceMode::FirstOnly));
pid_t pager_pid = TRY(pipe_to_pager(pager_command));
auto file = TRY(Core::File::open(filename, Core::OpenMode::ReadOnly));

View file

@ -143,24 +143,24 @@ static String slugify(String const& text)
String slug = text.to_lowercase();
// Reverse-engineered through github, using:
// find AK/ Base/ Documentation/ Kernel/ Meta/ Ports/ Tests/ Userland/ -name '*.md' | xargs grep --color=always -Pin '^##+ .*[^a-z0-9 ?()`_:/!&|.$'"'"',<>"+-]' README.md
slug = slug.replace(" ", "-", true)
.replace("!", "", true)
.replace("?", "", true)
.replace("(", "", true)
.replace(")", "", true)
.replace(":", "", true)
.replace("/", "-", true)
.replace("&", "", true)
.replace("|", "", true)
.replace(".", "", true)
.replace("$", "", true)
.replace("'", "", true)
.replace(",", "", true)
.replace("\"", "", true)
.replace("+", "", true)
.replace("\\", "", true)
.replace("<", "", true)
.replace(">", "", true);
slug = slug.replace(" ", "-", ReplaceMode::All)
.replace("!", "", ReplaceMode::All)
.replace("?", "", ReplaceMode::All)
.replace("(", "", ReplaceMode::All)
.replace(")", "", ReplaceMode::All)
.replace(":", "", ReplaceMode::All)
.replace("/", "-", ReplaceMode::All)
.replace("&", "", ReplaceMode::All)
.replace("|", "", ReplaceMode::All)
.replace(".", "", ReplaceMode::All)
.replace("$", "", ReplaceMode::All)
.replace("'", "", ReplaceMode::All)
.replace(",", "", ReplaceMode::All)
.replace("\"", "", ReplaceMode::All)
.replace("+", "", ReplaceMode::All)
.replace("\\", "", ReplaceMode::All)
.replace("<", "", ReplaceMode::All)
.replace(">", "", ReplaceMode::All);
// What about "="?
return slug;
}

View file

@ -122,7 +122,7 @@ ErrorOr<int> serenity_main(Main::Arguments arguments)
if (!file_filters.is_empty()) {
for (auto& filter : file_filters) {
// Convert underscore wildcards (usual unzip convention) to question marks (as used by StringUtils)
auto string_filter = filter.replace("_", "?", true);
auto string_filter = filter.replace("_", "?", ReplaceMode::All);
if (zip_member.name.matches(string_filter, CaseSensitivity::CaseSensitive)) {
keep_file = true;
break;

View file

@ -18,7 +18,7 @@ ErrorOr<int> serenity_main(Main::Arguments)
auto cpp_full_path = parser_tests.next_full_path();
if (!cpp_full_path.ends_with(".cpp"))
continue;
auto ast_full_path = cpp_full_path.replace(".cpp", ".ast");
auto ast_full_path = cpp_full_path.replace(".cpp", ".ast", ReplaceMode::FirstOnly);
outln("{}", cpp_full_path);
auto res = Core::command("/bin/sh", { "-c", String::formatted("cpp-parser {} > {}", cpp_full_path, ast_full_path) }, {});
VERIFY(!res.is_error());
@ -29,7 +29,7 @@ ErrorOr<int> serenity_main(Main::Arguments)
auto cpp_full_path = preprocessor_tests.next_full_path();
if (!cpp_full_path.ends_with(".cpp"))
continue;
auto ast_full_path = cpp_full_path.replace(".cpp", ".txt");
auto ast_full_path = cpp_full_path.replace(".cpp", ".txt", ReplaceMode::FirstOnly);
outln("{}", cpp_full_path);
auto res = Core::command("/bin/sh", { "-c", String::formatted("cpp-preprocessor {} > {}", cpp_full_path, ast_full_path) }, {});
VERIFY(!res.is_error());