Everywhere: Split Error::from_string_literal and Error::from_string_view

Error::from_string_literal now takes direct char const*s, while
Error::from_string_view does what Error::from_string_literal used to do:
taking StringViews. This change will remove the need to insert `sv`
after error strings when returning string literal errors once
StringView(char const*) is removed.

No functional changes.
This commit is contained in:
sin-ack 2022-07-11 17:57:32 +00:00 committed by Andreas Kling
parent c70f45ff44
commit e5f09ea170
Notes: sideshowbarker 2024-07-17 09:27:09 +09:00
51 changed files with 282 additions and 261 deletions

View File

@ -24,7 +24,19 @@ class Error {
public: public:
static Error from_errno(int code) { return Error(code); } static Error from_errno(int code) { return Error(code); }
static Error from_syscall(StringView syscall_name, int rc) { return Error(syscall_name, rc); } static Error from_syscall(StringView syscall_name, int rc) { return Error(syscall_name, rc); }
static Error from_string_literal(StringView string_literal) { return Error(string_literal); } static Error from_string_view(StringView string_literal) { return Error(string_literal); }
// NOTE: Prefer `from_string_literal` when directly typing out an error message:
//
// return Error::from_string_literal("Class: Some failure");
//
// If you need to return a static string based on a dynamic condition (like
// picking an error from an array), then prefer `from_string_view` instead.
template<size_t N>
ALWAYS_INLINE static Error from_string_literal(char const (&string_literal)[N])
{
return from_string_view(StringView { string_literal, N - 1 });
}
bool operator==(Error const& other) const bool operator==(Error const& other) const
{ {

View File

@ -20,7 +20,7 @@ constexpr bool is_space(int ch)
ErrorOr<String> JsonParser::consume_and_unescape_string() ErrorOr<String> JsonParser::consume_and_unescape_string()
{ {
if (!consume_specific('"')) if (!consume_specific('"'))
return Error::from_string_literal("JsonParser: Expected '\"'"sv); return Error::from_string_literal("JsonParser: Expected '\"'");
StringBuilder final_sb; StringBuilder final_sb;
for (;;) { for (;;) {
@ -33,7 +33,7 @@ ErrorOr<String> JsonParser::consume_and_unescape_string()
if (ch == '"' || ch == '\\') if (ch == '"' || ch == '\\')
break; break;
if (is_ascii_c0_control(ch)) if (is_ascii_c0_control(ch))
return Error::from_string_literal("JsonParser: Error while parsing string"sv); return Error::from_string_literal("JsonParser: Error while parsing string");
++peek_index; ++peek_index;
} }
@ -102,20 +102,20 @@ ErrorOr<String> JsonParser::consume_and_unescape_string()
if (next_is('u')) { if (next_is('u')) {
ignore(); ignore();
if (tell_remaining() < 4) if (tell_remaining() < 4)
return Error::from_string_literal("JsonParser: EOF while parsing Unicode escape"sv); return Error::from_string_literal("JsonParser: EOF while parsing Unicode escape");
auto code_point = AK::StringUtils::convert_to_uint_from_hex(consume(4)); auto code_point = AK::StringUtils::convert_to_uint_from_hex(consume(4));
if (code_point.has_value()) { if (code_point.has_value()) {
final_sb.append_code_point(code_point.value()); final_sb.append_code_point(code_point.value());
continue; continue;
} }
return Error::from_string_literal("JsonParser: Error while parsing Unicode escape"sv); return Error::from_string_literal("JsonParser: Error while parsing Unicode escape");
} }
return Error::from_string_literal("JsonParser: Error while parsing string"sv); return Error::from_string_literal("JsonParser: Error while parsing string");
} }
if (!consume_specific('"')) if (!consume_specific('"'))
return Error::from_string_literal("JsonParser: Expected '\"'"sv); return Error::from_string_literal("JsonParser: Expected '\"'");
return final_sb.to_string(); return final_sb.to_string();
} }
@ -124,7 +124,7 @@ ErrorOr<JsonValue> JsonParser::parse_object()
{ {
JsonObject object; JsonObject object;
if (!consume_specific('{')) if (!consume_specific('{'))
return Error::from_string_literal("JsonParser: Expected '{'"sv); return Error::from_string_literal("JsonParser: Expected '{'");
for (;;) { for (;;) {
ignore_while(is_space); ignore_while(is_space);
if (peek() == '}') if (peek() == '}')
@ -132,10 +132,10 @@ ErrorOr<JsonValue> JsonParser::parse_object()
ignore_while(is_space); ignore_while(is_space);
auto name = TRY(consume_and_unescape_string()); auto name = TRY(consume_and_unescape_string());
if (name.is_null()) if (name.is_null())
return Error::from_string_literal("JsonParser: Expected object property name"sv); return Error::from_string_literal("JsonParser: Expected object property name");
ignore_while(is_space); ignore_while(is_space);
if (!consume_specific(':')) if (!consume_specific(':'))
return Error::from_string_literal("JsonParser: Expected ':'"sv); return Error::from_string_literal("JsonParser: Expected ':'");
ignore_while(is_space); ignore_while(is_space);
auto value = TRY(parse_helper()); auto value = TRY(parse_helper());
object.set(name, move(value)); object.set(name, move(value));
@ -143,13 +143,13 @@ ErrorOr<JsonValue> JsonParser::parse_object()
if (peek() == '}') if (peek() == '}')
break; break;
if (!consume_specific(',')) if (!consume_specific(','))
return Error::from_string_literal("JsonParser: Expected ','"sv); return Error::from_string_literal("JsonParser: Expected ','");
ignore_while(is_space); ignore_while(is_space);
if (peek() == '}') if (peek() == '}')
return Error::from_string_literal("JsonParser: Unexpected '}'"sv); return Error::from_string_literal("JsonParser: Unexpected '}'");
} }
if (!consume_specific('}')) if (!consume_specific('}'))
return Error::from_string_literal("JsonParser: Expected '}'"sv); return Error::from_string_literal("JsonParser: Expected '}'");
return JsonValue { move(object) }; return JsonValue { move(object) };
} }
@ -157,7 +157,7 @@ ErrorOr<JsonValue> JsonParser::parse_array()
{ {
JsonArray array; JsonArray array;
if (!consume_specific('[')) if (!consume_specific('['))
return Error::from_string_literal("JsonParser: Expected '['"sv); return Error::from_string_literal("JsonParser: Expected '['");
for (;;) { for (;;) {
ignore_while(is_space); ignore_while(is_space);
if (peek() == ']') if (peek() == ']')
@ -168,14 +168,14 @@ ErrorOr<JsonValue> JsonParser::parse_array()
if (peek() == ']') if (peek() == ']')
break; break;
if (!consume_specific(',')) if (!consume_specific(','))
return Error::from_string_literal("JsonParser: Expected ','"sv); return Error::from_string_literal("JsonParser: Expected ','");
ignore_while(is_space); ignore_while(is_space);
if (peek() == ']') if (peek() == ']')
return Error::from_string_literal("JsonParser: Unexpected ']'"sv); return Error::from_string_literal("JsonParser: Unexpected ']'");
} }
ignore_while(is_space); ignore_while(is_space);
if (!consume_specific(']')) if (!consume_specific(']'))
return Error::from_string_literal("JsonParser: Expected ']'"sv); return Error::from_string_literal("JsonParser: Expected ']'");
return JsonValue { move(array) }; return JsonValue { move(array) };
} }
@ -197,7 +197,7 @@ ErrorOr<JsonValue> JsonParser::parse_number()
char ch = peek(); char ch = peek();
if (ch == '.') { if (ch == '.') {
if (is_double) if (is_double)
return Error::from_string_literal("JsonParser: Multiple '.' in number"sv); return Error::from_string_literal("JsonParser: Multiple '.' in number");
is_double = true; is_double = true;
++m_index; ++m_index;
@ -209,18 +209,18 @@ ErrorOr<JsonValue> JsonParser::parse_number()
if (is_double) { if (is_double) {
if (ch == '-') if (ch == '-')
return Error::from_string_literal("JsonParser: Error while parsing number"sv); return Error::from_string_literal("JsonParser: Error while parsing number");
fraction_buffer.append(ch); fraction_buffer.append(ch);
} else { } else {
if (number_buffer.size() > 0) { if (number_buffer.size() > 0) {
if (number_buffer.at(0) == '0') if (number_buffer.at(0) == '0')
return Error::from_string_literal("JsonParser: Error while parsing number"sv); return Error::from_string_literal("JsonParser: Error while parsing number");
} }
if (number_buffer.size() > 1) { if (number_buffer.size() > 1) {
if (number_buffer.at(0) == '-' && number_buffer.at(1) == '0') if (number_buffer.at(0) == '-' && number_buffer.at(1) == '0')
return Error::from_string_literal("JsonParser: Error while parsing number"sv); return Error::from_string_literal("JsonParser: Error while parsing number");
} }
number_buffer.append(ch); number_buffer.append(ch);
@ -247,14 +247,14 @@ ErrorOr<JsonValue> JsonParser::parse_number()
} else { } else {
auto number = number_string.to_int(); auto number = number_string.to_int();
if (!number.has_value()) if (!number.has_value())
return Error::from_string_literal("JsonParser: Error while parsing number"sv); return Error::from_string_literal("JsonParser: Error while parsing number");
whole = number.value(); whole = number.value();
} }
StringView fraction_string(fraction_buffer.data(), fraction_buffer.size()); StringView fraction_string(fraction_buffer.data(), fraction_buffer.size());
auto fraction_string_uint = fraction_string.to_uint<u64>(); auto fraction_string_uint = fraction_string.to_uint<u64>();
if (!fraction_string_uint.has_value()) if (!fraction_string_uint.has_value())
return Error::from_string_literal("JsonParser: Error while parsing number"sv); return Error::from_string_literal("JsonParser: Error while parsing number");
auto fraction = static_cast<double>(fraction_string_uint.value()); auto fraction = static_cast<double>(fraction_string_uint.value());
double sign = (whole < 0) ? -1 : 1; double sign = (whole < 0) ? -1 : 1;
@ -272,7 +272,7 @@ ErrorOr<JsonValue> JsonParser::parse_number()
} else { } else {
auto number = number_string.to_int<i64>(); auto number = number_string.to_int<i64>();
if (!number.has_value()) if (!number.has_value())
return Error::from_string_literal("JsonParser: Error while parsing number"sv); return Error::from_string_literal("JsonParser: Error while parsing number");
if (number.value() <= NumericLimits<i32>::max()) { if (number.value() <= NumericLimits<i32>::max()) {
value = JsonValue((i32)number.value()); value = JsonValue((i32)number.value());
} else { } else {
@ -289,21 +289,21 @@ ErrorOr<JsonValue> JsonParser::parse_number()
ErrorOr<JsonValue> JsonParser::parse_true() ErrorOr<JsonValue> JsonParser::parse_true()
{ {
if (!consume_specific("true")) if (!consume_specific("true"))
return Error::from_string_literal("JsonParser: Expected 'true'"sv); return Error::from_string_literal("JsonParser: Expected 'true'");
return JsonValue(true); return JsonValue(true);
} }
ErrorOr<JsonValue> JsonParser::parse_false() ErrorOr<JsonValue> JsonParser::parse_false()
{ {
if (!consume_specific("false")) if (!consume_specific("false"))
return Error::from_string_literal("JsonParser: Expected 'false'"sv); return Error::from_string_literal("JsonParser: Expected 'false'");
return JsonValue(false); return JsonValue(false);
} }
ErrorOr<JsonValue> JsonParser::parse_null() ErrorOr<JsonValue> JsonParser::parse_null()
{ {
if (!consume_specific("null")) if (!consume_specific("null"))
return Error::from_string_literal("JsonParser: Expected 'null'"sv); return Error::from_string_literal("JsonParser: Expected 'null'");
return JsonValue(JsonValue::Type::Null); return JsonValue(JsonValue::Type::Null);
} }
@ -338,7 +338,7 @@ ErrorOr<JsonValue> JsonParser::parse_helper()
return parse_null(); return parse_null();
} }
return Error::from_string_literal("JsonParser: Unexpected character"sv); return Error::from_string_literal("JsonParser: Unexpected character");
} }
ErrorOr<JsonValue> JsonParser::parse() ErrorOr<JsonValue> JsonParser::parse()
@ -346,7 +346,7 @@ ErrorOr<JsonValue> JsonParser::parse()
auto result = TRY(parse_helper()); auto result = TRY(parse_helper());
ignore_while(is_space); ignore_while(is_space);
if (!is_eof()) if (!is_eof())
return Error::from_string_literal("JsonParser: Didn't consume all input"sv); return Error::from_string_literal("JsonParser: Didn't consume all input");
return result; return result;
} }

View File

@ -45,7 +45,7 @@ public:
{ {
if (!handle_any_error()) if (!handle_any_error())
return {}; return {};
return Error::from_string_literal("Stream error"sv); return Error::from_string_literal("Stream error");
} }
virtual void set_recoverable_error() const { m_recoverable_error = true; } virtual void set_recoverable_error() const { m_recoverable_error = true; }

View File

@ -79,7 +79,7 @@ static ErrorOr<String> decode_html_entities(StringView const& str)
} }
if (!found_entity) if (!found_entity)
return Error::from_string_literal("Failed to decode html entity"sv); return Error::from_string_literal("Failed to decode html entity");
if (entity_start.value() != start) if (entity_start.value() != start)
decoded_str.append(str.substring_view(start, entity_start.value() - start)); decoded_str.append(str.substring_view(start, entity_start.value() - start));
@ -94,25 +94,25 @@ static ErrorOr<ApprovalDate> parse_approval_date(StringView const& str)
{ {
auto parts = str.trim_whitespace().split_view('/', true); auto parts = str.trim_whitespace().split_view('/', true);
if (parts.size() != 3) if (parts.size() != 3)
return Error::from_string_literal("Failed to parse approval date parts (mm/dd/yyyy)"sv); return Error::from_string_literal("Failed to parse approval date parts (mm/dd/yyyy)");
auto month = parts[0].to_uint(); auto month = parts[0].to_uint();
if (!month.has_value()) if (!month.has_value())
return Error::from_string_literal("Failed to parse month from approval date"sv); return Error::from_string_literal("Failed to parse month from approval date");
if (month.value() == 0 || month.value() > 12) if (month.value() == 0 || month.value() > 12)
return Error::from_string_literal("Invalid month in approval date"sv); return Error::from_string_literal("Invalid month in approval date");
auto day = parts[1].to_uint(); auto day = parts[1].to_uint();
if (!day.has_value()) if (!day.has_value())
return Error::from_string_literal("Failed to parse day from approval date"sv); return Error::from_string_literal("Failed to parse day from approval date");
if (day.value() == 0 || day.value() > 31) if (day.value() == 0 || day.value() > 31)
return Error::from_string_literal("Invalid day in approval date"sv); return Error::from_string_literal("Invalid day in approval date");
auto year = parts[2].to_uint(); auto year = parts[2].to_uint();
if (!year.has_value()) if (!year.has_value())
return Error::from_string_literal("Failed to parse year from approval date"sv); return Error::from_string_literal("Failed to parse year from approval date");
if (year.value() < 1900 || year.value() > 2999) if (year.value() < 1900 || year.value() > 2999)
return Error::from_string_literal("Invalid year approval date"sv); return Error::from_string_literal("Invalid year approval date");
return ApprovalDate { .year = year.value(), .month = month.value(), .day = day.value() }; return ApprovalDate { .year = year.value(), .month = month.value(), .day = day.value() };
} }
@ -132,15 +132,15 @@ static ErrorOr<HashMap<String, PnpIdData>> parse_pnp_ids_database(Core::File& pn
auto row_start_tag_end = pnp_ids_file_contents.find(">"sv, row_start.value() + row_start_tag.length()); auto row_start_tag_end = pnp_ids_file_contents.find(">"sv, row_start.value() + row_start_tag.length());
if (!row_start_tag_end.has_value()) if (!row_start_tag_end.has_value())
return Error::from_string_literal("Incomplete row start tag"sv); return Error::from_string_literal("Incomplete row start tag");
static auto const row_end_tag = "</tr>"sv; static auto const row_end_tag = "</tr>"sv;
auto row_end = pnp_ids_file_contents.find(row_end_tag, row_start.value()); auto row_end = pnp_ids_file_contents.find(row_end_tag, row_start.value());
if (!row_end.has_value()) if (!row_end.has_value())
return Error::from_string_literal("No matching row end tag found"sv); return Error::from_string_literal("No matching row end tag found");
if (row_start_tag_end.value() > row_end.value() + row_end_tag.length()) if (row_start_tag_end.value() > row_end.value() + row_end_tag.length())
return Error::from_string_literal("Invalid row start tag"sv); return Error::from_string_literal("Invalid row start tag");
auto row_string = pnp_ids_file_contents.substring_view(row_start_tag_end.value() + 1, row_end.value() - row_start_tag_end.value() - 1); auto row_string = pnp_ids_file_contents.substring_view(row_start_tag_end.value() + 1, row_end.value() - row_start_tag_end.value() - 1);
Vector<String, (size_t)PnpIdColumns::ColumnCount> columns; Vector<String, (size_t)PnpIdColumns::ColumnCount> columns;
@ -153,31 +153,31 @@ static ErrorOr<HashMap<String, PnpIdData>> parse_pnp_ids_database(Core::File& pn
static auto const column_end_tag = "</td>"sv; static auto const column_end_tag = "</td>"sv;
auto column_end = row_string.find(column_end_tag, column_start.value() + column_start_tag.length()); auto column_end = row_string.find(column_end_tag, column_start.value() + column_start_tag.length());
if (!column_end.has_value()) if (!column_end.has_value())
return Error::from_string_literal("No matching column end tag found"sv); return Error::from_string_literal("No matching column end tag found");
auto column_content_row_offset = column_start.value() + column_start_tag.length(); auto column_content_row_offset = column_start.value() + column_start_tag.length();
auto column_str = row_string.substring_view(column_content_row_offset, column_end.value() - column_content_row_offset).trim_whitespace(); auto column_str = row_string.substring_view(column_content_row_offset, column_end.value() - column_content_row_offset).trim_whitespace();
if (column_str.find('\"').has_value()) if (column_str.find('\"').has_value())
return Error::from_string_literal("Found '\"' in column content, escaping not supported!"sv); return Error::from_string_literal("Found '\"' in column content, escaping not supported!");
columns.append(column_str); columns.append(column_str);
column_row_offset = column_end.value() + column_end_tag.length(); column_row_offset = column_end.value() + column_end_tag.length();
} }
if (columns.size() != (size_t)PnpIdColumns::ColumnCount) if (columns.size() != (size_t)PnpIdColumns::ColumnCount)
return Error::from_string_literal("Unexpected number of columns found"sv); return Error::from_string_literal("Unexpected number of columns found");
auto approval_date = TRY(parse_approval_date(columns[(size_t)PnpIdColumns::ApprovalDate])); auto approval_date = TRY(parse_approval_date(columns[(size_t)PnpIdColumns::ApprovalDate]));
auto decoded_manufacturer_name = TRY(decode_html_entities(columns[(size_t)PnpIdColumns::ManufacturerName])); auto decoded_manufacturer_name = TRY(decode_html_entities(columns[(size_t)PnpIdColumns::ManufacturerName]));
auto hash_set_result = pnp_id_data.set(columns[(size_t)PnpIdColumns::ManufacturerId], PnpIdData { .manufacturer_name = decoded_manufacturer_name, .approval_date = move(approval_date) }); auto hash_set_result = pnp_id_data.set(columns[(size_t)PnpIdColumns::ManufacturerId], PnpIdData { .manufacturer_name = decoded_manufacturer_name, .approval_date = move(approval_date) });
if (hash_set_result != AK::HashSetResult::InsertedNewEntry) if (hash_set_result != AK::HashSetResult::InsertedNewEntry)
return Error::from_string_literal("Duplicate manufacturer ID encountered"sv); return Error::from_string_literal("Duplicate manufacturer ID encountered");
row_content_offset = row_end.value() + row_end_tag.length(); row_content_offset = row_end.value() + row_end_tag.length();
} }
if (pnp_id_data.size() <= 1) if (pnp_id_data.size() <= 1)
return Error::from_string_literal("Expected more than one row"sv); return Error::from_string_literal("Expected more than one row");
return pnp_id_data; return pnp_id_data;
} }
@ -283,7 +283,7 @@ ErrorOr<int> serenity_main(Main::Arguments arguments)
auto open_file = [&](StringView path, Core::OpenMode mode = Core::OpenMode::ReadOnly) -> ErrorOr<NonnullRefPtr<Core::File>> { auto open_file = [&](StringView path, Core::OpenMode mode = Core::OpenMode::ReadOnly) -> ErrorOr<NonnullRefPtr<Core::File>> {
if (path.is_empty()) { if (path.is_empty()) {
args_parser.print_usage(stderr, arguments.argv[0]); args_parser.print_usage(stderr, arguments.argv[0]);
return Error::from_string_literal("Must provide all command line options"sv); return Error::from_string_literal("Must provide all command line options");
} }
return Core::File::open(path, mode); return Core::File::open(path, mode);

View File

@ -211,7 +211,7 @@ struct CanonicalLanguageID {
if (segments.size() == ++index) if (segments.size() == ++index)
return language_id; return language_id;
} else { } else {
return Error::from_string_literal("Expected language subtag"sv); return Error::from_string_literal("Expected language subtag");
} }
if (Unicode::is_unicode_script_subtag(segments[index])) { if (Unicode::is_unicode_script_subtag(segments[index])) {
@ -228,7 +228,7 @@ struct CanonicalLanguageID {
while (index < segments.size()) { while (index < segments.size()) {
if (!Unicode::is_unicode_variant_subtag(segments[index])) if (!Unicode::is_unicode_variant_subtag(segments[index]))
return Error::from_string_literal("Expected variant subtag"sv); return Error::from_string_literal("Expected variant subtag");
language_id.variants.append(unique_strings.ensure(segments[index++])); language_id.variants.append(unique_strings.ensure(segments[index++]));
} }
@ -244,7 +244,7 @@ struct CanonicalLanguageID {
inline ErrorOr<NonnullOwnPtr<Core::Stream::BufferedFile>> open_file(StringView path, Core::Stream::OpenMode mode) inline ErrorOr<NonnullOwnPtr<Core::Stream::BufferedFile>> open_file(StringView path, Core::Stream::OpenMode mode)
{ {
if (path.is_empty()) if (path.is_empty())
return Error::from_string_literal("Provided path is empty, please provide all command line options"sv); return Error::from_string_literal("Provided path is empty, please provide all command line options");
auto file = TRY(Core::Stream::File::open(path, mode)); auto file = TRY(Core::Stream::File::open(path, mode));
return Core::Stream::BufferedFile::create(move(file)); return Core::Stream::BufferedFile::create(move(file));
@ -273,8 +273,12 @@ inline ErrorOr<Core::DirIterator> path_to_dir_iterator(String path, StringView s
lexical_path = lexical_path.append(subpath); lexical_path = lexical_path.append(subpath);
Core::DirIterator iterator(lexical_path.string(), Core::DirIterator::SkipParentAndBaseDir); Core::DirIterator iterator(lexical_path.string(), Core::DirIterator::SkipParentAndBaseDir);
if (iterator.has_error()) if (iterator.has_error()) {
return Error::from_string_literal(iterator.error_string()); // FIXME: Make Core::DirIterator return a StringView for its error
// string.
auto const* error_string_ptr = iterator.error_string();
return Error::from_string_view({ error_string_ptr, strlen(error_string_ptr) });
}
return iterator; return iterator;
} }
@ -282,8 +286,12 @@ inline ErrorOr<Core::DirIterator> path_to_dir_iterator(String path, StringView s
inline ErrorOr<String> next_path_from_dir_iterator(Core::DirIterator& iterator) inline ErrorOr<String> next_path_from_dir_iterator(Core::DirIterator& iterator)
{ {
auto next_path = iterator.next_full_path(); auto next_path = iterator.next_full_path();
if (iterator.has_error()) if (iterator.has_error()) {
return Error::from_string_literal(iterator.error_string()); // FIXME: Make Core::DirIterator return a StringView for its error
// string.
auto const* error_string_ptr = iterator.error_string();
return Error::from_string_view({ error_string_ptr, strlen(error_string_ptr) });
}
return next_path; return next_path;
} }

View File

@ -289,7 +289,7 @@ ErrorOr<int> serenity_main(Main::Arguments arguments)
dbgln("Create applet: {} with spec '{}'", (int)graph_type, spec); dbgln("Create applet: {} with spec '{}'", (int)graph_type, spec);
if (parts.size() != 2) if (parts.size() != 2)
return Error::from_string_literal("ResourceGraph: Applet spec is not composed of exactly 2 comma-separated parts"sv); return Error::from_string_literal("ResourceGraph: Applet spec is not composed of exactly 2 comma-separated parts");
auto name = parts[0]; auto name = parts[0];
auto graph_color = Gfx::Color::from_string(parts[1]); auto graph_color = Gfx::Color::from_string(parts[1]);

View File

@ -30,7 +30,7 @@ ErrorOr<NonnullRefPtr<Image>> Image::try_create_with_size(Gfx::IntSize const& si
VERIFY(!size.is_empty()); VERIFY(!size.is_empty());
if (size.width() > 16384 || size.height() > 16384) if (size.width() > 16384 || size.height() > 16384)
return Error::from_string_literal("Image size too large"sv); return Error::from_string_literal("Image size too large");
return adopt_nonnull_ref_or_enomem(new (nothrow) Image(size)); return adopt_nonnull_ref_or_enomem(new (nothrow) Image(size));
} }
@ -62,16 +62,16 @@ ErrorOr<NonnullRefPtr<Gfx::Bitmap>> Image::try_decode_bitmap(ReadonlyBytes bitma
// FIXME: Find a way to avoid the memory copying here. // FIXME: Find a way to avoid the memory copying here.
auto maybe_decoded_image = client->decode_image(bitmap_data); auto maybe_decoded_image = client->decode_image(bitmap_data);
if (!maybe_decoded_image.has_value()) if (!maybe_decoded_image.has_value())
return Error::from_string_literal("Image decode failed"sv); return Error::from_string_literal("Image decode failed");
// FIXME: Support multi-frame images? // FIXME: Support multi-frame images?
auto decoded_image = maybe_decoded_image.release_value(); auto decoded_image = maybe_decoded_image.release_value();
if (decoded_image.frames.is_empty()) if (decoded_image.frames.is_empty())
return Error::from_string_literal("Image decode failed (no frames)"sv); return Error::from_string_literal("Image decode failed (no frames)");
auto decoded_bitmap = decoded_image.frames.first().bitmap; auto decoded_bitmap = decoded_image.frames.first().bitmap;
if (decoded_bitmap.is_null()) if (decoded_bitmap.is_null())
return Error::from_string_literal("Image decode failed (no bitmap for frame)"sv); return Error::from_string_literal("Image decode failed (no bitmap for frame)");
return decoded_bitmap.release_nonnull(); return decoded_bitmap.release_nonnull();
} }
@ -108,7 +108,7 @@ ErrorOr<NonnullRefPtr<Image>> Image::try_create_from_pixel_paint_json(JsonObject
auto height = layer_object.get("height").to_i32(); auto height = layer_object.get("height").to_i32();
if (width != layer->size().width() || height != layer->size().height()) if (width != layer->size().width() || height != layer->size().height())
return Error::from_string_literal("Decoded layer bitmap has wrong size"sv); return Error::from_string_literal("Decoded layer bitmap has wrong size");
image->add_layer(*layer); image->add_layer(*layer);

View File

@ -20,7 +20,7 @@ ErrorOr<NonnullRefPtr<Layer>> Layer::try_create_with_size(Image& image, Gfx::Int
VERIFY(!size.is_empty()); VERIFY(!size.is_empty());
if (size.width() > 16384 || size.height() > 16384) if (size.width() > 16384 || size.height() > 16384)
return Error::from_string_literal("Layer size too large"sv); return Error::from_string_literal("Layer size too large");
auto bitmap = TRY(Gfx::Bitmap::try_create(Gfx::BitmapFormat::BGRA8888, size)); auto bitmap = TRY(Gfx::Bitmap::try_create(Gfx::BitmapFormat::BGRA8888, size));
return adopt_nonnull_ref_or_enomem(new (nothrow) Layer(image, move(bitmap), move(name))); return adopt_nonnull_ref_or_enomem(new (nothrow) Layer(image, move(bitmap), move(name)));
@ -31,7 +31,7 @@ ErrorOr<NonnullRefPtr<Layer>> Layer::try_create_with_bitmap(Image& image, Nonnul
VERIFY(!bitmap->size().is_empty()); VERIFY(!bitmap->size().is_empty());
if (bitmap->size().width() > 16384 || bitmap->size().height() > 16384) if (bitmap->size().width() > 16384 || bitmap->size().height() > 16384)
return Error::from_string_literal("Layer size too large"sv); return Error::from_string_literal("Layer size too large");
return adopt_nonnull_ref_or_enomem(new (nothrow) Layer(image, bitmap, move(name))); return adopt_nonnull_ref_or_enomem(new (nothrow) Layer(image, bitmap, move(name)));
} }
@ -145,7 +145,7 @@ void Layer::erase_selection(Selection const& selection)
ErrorOr<void> Layer::try_set_bitmaps(NonnullRefPtr<Gfx::Bitmap> content, RefPtr<Gfx::Bitmap> mask) ErrorOr<void> Layer::try_set_bitmaps(NonnullRefPtr<Gfx::Bitmap> content, RefPtr<Gfx::Bitmap> mask)
{ {
if (mask && content->size() != mask->size()) if (mask && content->size() != mask->size())
return Error::from_string_literal("Layer content and mask must be same size"sv); return Error::from_string_literal("Layer content and mask must be same size");
m_content_bitmap = move(content); m_content_bitmap = move(content);
m_mask_bitmap = move(mask); m_mask_bitmap = move(mask);

View File

@ -32,7 +32,7 @@ ErrorOr<void> ProjectBuilder::build(StringView active_file)
} }
if (active_file.is_null()) if (active_file.is_null())
return Error::from_string_literal("no active file"sv); return Error::from_string_literal("no active file");
if (active_file.ends_with(".js")) { if (active_file.ends_with(".js")) {
TRY(m_terminal->run_command(String::formatted("js -A {}", active_file))); TRY(m_terminal->run_command(String::formatted("js -A {}", active_file)));
@ -58,7 +58,7 @@ ErrorOr<void> ProjectBuilder::run(StringView active_file)
} }
if (active_file.is_null()) if (active_file.is_null())
return Error::from_string_literal("no active file"sv); return Error::from_string_literal("no active file");
if (active_file.ends_with(".js")) { if (active_file.ends_with(".js")) {
TRY(m_terminal->run_command(String::formatted("js {}", active_file))); TRY(m_terminal->run_command(String::formatted("js {}", active_file)));
@ -89,7 +89,7 @@ ErrorOr<void> ProjectBuilder::update_active_file(StringView active_file)
auto cmake_file = find_cmake_file_for(active_file); auto cmake_file = find_cmake_file_for(active_file);
if (!cmake_file.has_value()) { if (!cmake_file.has_value()) {
warnln("did not find cmake file for: {}", active_file); warnln("did not find cmake file for: {}", active_file);
return Error::from_string_literal("did not find cmake file"sv); return Error::from_string_literal("did not find cmake file");
} }
if (m_serenity_component_cmake_file == cmake_file.value()) if (m_serenity_component_cmake_file == cmake_file.value())
@ -116,7 +116,7 @@ ErrorOr<String> ProjectBuilder::component_name(StringView cmake_file_path)
static Regex<ECMA262> const component_name(R"~~~(serenity_component\([\s]*(\w+)[\s\S]*\))~~~"); static Regex<ECMA262> const component_name(R"~~~(serenity_component\([\s]*(\w+)[\s\S]*\))~~~");
RegexResult result; RegexResult result;
if (!component_name.search(StringView { content }, result)) if (!component_name.search(StringView { content }, result))
return Error::from_string_literal("component not found"sv); return Error::from_string_literal("component not found");
return String { result.capture_group_matches.at(0).at(0).view.string_view() }; return String { result.capture_group_matches.at(0).at(0).view.string_view() };
} }
@ -255,7 +255,7 @@ ErrorOr<void> ProjectBuilder::verify_cmake_is_installed()
auto res = Core::command("cmake --version", {}); auto res = Core::command("cmake --version", {});
if (!res.is_error() && res.value().exit_code == 0) if (!res.is_error() && res.value().exit_code == 0)
return {}; return {};
return Error::from_string_literal("CMake port is not installed"sv); return Error::from_string_literal("CMake port is not installed");
} }
ErrorOr<void> ProjectBuilder::verify_make_is_installed() ErrorOr<void> ProjectBuilder::verify_make_is_installed()
@ -263,7 +263,7 @@ ErrorOr<void> ProjectBuilder::verify_make_is_installed()
auto res = Core::command("make --version", {}); auto res = Core::command("make --version", {});
if (!res.is_error() && res.value().exit_code == 0) if (!res.is_error() && res.value().exit_code == 0)
return {}; return {};
return Error::from_string_literal("Make port is not installed"sv); return Error::from_string_literal("Make port is not installed");
} }
String ProjectBuilder::build_directory() const String ProjectBuilder::build_directory() const

View File

@ -49,7 +49,7 @@ ErrorOr<void> TerminalWrapper::run_command(String const& command, Optional<Strin
VERIFY(m_child_exit_status.has_value()); VERIFY(m_child_exit_status.has_value());
if (m_child_exit_status.value() != 0) if (m_child_exit_status.value() != 0)
return Error::from_string_literal(failure_message.value_or("Command execution failed"sv)); return Error::from_string_view(failure_message.value_or("Command execution failed"sv));
} }
return {}; return {};

View File

@ -240,7 +240,7 @@ ErrorOr<NonnullOwnPtr<Profile>> Profile::load_from_perfcore_file(StringView path
auto json = JsonValue::from_string(file->read_all()); auto json = JsonValue::from_string(file->read_all());
if (json.is_error() || !json.value().is_object()) if (json.is_error() || !json.value().is_object())
return Error::from_string_literal("Invalid perfcore format (not a JSON object)"sv); return Error::from_string_literal("Invalid perfcore format (not a JSON object)");
auto const& object = json.value().as_object(); auto const& object = json.value().as_object();
@ -255,7 +255,7 @@ ErrorOr<NonnullOwnPtr<Profile>> Profile::load_from_perfcore_file(StringView path
auto const* strings_value = object.get_ptr("strings"sv); auto const* strings_value = object.get_ptr("strings"sv);
if (!strings_value || !strings_value->is_array()) if (!strings_value || !strings_value->is_array())
return Error::from_string_literal("Malformed profile (strings is not an array)"sv); return Error::from_string_literal("Malformed profile (strings is not an array)");
HashMap<FlatPtr, String> profile_strings; HashMap<FlatPtr, String> profile_strings;
for (FlatPtr string_id = 0; string_id < strings_value->as_array().size(); ++string_id) { for (FlatPtr string_id = 0; string_id < strings_value->as_array().size(); ++string_id) {
@ -265,7 +265,7 @@ ErrorOr<NonnullOwnPtr<Profile>> Profile::load_from_perfcore_file(StringView path
auto const* events_value = object.get_ptr("events"); auto const* events_value = object.get_ptr("events");
if (!events_value || !events_value->is_array()) if (!events_value || !events_value->is_array())
return Error::from_string_literal("Malformed profile (events is not an array)"sv); return Error::from_string_literal("Malformed profile (events is not an array)");
auto const& perf_events = events_value->as_array(); auto const& perf_events = events_value->as_array();
@ -446,7 +446,7 @@ ErrorOr<NonnullOwnPtr<Profile>> Profile::load_from_perfcore_file(StringView path
} }
if (events.is_empty()) if (events.is_empty())
return Error::from_string_literal("No events captured (targeted process was never on CPU)"sv); return Error::from_string_literal("No events captured (targeted process was never on CPU)");
quick_sort(all_processes, [](auto& a, auto& b) { quick_sort(all_processes, [](auto& a, auto& b) {
if (a.pid == b.pid) if (a.pid == b.pid)

View File

@ -861,7 +861,7 @@ ErrorOr<u64> read_utf8_char(BigEndianInputBitStream& input)
if ((start_byte & 0b10000000) == 0) { if ((start_byte & 0b10000000) == 0) {
return start_byte; return start_byte;
} else if ((start_byte & 0b11000000) == 0b10000000) { } else if ((start_byte & 0b11000000) == 0b10000000) {
return Error::from_string_literal("Illegal continuation byte"sv); return Error::from_string_literal("Illegal continuation byte");
} }
// This algorithm is too good and supports the theoretical max 0xFF start byte // This algorithm is too good and supports the theoretical max 0xFF start byte
u8 length = 1; u8 length = 1;

View File

@ -73,14 +73,14 @@ ErrorOr<Account> Account::self([[maybe_unused]] Read options)
auto pwd = TRY(Core::System::getpwuid(getuid())); auto pwd = TRY(Core::System::getpwuid(getuid()));
if (!pwd.has_value()) if (!pwd.has_value())
return Error::from_string_literal("No such user"sv); return Error::from_string_literal("No such user");
spwd spwd = {}; spwd spwd = {};
#ifndef AK_OS_BSD_GENERIC #ifndef AK_OS_BSD_GENERIC
if (options != Read::PasswdOnly) { if (options != Read::PasswdOnly) {
auto maybe_spwd = TRY(Core::System::getspnam({ pwd->pw_name, strlen(pwd->pw_name) })); auto maybe_spwd = TRY(Core::System::getspnam({ pwd->pw_name, strlen(pwd->pw_name) }));
if (!maybe_spwd.has_value()) if (!maybe_spwd.has_value())
return Error::from_string_literal("No shadow entry for user"sv); return Error::from_string_literal("No shadow entry for user");
spwd = maybe_spwd.release_value(); spwd = maybe_spwd.release_value();
} }
#endif #endif
@ -92,14 +92,14 @@ ErrorOr<Account> Account::from_name(char const* username, [[maybe_unused]] Read
{ {
auto pwd = TRY(Core::System::getpwnam({ username, strlen(username) })); auto pwd = TRY(Core::System::getpwnam({ username, strlen(username) }));
if (!pwd.has_value()) if (!pwd.has_value())
return Error::from_string_literal("No such user"sv); return Error::from_string_literal("No such user");
spwd spwd = {}; spwd spwd = {};
#ifndef AK_OS_BSD_GENERIC #ifndef AK_OS_BSD_GENERIC
if (options != Read::PasswdOnly) { if (options != Read::PasswdOnly) {
auto maybe_spwd = TRY(Core::System::getspnam({ pwd->pw_name, strlen(pwd->pw_name) })); auto maybe_spwd = TRY(Core::System::getspnam({ pwd->pw_name, strlen(pwd->pw_name) }));
if (!maybe_spwd.has_value()) if (!maybe_spwd.has_value())
return Error::from_string_literal("No shadow entry for user"sv); return Error::from_string_literal("No shadow entry for user");
spwd = maybe_spwd.release_value(); spwd = maybe_spwd.release_value();
} }
#endif #endif
@ -110,14 +110,14 @@ ErrorOr<Account> Account::from_uid(uid_t uid, [[maybe_unused]] Read options)
{ {
auto pwd = TRY(Core::System::getpwuid(uid)); auto pwd = TRY(Core::System::getpwuid(uid));
if (!pwd.has_value()) if (!pwd.has_value())
return Error::from_string_literal("No such user"sv); return Error::from_string_literal("No such user");
spwd spwd = {}; spwd spwd = {};
#ifndef AK_OS_BSD_GENERIC #ifndef AK_OS_BSD_GENERIC
if (options != Read::PasswdOnly) { if (options != Read::PasswdOnly) {
auto maybe_spwd = TRY(Core::System::getspnam({ pwd->pw_name, strlen(pwd->pw_name) })); auto maybe_spwd = TRY(Core::System::getspnam({ pwd->pw_name, strlen(pwd->pw_name) }));
if (!maybe_spwd.has_value()) if (!maybe_spwd.has_value())
return Error::from_string_literal("No shadow entry for user"sv); return Error::from_string_literal("No shadow entry for user");
spwd = maybe_spwd.release_value(); spwd = maybe_spwd.release_value();
} }
#endif #endif

View File

@ -22,7 +22,7 @@ ErrorOr<CommandResult> command(String const& command_string, Optional<LexicalPat
{ {
auto parts = command_string.split(' '); auto parts = command_string.split(' ');
if (parts.is_empty()) if (parts.is_empty())
return Error::from_string_literal("empty command"sv); return Error::from_string_literal("empty command");
auto program = parts[0]; auto program = parts[0];
parts.remove(0); parts.remove(0);
return command(program, parts, chdir); return command(program, parts, chdir);

View File

@ -41,7 +41,7 @@ ErrorOr<FilePermissionsMask> FilePermissionsMask::from_numeric_notation(StringVi
{ {
mode_t mode = AK::StringUtils::convert_to_uint_from_octal<u16>(string).value_or(01000); mode_t mode = AK::StringUtils::convert_to_uint_from_octal<u16>(string).value_or(01000);
if (mode > 0777) if (mode > 0777)
return Error::from_string_literal("invalid octal representation"sv); return Error::from_string_literal("invalid octal representation");
return FilePermissionsMask().assign_permissions(mode); return FilePermissionsMask().assign_permissions(mode);
} }
@ -73,9 +73,9 @@ ErrorOr<FilePermissionsMask> FilePermissionsMask::from_symbolic_notation(StringV
else if (ch == '=') else if (ch == '=')
operation = Operation::Assign; operation = Operation::Assign;
else if (classes == 0) else if (classes == 0)
return Error::from_string_literal("invalid class: expected 'u', 'g', 'o' or 'a'"sv); return Error::from_string_literal("invalid class: expected 'u', 'g', 'o' or 'a'");
else else
return Error::from_string_literal("invalid operation: expected '+', '-' or '='"sv); return Error::from_string_literal("invalid operation: expected '+', '-' or '='");
// if an operation was specified without a class, assume all // if an operation was specified without a class, assume all
if (classes == 0) if (classes == 0)
@ -106,7 +106,7 @@ ErrorOr<FilePermissionsMask> FilePermissionsMask::from_symbolic_notation(StringV
else if (ch == 'x') else if (ch == 'x')
write_bits = 1; write_bits = 1;
else else
return Error::from_string_literal("invalid symbolic permission: expected 'r', 'w' or 'x'"sv); return Error::from_string_literal("invalid symbolic permission: expected 'r', 'w' or 'x'");
mode_t clear_bits = operation == Operation::Assign ? 7 : write_bits; mode_t clear_bits = operation == Operation::Assign ? 7 : write_bits;

View File

@ -35,7 +35,7 @@ LocalServer::~LocalServer()
ErrorOr<void> LocalServer::take_over_from_system_server(String const& socket_path) ErrorOr<void> LocalServer::take_over_from_system_server(String const& socket_path)
{ {
if (m_listening) if (m_listening)
return Error::from_string_literal("Core::LocalServer: Can't perform socket takeover when already listening"sv); return Error::from_string_literal("Core::LocalServer: Can't perform socket takeover when already listening");
auto socket = TRY(take_over_socket_from_system_server(socket_path)); auto socket = TRY(take_over_socket_from_system_server(socket_path));
m_fd = TRY(socket->release_fd()); m_fd = TRY(socket->release_fd());

View File

@ -45,19 +45,19 @@ public:
switch (seek_mode) { switch (seek_mode) {
case SeekMode::SetPosition: case SeekMode::SetPosition:
if (offset >= static_cast<i64>(m_bytes.size())) if (offset >= static_cast<i64>(m_bytes.size()))
return Error::from_string_literal("Offset past the end of the stream memory"sv); return Error::from_string_literal("Offset past the end of the stream memory");
m_offset = offset; m_offset = offset;
break; break;
case SeekMode::FromCurrentPosition: case SeekMode::FromCurrentPosition:
if (offset + static_cast<i64>(m_offset) >= static_cast<i64>(m_bytes.size())) if (offset + static_cast<i64>(m_offset) >= static_cast<i64>(m_bytes.size()))
return Error::from_string_literal("Offset past the end of the stream memory"sv); return Error::from_string_literal("Offset past the end of the stream memory");
m_offset += offset; m_offset += offset;
break; break;
case SeekMode::FromEndPosition: case SeekMode::FromEndPosition:
if (offset >= static_cast<i64>(m_bytes.size())) if (offset >= static_cast<i64>(m_bytes.size()))
return Error::from_string_literal("Offset past the start of the stream memory"sv); return Error::from_string_literal("Offset past the start of the stream memory");
m_offset = m_bytes.size() - offset; m_offset = m_bytes.size() - offset;
break; break;

View File

@ -277,7 +277,7 @@ ErrorOr<NonnullOwnPtr<SOCKSProxyClient>> SOCKSProxyClient::connect(Socket& under
auto reply = TRY(send_connect_request_message(underlying, version, target, target_port, command)); auto reply = TRY(send_connect_request_message(underlying, version, target, target_port, command));
if (reply != Reply::Succeeded) { if (reply != Reply::Succeeded) {
underlying.close(); underlying.close();
return Error::from_string_literal(reply_response_name(reply)); return Error::from_string_view(reply_response_name(reply));
} }
return adopt_nonnull_own_or_enomem(new SOCKSProxyClient { return adopt_nonnull_own_or_enomem(new SOCKSProxyClient {
@ -296,7 +296,7 @@ ErrorOr<NonnullOwnPtr<SOCKSProxyClient>> SOCKSProxyClient::connect(Socket& under
auto reply = TRY(send_connect_request_message(underlying, version, target, target_port, command)); auto reply = TRY(send_connect_request_message(underlying, version, target, target_port, command));
if (reply != Reply::Succeeded) { if (reply != Reply::Succeeded) {
underlying.close(); underlying.close();
return Error::from_string_literal(reply_response_name(reply)); return Error::from_string_view(reply_response_name(reply));
} }
return adopt_nonnull_own_or_enomem(new SOCKSProxyClient { return adopt_nonnull_own_or_enomem(new SOCKSProxyClient {

View File

@ -118,7 +118,7 @@ public:
if (!result.is_error()) if (!result.is_error())
break; break;
if (result.error() != QueueStatus::Full) if (result.error() != QueueStatus::Full)
return Error::from_string_literal("Unexpected error while enqueuing"sv); return Error::from_string_literal("Unexpected error while enqueuing");
wait_function(); wait_function();
} }
@ -208,7 +208,7 @@ private:
SharedMemorySPCQ* shared_queue = is_new ? new (raw_mapping) SharedMemorySPCQ() : reinterpret_cast<SharedMemorySPCQ*>(raw_mapping); SharedMemorySPCQ* shared_queue = is_new ? new (raw_mapping) SharedMemorySPCQ() : reinterpret_cast<SharedMemorySPCQ*>(raw_mapping);
if (!shared_queue) if (!shared_queue)
return Error::from_string_literal("Unexpected error when creating shared queue from raw memory"sv); return Error::from_string_literal("Unexpected error when creating shared queue from raw memory");
return SharedSingleProducerCircularQueue<T, Size> { move(name), adopt_ref(*new (nothrow) RefCountedSharedMemorySPCQ(shared_queue, fd)) }; return SharedSingleProducerCircularQueue<T, Size> { move(name), adopt_ref(*new (nothrow) RefCountedSharedMemorySPCQ(shared_queue, fd)) };
} }

View File

@ -336,7 +336,8 @@ ErrorOr<IPv4Address> Socket::resolve_host(String const& host, SocketType type)
return Error::from_syscall("getaddrinfo", -errno); return Error::from_syscall("getaddrinfo", -errno);
} }
return Error::from_string_literal(gai_strerror(rc)); auto const* error_string = gai_strerror(rc);
return Error::from_string_view({ error_string, strlen(error_string) });
} }
auto* socket_address = bit_cast<struct sockaddr_in*>(results->ai_addr); auto* socket_address = bit_cast<struct sockaddr_in*>(results->ai_addr);

View File

@ -47,7 +47,7 @@ ErrorOr<NonnullOwnPtr<Core::Stream::LocalSocket>> take_over_socket_from_system_s
} else { } else {
auto it = s_overtaken_sockets.find(socket_path); auto it = s_overtaken_sockets.find(socket_path);
if (it == s_overtaken_sockets.end()) if (it == s_overtaken_sockets.end())
return Error::from_string_literal("Non-existent socket requested"sv); return Error::from_string_literal("Non-existent socket requested");
fd = it->value; fd = it->value;
} }
@ -55,7 +55,7 @@ ErrorOr<NonnullOwnPtr<Core::Stream::LocalSocket>> take_over_socket_from_system_s
auto stat = TRY(Core::System::fstat(fd)); auto stat = TRY(Core::System::fstat(fd));
if (!S_ISSOCK(stat.st_mode)) if (!S_ISSOCK(stat.st_mode))
return Error::from_string_literal("The fd we got from SystemServer is not a socket"sv); return Error::from_string_literal("The fd we got from SystemServer is not a socket");
auto socket = TRY(Core::Stream::LocalSocket::adopt_fd(fd)); auto socket = TRY(Core::Stream::LocalSocket::adopt_fd(fd));
// It had to be !CLOEXEC for obvious reasons, but we // It had to be !CLOEXEC for obvious reasons, but we

View File

@ -59,7 +59,7 @@ ErrorOr<void> Launcher::add_allowed_url(URL const& url)
{ {
auto response_or_error = connection().try_add_allowed_url(url); auto response_or_error = connection().try_add_allowed_url(url);
if (response_or_error.is_error()) if (response_or_error.is_error())
return Error::from_string_literal("Launcher::add_allowed_url: Failed"sv); return Error::from_string_literal("Launcher::add_allowed_url: Failed");
return {}; return {};
} }
@ -67,7 +67,7 @@ ErrorOr<void> Launcher::add_allowed_handler_with_any_url(String const& handler)
{ {
auto response_or_error = connection().try_add_allowed_handler_with_any_url(handler); auto response_or_error = connection().try_add_allowed_handler_with_any_url(handler);
if (response_or_error.is_error()) if (response_or_error.is_error())
return Error::from_string_literal("Launcher::add_allowed_handler_with_any_url: Failed"sv); return Error::from_string_literal("Launcher::add_allowed_handler_with_any_url: Failed");
return {}; return {};
} }
@ -75,7 +75,7 @@ ErrorOr<void> Launcher::add_allowed_handler_with_only_specific_urls(String const
{ {
auto response_or_error = connection().try_add_allowed_handler_with_only_specific_urls(handler, urls); auto response_or_error = connection().try_add_allowed_handler_with_only_specific_urls(handler, urls);
if (response_or_error.is_error()) if (response_or_error.is_error())
return Error::from_string_literal("Launcher::add_allowed_handler_with_only_specific_urls: Failed"sv); return Error::from_string_literal("Launcher::add_allowed_handler_with_only_specific_urls: Failed");
return {}; return {};
} }
@ -83,7 +83,7 @@ ErrorOr<void> Launcher::seal_allowlist()
{ {
auto response_or_error = connection().try_seal_allowlist(); auto response_or_error = connection().try_seal_allowlist();
if (response_or_error.is_error()) if (response_or_error.is_error())
return Error::from_string_literal("Launcher::seal_allowlist: Failed"sv); return Error::from_string_literal("Launcher::seal_allowlist: Failed");
return {}; return {};
} }

View File

@ -58,7 +58,7 @@ public:
auto* vic_details = VIC::find_details_by_vic_id(vic_id); auto* vic_details = VIC::find_details_by_vic_id(vic_id);
if (!vic_details) if (!vic_details)
return Error::from_string_literal("CEA 861 extension block has invalid short video descriptor"sv); return Error::from_string_literal("CEA 861 extension block has invalid short video descriptor");
IterationDecision decision = callback(is_native, *vic_details); IterationDecision decision = callback(is_native, *vic_details);
if (decision != IterationDecision::Continue) if (decision != IterationDecision::Continue)
@ -77,7 +77,7 @@ public:
} }
if (dtd_start > offsetof(Definitions::ExtensionBlock, checksum) - sizeof(Definitions::DetailedTiming)) if (dtd_start > offsetof(Definitions::ExtensionBlock, checksum) - sizeof(Definitions::DetailedTiming))
return Error::from_string_literal("CEA 861 extension block has invalid DTD list"sv); return Error::from_string_literal("CEA 861 extension block has invalid DTD list");
size_t dtd_index = 0; size_t dtd_index = 0;
for (size_t offset = dtd_start; offset <= offsetof(Definitions::ExtensionBlock, checksum) - sizeof(Definitions::DetailedTiming); offset += sizeof(Definitions::DetailedTiming)) { for (size_t offset = dtd_start; offset <= offsetof(Definitions::ExtensionBlock, checksum) - sizeof(Definitions::DetailedTiming); offset += sizeof(Definitions::DetailedTiming)) {
@ -108,7 +108,7 @@ private:
return IterationDecision::Continue; return IterationDecision::Continue;
if (dtd_start > offsetof(Definitions::ExtensionBlock, checksum)) if (dtd_start > offsetof(Definitions::ExtensionBlock, checksum))
return Error::from_string_literal("CEA 861 extension block has invalid DTD start offset"sv); return Error::from_string_literal("CEA 861 extension block has invalid DTD start offset");
auto* data_block_header = &m_block->cea861extension.bytes[0]; auto* data_block_header = &m_block->cea861extension.bytes[0];
auto* data_block_end = (u8 const*)m_block + dtd_start; auto* data_block_end = (u8 const*)m_block + dtd_start;
@ -117,7 +117,7 @@ private:
size_t payload_size = header_byte & 0x1f; size_t payload_size = header_byte & 0x1f;
auto tag = (DataBlockTag)((header_byte >> 5) & 0x7); auto tag = (DataBlockTag)((header_byte >> 5) & 0x7);
if (tag == DataBlockTag::Extended && payload_size == 0) if (tag == DataBlockTag::Extended && payload_size == 0)
return Error::from_string_literal("CEA 861 extension block has invalid extended data block size"sv); return Error::from_string_literal("CEA 861 extension block has invalid extended data block size");
auto decision = TRY(callback(tag, m_edid.m_bytes.slice(data_block_header - m_edid.m_bytes.data() + 1, payload_size))); auto decision = TRY(callback(tag, m_edid.m_bytes.slice(data_block_header - m_edid.m_bytes.data() + 1, payload_size)));
if (decision != IterationDecision::Continue) if (decision != IterationDecision::Continue)
@ -135,7 +135,7 @@ private:
return IterationDecision::Continue; return IterationDecision::Continue;
if (dtd_start > offsetof(Definitions::ExtensionBlock, checksum) - sizeof(Definitions::DetailedTiming)) if (dtd_start > offsetof(Definitions::ExtensionBlock, checksum) - sizeof(Definitions::DetailedTiming))
return Error::from_string_literal("CEA 861 extension block has invalid DTD list"sv); return Error::from_string_literal("CEA 861 extension block has invalid DTD list");
for (size_t offset = dtd_start; offset <= offsetof(Definitions::ExtensionBlock, checksum) - sizeof(Definitions::DisplayDescriptor); offset += sizeof(Definitions::DisplayDescriptor)) { for (size_t offset = dtd_start; offset <= offsetof(Definitions::ExtensionBlock, checksum) - sizeof(Definitions::DisplayDescriptor); offset += sizeof(Definitions::DisplayDescriptor)) {
auto& dd = *(Definitions::DisplayDescriptor const*)((u8 const*)m_block + offset); auto& dd = *(Definitions::DisplayDescriptor const*)((u8 const*)m_block + offset);
@ -301,17 +301,17 @@ Definitions::EDID const& Parser::raw_edid() const
ErrorOr<void> Parser::parse() ErrorOr<void> Parser::parse()
{ {
if (m_bytes.size() < sizeof(Definitions::EDID)) if (m_bytes.size() < sizeof(Definitions::EDID))
return Error::from_string_literal("Incomplete Parser structure"sv); return Error::from_string_literal("Incomplete Parser structure");
auto const& edid = raw_edid(); auto const& edid = raw_edid();
u64 header = read_le(&edid.header); u64 header = read_le(&edid.header);
if (header != 0x00ffffffffffff00ull) if (header != 0x00ffffffffffff00ull)
return Error::from_string_literal("No Parser header"sv); return Error::from_string_literal("No Parser header");
u8 major_version = read_host(&edid.version.version); u8 major_version = read_host(&edid.version.version);
m_revision = read_host(&edid.version.revision); m_revision = read_host(&edid.version.revision);
if (major_version != 1 || m_revision > 4) if (major_version != 1 || m_revision > 4)
return Error::from_string_literal("Unsupported Parser version"sv); return Error::from_string_literal("Unsupported Parser version");
#ifdef KERNEL #ifdef KERNEL
m_version = TRY(Kernel::KString::formatted("1.{}", (int)m_revision)); m_version = TRY(Kernel::KString::formatted("1.{}", (int)m_revision));
@ -325,7 +325,7 @@ ErrorOr<void> Parser::parse()
if (checksum != 0) { if (checksum != 0) {
if (m_revision >= 4) { if (m_revision >= 4) {
return Error::from_string_literal("Parser checksum mismatch"sv); return Error::from_string_literal("Parser checksum mismatch");
} else { } else {
dbgln("EDID checksum mismatch, data may be corrupted!"); dbgln("EDID checksum mismatch, data may be corrupted!");
} }
@ -370,9 +370,9 @@ ErrorOr<IterationDecision> Parser::for_each_extension_block(Function<IterationDe
current_extension_map = &raw_extension_blocks[0]; current_extension_map = &raw_extension_blocks[0];
raw_index++; raw_index++;
if (read_host(&current_extension_map->tag) != (u8)Definitions::ExtensionBlockTag::ExtensionBlockMap) if (read_host(&current_extension_map->tag) != (u8)Definitions::ExtensionBlockTag::ExtensionBlockMap)
return Error::from_string_literal("Did not find extension map at block 1"sv); return Error::from_string_literal("Did not find extension map at block 1");
if (!validate_block_checksum(*current_extension_map)) if (!validate_block_checksum(*current_extension_map))
return Error::from_string_literal("Extension block map checksum mismatch"sv); return Error::from_string_literal("Extension block map checksum mismatch");
} }
} else if (read_host(&raw_extension_blocks[0].tag) == (u8)Definitions::ExtensionBlockTag::ExtensionBlockMap) { } else if (read_host(&raw_extension_blocks[0].tag) == (u8)Definitions::ExtensionBlockTag::ExtensionBlockMap) {
current_extension_map = &raw_extension_blocks[0]; current_extension_map = &raw_extension_blocks[0];
@ -385,18 +385,18 @@ ErrorOr<IterationDecision> Parser::for_each_extension_block(Function<IterationDe
if (current_extension_map && raw_index == 127) { if (current_extension_map && raw_index == 127) {
if (tag != (u8)Definitions::ExtensionBlockTag::ExtensionBlockMap) if (tag != (u8)Definitions::ExtensionBlockTag::ExtensionBlockMap)
return Error::from_string_literal("Did not find extension map at block 128"sv); return Error::from_string_literal("Did not find extension map at block 128");
current_extension_map = &raw_extension_blocks[127]; current_extension_map = &raw_extension_blocks[127];
if (!validate_block_checksum(*current_extension_map)) if (!validate_block_checksum(*current_extension_map))
return Error::from_string_literal("Extension block map checksum mismatch"sv); return Error::from_string_literal("Extension block map checksum mismatch");
continue; continue;
} }
if (tag == (u8)Definitions::ExtensionBlockTag::ExtensionBlockMap) if (tag == (u8)Definitions::ExtensionBlockTag::ExtensionBlockMap)
return Error::from_string_literal("Unexpected extension map encountered"sv); return Error::from_string_literal("Unexpected extension map encountered");
if (!validate_block_checksum(raw_block)) if (!validate_block_checksum(raw_block))
return Error::from_string_literal("Extension block checksum mismatch"sv); return Error::from_string_literal("Extension block checksum mismatch");
size_t offset = (u8 const*)&raw_block - m_bytes.data(); size_t offset = (u8 const*)&raw_block - m_bytes.data();
IterationDecision decision = callback(raw_index + 1, tag, raw_block.block.revision, m_bytes.slice(offset, sizeof(Definitions::ExtensionBlock))); IterationDecision decision = callback(raw_index + 1, tag, raw_block.block.revision, m_bytes.slice(offset, sizeof(Definitions::ExtensionBlock)));

View File

@ -140,7 +140,7 @@ void Client::handle_prompt_end(i32 request_id, i32 error, Optional<IPC::File> co
if (file->is_device()) { if (file->is_device()) {
GUI::MessageBox::show_error(request_data.parent_window, String::formatted("Opening \"{}\" failed: Cannot open device files", *chosen_file)); GUI::MessageBox::show_error(request_data.parent_window, String::formatted("Opening \"{}\" failed: Cannot open device files", *chosen_file));
request_data.promise->resolve(Error::from_string_literal("Cannot open device files"sv)); request_data.promise->resolve(Error::from_string_literal("Cannot open device files"));
return; return;
} }

View File

@ -32,12 +32,12 @@ static ErrorOr<NonnullRefPtr<Object>> parse_gml_object(Queue<Token>& tokens)
TRY(object->add_property_child(TRY(Node::from_token<Comment>(tokens.dequeue())))); TRY(object->add_property_child(TRY(Node::from_token<Comment>(tokens.dequeue()))));
if (peek() != Token::Type::ClassMarker) if (peek() != Token::Type::ClassMarker)
return Error::from_string_literal("Expected class marker"sv); return Error::from_string_literal("Expected class marker");
tokens.dequeue(); tokens.dequeue();
if (peek() != Token::Type::ClassName) if (peek() != Token::Type::ClassName)
return Error::from_string_literal("Expected class name"sv); return Error::from_string_literal("Expected class name");
auto class_name = tokens.dequeue(); auto class_name = tokens.dequeue();
object->set_name(class_name.m_view); object->set_name(class_name.m_view);
@ -69,10 +69,10 @@ static ErrorOr<NonnullRefPtr<Object>> parse_gml_object(Queue<Token>& tokens)
auto property_name = tokens.dequeue(); auto property_name = tokens.dequeue();
if (property_name.m_view.is_empty()) if (property_name.m_view.is_empty())
return Error::from_string_literal("Expected non-empty property name"sv); return Error::from_string_literal("Expected non-empty property name");
if (peek() != Token::Type::Colon) if (peek() != Token::Type::Colon)
return Error::from_string_literal("Expected ':'"sv); return Error::from_string_literal("Expected ':'");
tokens.dequeue(); tokens.dequeue();
@ -87,7 +87,7 @@ static ErrorOr<NonnullRefPtr<Object>> parse_gml_object(Queue<Token>& tokens)
} else if (peek() == Token::Type::Comment) { } else if (peek() == Token::Type::Comment) {
pending_comments.append(TRY(Node::from_token<Comment>(tokens.dequeue()))); pending_comments.append(TRY(Node::from_token<Comment>(tokens.dequeue())));
} else { } else {
return Error::from_string_literal("Expected child, property, comment, or }}"sv); return Error::from_string_literal("Expected child, property, comment, or }}");
} }
} }
@ -96,7 +96,7 @@ static ErrorOr<NonnullRefPtr<Object>> parse_gml_object(Queue<Token>& tokens)
TRY(object->add_sub_object_child(pending_comments.take_first())); TRY(object->add_sub_object_child(pending_comments.take_first()));
if (peek() != Token::Type::RightCurly) if (peek() != Token::Type::RightCurly)
return Error::from_string_literal("Expected }}"sv); return Error::from_string_literal("Expected }}");
tokens.dequeue(); tokens.dequeue();
} }

View File

@ -89,7 +89,7 @@ ErrorOr<Icon> Icon::try_create_default_icon(StringView name)
if (!bitmap16 && !bitmap32) { if (!bitmap16 && !bitmap32) {
dbgln("Default icon not found: {}", name); dbgln("Default icon not found: {}", name);
return Error::from_string_literal("Default icon not found"sv); return Error::from_string_literal("Default icon not found");
} }
return Icon(move(bitmap16), move(bitmap32)); return Icon(move(bitmap16), move(bitmap32));

View File

@ -1356,13 +1356,13 @@ size_t BMPImageDecoderPlugin::frame_count()
ErrorOr<ImageFrameDescriptor> BMPImageDecoderPlugin::frame(size_t index) ErrorOr<ImageFrameDescriptor> BMPImageDecoderPlugin::frame(size_t index)
{ {
if (index > 0) if (index > 0)
return Error::from_string_literal("BMPImageDecoderPlugin: Invalid frame index"sv); return Error::from_string_literal("BMPImageDecoderPlugin: Invalid frame index");
if (m_context->state == BMPLoadingContext::State::Error) if (m_context->state == BMPLoadingContext::State::Error)
return Error::from_string_literal("BMPImageDecoderPlugin: Decoding failed"sv); return Error::from_string_literal("BMPImageDecoderPlugin: Decoding failed");
if (m_context->state < BMPLoadingContext::State::PixelDataDecoded && !decode_bmp_pixel_data(*m_context)) if (m_context->state < BMPLoadingContext::State::PixelDataDecoded && !decode_bmp_pixel_data(*m_context))
return Error::from_string_literal("BMPImageDecoderPlugin: Decoding failed"sv); return Error::from_string_literal("BMPImageDecoderPlugin: Decoding failed");
VERIFY(m_context->bitmap); VERIFY(m_context->bitmap);
return ImageFrameDescriptor { m_context->bitmap, 0 }; return ImageFrameDescriptor { m_context->bitmap, 0 };

View File

@ -70,7 +70,7 @@ ErrorOr<NonnullRefPtr<Bitmap>> Bitmap::try_create(BitmapFormat format, IntSize c
ErrorOr<NonnullRefPtr<Bitmap>> Bitmap::try_create_shareable(BitmapFormat format, IntSize const& size, int scale_factor) ErrorOr<NonnullRefPtr<Bitmap>> Bitmap::try_create_shareable(BitmapFormat format, IntSize const& size, int scale_factor)
{ {
if (size_would_overflow(format, size, scale_factor)) if (size_would_overflow(format, size, scale_factor))
return Error::from_string_literal("Gfx::Bitmap::try_create_shareable size overflow"sv); return Error::from_string_literal("Gfx::Bitmap::try_create_shareable size overflow");
auto const pitch = minimum_pitch(size.width() * scale_factor, format); auto const pitch = minimum_pitch(size.width() * scale_factor, format);
auto const data_size = size_in_bytes(pitch, size.height() * scale_factor); auto const data_size = size_in_bytes(pitch, size.height() * scale_factor);
@ -98,7 +98,7 @@ Bitmap::Bitmap(BitmapFormat format, IntSize const& size, int scale_factor, Backi
ErrorOr<NonnullRefPtr<Bitmap>> Bitmap::try_create_wrapper(BitmapFormat format, IntSize const& size, int scale_factor, size_t pitch, void* data) ErrorOr<NonnullRefPtr<Bitmap>> Bitmap::try_create_wrapper(BitmapFormat format, IntSize const& size, int scale_factor, size_t pitch, void* data)
{ {
if (size_would_overflow(format, size, scale_factor)) if (size_would_overflow(format, size, scale_factor))
return Error::from_string_literal("Gfx::Bitmap::try_create_wrapper size overflow"sv); return Error::from_string_literal("Gfx::Bitmap::try_create_wrapper size overflow");
return adopt_ref(*new Bitmap(format, size, scale_factor, pitch, data)); return adopt_ref(*new Bitmap(format, size, scale_factor, pitch, data));
} }
@ -134,7 +134,7 @@ ErrorOr<NonnullRefPtr<Bitmap>> Bitmap::try_load_from_fd_and_close(int fd, String
return bitmap.release_nonnull(); return bitmap.release_nonnull();
} }
return Error::from_string_literal("Gfx::Bitmap unable to load from fd"sv); return Error::from_string_literal("Gfx::Bitmap unable to load from fd");
} }
Bitmap::Bitmap(BitmapFormat format, IntSize const& size, int scale_factor, size_t pitch, void* data) Bitmap::Bitmap(BitmapFormat format, IntSize const& size, int scale_factor, size_t pitch, void* data)
@ -206,22 +206,22 @@ ErrorOr<NonnullRefPtr<Bitmap>> Bitmap::try_create_from_serialized_byte_buffer(By
}; };
if (!read(actual_size) || !read(width) || !read(height) || !read(scale_factor) || !read(format) || !read(palette_size)) if (!read(actual_size) || !read(width) || !read(height) || !read(scale_factor) || !read(format) || !read(palette_size))
return Error::from_string_literal("Gfx::Bitmap::try_create_from_serialized_byte_buffer: decode failed"sv); return Error::from_string_literal("Gfx::Bitmap::try_create_from_serialized_byte_buffer: decode failed");
if (format > BitmapFormat::BGRA8888 || format < BitmapFormat::Indexed1) if (format > BitmapFormat::BGRA8888 || format < BitmapFormat::Indexed1)
return Error::from_string_literal("Gfx::Bitmap::try_create_from_serialized_byte_buffer: decode failed"sv); return Error::from_string_literal("Gfx::Bitmap::try_create_from_serialized_byte_buffer: decode failed");
if (!check_size({ width, height }, scale_factor, format, actual_size)) if (!check_size({ width, height }, scale_factor, format, actual_size))
return Error::from_string_literal("Gfx::Bitmap::try_create_from_serialized_byte_buffer: decode failed"sv); return Error::from_string_literal("Gfx::Bitmap::try_create_from_serialized_byte_buffer: decode failed");
palette.ensure_capacity(palette_size); palette.ensure_capacity(palette_size);
for (size_t i = 0; i < palette_size; ++i) { for (size_t i = 0; i < palette_size; ++i) {
if (!read(palette[i])) if (!read(palette[i]))
return Error::from_string_literal("Gfx::Bitmap::try_create_from_serialized_byte_buffer: decode failed"sv); return Error::from_string_literal("Gfx::Bitmap::try_create_from_serialized_byte_buffer: decode failed");
} }
if (stream.remaining() < actual_size) if (stream.remaining() < actual_size)
return Error::from_string_literal("Gfx::Bitmap::try_create_from_serialized_byte_buffer: decode failed"sv); return Error::from_string_literal("Gfx::Bitmap::try_create_from_serialized_byte_buffer: decode failed");
auto data = stream.bytes().slice(stream.offset(), actual_size); auto data = stream.bytes().slice(stream.offset(), actual_size);
@ -548,7 +548,7 @@ Gfx::ShareableBitmap Bitmap::to_shareable_bitmap() const
ErrorOr<BackingStore> Bitmap::allocate_backing_store(BitmapFormat format, IntSize const& size, int scale_factor) ErrorOr<BackingStore> Bitmap::allocate_backing_store(BitmapFormat format, IntSize const& size, int scale_factor)
{ {
if (size_would_overflow(format, size, scale_factor)) if (size_would_overflow(format, size, scale_factor))
return Error::from_string_literal("Gfx::Bitmap backing store size overflow"sv); return Error::from_string_literal("Gfx::Bitmap backing store size overflow");
auto const pitch = minimum_pitch(size.width() * scale_factor, format); auto const pitch = minimum_pitch(size.width() * scale_factor, format);
auto const data_size_in_bytes = size_in_bytes(pitch, size.height() * scale_factor); auto const data_size_in_bytes = size_in_bytes(pitch, size.height() * scale_factor);

View File

@ -998,15 +998,15 @@ size_t DDSImageDecoderPlugin::frame_count()
ErrorOr<ImageFrameDescriptor> DDSImageDecoderPlugin::frame(size_t index) ErrorOr<ImageFrameDescriptor> DDSImageDecoderPlugin::frame(size_t index)
{ {
if (index > 0) if (index > 0)
return Error::from_string_literal("DDSImageDecoderPlugin: Invalid frame index"sv); return Error::from_string_literal("DDSImageDecoderPlugin: Invalid frame index");
if (m_context->state == DDSLoadingContext::State::Error) if (m_context->state == DDSLoadingContext::State::Error)
return Error::from_string_literal("DDSImageDecoderPlugin: Decoding failed"sv); return Error::from_string_literal("DDSImageDecoderPlugin: Decoding failed");
if (m_context->state < DDSLoadingContext::State::BitmapDecoded) { if (m_context->state < DDSLoadingContext::State::BitmapDecoded) {
bool success = decode_dds(*m_context); bool success = decode_dds(*m_context);
if (!success) if (!success)
return Error::from_string_literal("DDSImageDecoderPlugin: Decoding failed"sv); return Error::from_string_literal("DDSImageDecoderPlugin: Decoding failed");
} }
VERIFY(m_context->bitmap); VERIFY(m_context->bitmap);

View File

@ -168,22 +168,22 @@ Optional<Name> Name::from_slice(ReadonlyBytes slice)
ErrorOr<Kern> Kern::from_slice(ReadonlyBytes slice) ErrorOr<Kern> Kern::from_slice(ReadonlyBytes slice)
{ {
if (slice.size() < sizeof(u32)) if (slice.size() < sizeof(u32))
return Error::from_string_literal("Invalid kern table header"sv); return Error::from_string_literal("Invalid kern table header");
// We only support the old (2x u16) version of the header // We only support the old (2x u16) version of the header
auto version = be_u16(slice.data()); auto version = be_u16(slice.data());
auto number_of_subtables = be_u16(slice.offset(sizeof(u16))); auto number_of_subtables = be_u16(slice.offset(sizeof(u16)));
if (version != 0) if (version != 0)
return Error::from_string_literal("Unsupported kern table version"sv); return Error::from_string_literal("Unsupported kern table version");
if (number_of_subtables == 0) if (number_of_subtables == 0)
return Error::from_string_literal("Kern table does not contain any subtables"sv); return Error::from_string_literal("Kern table does not contain any subtables");
// Read all subtable offsets // Read all subtable offsets
auto subtable_offsets = TRY(FixedArray<size_t>::try_create(number_of_subtables)); auto subtable_offsets = TRY(FixedArray<size_t>::try_create(number_of_subtables));
size_t offset = 2 * sizeof(u16); size_t offset = 2 * sizeof(u16);
for (size_t i = 0; i < number_of_subtables; ++i) { for (size_t i = 0; i < number_of_subtables; ++i) {
if (slice.size() < offset + Sizes::SubtableHeader) if (slice.size() < offset + Sizes::SubtableHeader)
return Error::from_string_literal("Invalid kern subtable header"sv); return Error::from_string_literal("Invalid kern subtable header");
subtable_offsets[i] = offset; subtable_offsets[i] = offset;
auto subtable_size = be_u16(slice.offset(offset + sizeof(u16))); auto subtable_size = be_u16(slice.offset(offset + sizeof(u16)));
@ -365,22 +365,22 @@ ErrorOr<NonnullRefPtr<Font>> Font::try_load_from_file(String path, unsigned inde
ErrorOr<NonnullRefPtr<Font>> Font::try_load_from_externally_owned_memory(ReadonlyBytes buffer, unsigned index) ErrorOr<NonnullRefPtr<Font>> Font::try_load_from_externally_owned_memory(ReadonlyBytes buffer, unsigned index)
{ {
if (buffer.size() < 4) if (buffer.size() < 4)
return Error::from_string_literal("Font file too small"sv); return Error::from_string_literal("Font file too small");
u32 tag = be_u32(buffer.data()); u32 tag = be_u32(buffer.data());
if (tag == tag_from_str("ttcf")) { if (tag == tag_from_str("ttcf")) {
// It's a font collection // It's a font collection
if (buffer.size() < (u32)Sizes::TTCHeaderV1 + sizeof(u32) * (index + 1)) if (buffer.size() < (u32)Sizes::TTCHeaderV1 + sizeof(u32) * (index + 1))
return Error::from_string_literal("Font file too small"sv); return Error::from_string_literal("Font file too small");
u32 offset = be_u32(buffer.offset_pointer((u32)Sizes::TTCHeaderV1 + sizeof(u32) * index)); u32 offset = be_u32(buffer.offset_pointer((u32)Sizes::TTCHeaderV1 + sizeof(u32) * index));
return try_load_from_offset(buffer, offset); return try_load_from_offset(buffer, offset);
} }
if (tag == tag_from_str("OTTO")) if (tag == tag_from_str("OTTO"))
return Error::from_string_literal("CFF fonts not supported yet"sv); return Error::from_string_literal("CFF fonts not supported yet");
if (tag != 0x00010000) if (tag != 0x00010000)
return Error::from_string_literal("Not a valid font"sv); return Error::from_string_literal("Not a valid font");
return try_load_from_offset(buffer, 0); return try_load_from_offset(buffer, 0);
} }
@ -389,10 +389,10 @@ ErrorOr<NonnullRefPtr<Font>> Font::try_load_from_externally_owned_memory(Readonl
ErrorOr<NonnullRefPtr<Font>> Font::try_load_from_offset(ReadonlyBytes buffer, u32 offset) ErrorOr<NonnullRefPtr<Font>> Font::try_load_from_offset(ReadonlyBytes buffer, u32 offset)
{ {
if (Checked<u32>::addition_would_overflow(offset, (u32)Sizes::OffsetTable)) if (Checked<u32>::addition_would_overflow(offset, (u32)Sizes::OffsetTable))
return Error::from_string_literal("Invalid offset in font header"sv); return Error::from_string_literal("Invalid offset in font header");
if (buffer.size() < offset + (u32)Sizes::OffsetTable) if (buffer.size() < offset + (u32)Sizes::OffsetTable)
return Error::from_string_literal("Font file too small"sv); return Error::from_string_literal("Font file too small");
Optional<ReadonlyBytes> opt_head_slice = {}; Optional<ReadonlyBytes> opt_head_slice = {};
Optional<ReadonlyBytes> opt_name_slice = {}; Optional<ReadonlyBytes> opt_name_slice = {};
@ -417,7 +417,7 @@ ErrorOr<NonnullRefPtr<Font>> Font::try_load_from_offset(ReadonlyBytes buffer, u3
auto num_tables = be_u16(buffer.offset_pointer(offset + (u32)Offsets::NumTables)); auto num_tables = be_u16(buffer.offset_pointer(offset + (u32)Offsets::NumTables));
if (buffer.size() < offset + (u32)Sizes::OffsetTable + num_tables * (u32)Sizes::TableRecord) if (buffer.size() < offset + (u32)Sizes::OffsetTable + num_tables * (u32)Sizes::TableRecord)
return Error::from_string_literal("Font file too small"sv); return Error::from_string_literal("Font file too small");
for (auto i = 0; i < num_tables; i++) { for (auto i = 0; i < num_tables; i++) {
u32 record_offset = offset + (u32)Sizes::OffsetTable + i * (u32)Sizes::TableRecord; u32 record_offset = offset + (u32)Sizes::OffsetTable + i * (u32)Sizes::TableRecord;
@ -426,10 +426,10 @@ ErrorOr<NonnullRefPtr<Font>> Font::try_load_from_offset(ReadonlyBytes buffer, u3
u32 table_length = be_u32(buffer.offset_pointer(record_offset + (u32)Offsets::TableRecord_Length)); u32 table_length = be_u32(buffer.offset_pointer(record_offset + (u32)Offsets::TableRecord_Length));
if (Checked<u32>::addition_would_overflow(table_offset, table_length)) if (Checked<u32>::addition_would_overflow(table_offset, table_length))
return Error::from_string_literal("Invalid table offset or length in font"sv); return Error::from_string_literal("Invalid table offset or length in font");
if (buffer.size() < table_offset + table_length) if (buffer.size() < table_offset + table_length)
return Error::from_string_literal("Font file too small"sv); return Error::from_string_literal("Font file too small");
auto buffer_here = ReadonlyBytes(buffer.offset_pointer(table_offset), table_length); auto buffer_here = ReadonlyBytes(buffer.offset_pointer(table_offset), table_length);
@ -458,39 +458,39 @@ ErrorOr<NonnullRefPtr<Font>> Font::try_load_from_offset(ReadonlyBytes buffer, u3
} }
if (!opt_head_slice.has_value() || !(opt_head = Head::from_slice(opt_head_slice.value())).has_value()) if (!opt_head_slice.has_value() || !(opt_head = Head::from_slice(opt_head_slice.value())).has_value())
return Error::from_string_literal("Could not load Head"sv); return Error::from_string_literal("Could not load Head");
auto head = opt_head.value(); auto head = opt_head.value();
if (!opt_name_slice.has_value() || !(opt_name = Name::from_slice(opt_name_slice.value())).has_value()) if (!opt_name_slice.has_value() || !(opt_name = Name::from_slice(opt_name_slice.value())).has_value())
return Error::from_string_literal("Could not load Name"sv); return Error::from_string_literal("Could not load Name");
auto name = opt_name.value(); auto name = opt_name.value();
if (!opt_hhea_slice.has_value() || !(opt_hhea = Hhea::from_slice(opt_hhea_slice.value())).has_value()) if (!opt_hhea_slice.has_value() || !(opt_hhea = Hhea::from_slice(opt_hhea_slice.value())).has_value())
return Error::from_string_literal("Could not load Hhea"sv); return Error::from_string_literal("Could not load Hhea");
auto hhea = opt_hhea.value(); auto hhea = opt_hhea.value();
if (!opt_maxp_slice.has_value() || !(opt_maxp = Maxp::from_slice(opt_maxp_slice.value())).has_value()) if (!opt_maxp_slice.has_value() || !(opt_maxp = Maxp::from_slice(opt_maxp_slice.value())).has_value())
return Error::from_string_literal("Could not load Maxp"sv); return Error::from_string_literal("Could not load Maxp");
auto maxp = opt_maxp.value(); auto maxp = opt_maxp.value();
if (!opt_hmtx_slice.has_value() || !(opt_hmtx = Hmtx::from_slice(opt_hmtx_slice.value(), maxp.num_glyphs(), hhea.number_of_h_metrics())).has_value()) if (!opt_hmtx_slice.has_value() || !(opt_hmtx = Hmtx::from_slice(opt_hmtx_slice.value(), maxp.num_glyphs(), hhea.number_of_h_metrics())).has_value())
return Error::from_string_literal("Could not load Hmtx"sv); return Error::from_string_literal("Could not load Hmtx");
auto hmtx = opt_hmtx.value(); auto hmtx = opt_hmtx.value();
if (!opt_cmap_slice.has_value() || !(opt_cmap = Cmap::from_slice(opt_cmap_slice.value())).has_value()) if (!opt_cmap_slice.has_value() || !(opt_cmap = Cmap::from_slice(opt_cmap_slice.value())).has_value())
return Error::from_string_literal("Could not load Cmap"sv); return Error::from_string_literal("Could not load Cmap");
auto cmap = opt_cmap.value(); auto cmap = opt_cmap.value();
if (!opt_loca_slice.has_value() || !(opt_loca = Loca::from_slice(opt_loca_slice.value(), maxp.num_glyphs(), head.index_to_loc_format())).has_value()) if (!opt_loca_slice.has_value() || !(opt_loca = Loca::from_slice(opt_loca_slice.value(), maxp.num_glyphs(), head.index_to_loc_format())).has_value())
return Error::from_string_literal("Could not load Loca"sv); return Error::from_string_literal("Could not load Loca");
auto loca = opt_loca.value(); auto loca = opt_loca.value();
if (!opt_glyf_slice.has_value()) if (!opt_glyf_slice.has_value())
return Error::from_string_literal("Could not load Glyf"sv); return Error::from_string_literal("Could not load Glyf");
auto glyf = Glyf(opt_glyf_slice.value()); auto glyf = Glyf(opt_glyf_slice.value());
if (!opt_os2_slice.has_value()) if (!opt_os2_slice.has_value())
return Error::from_string_literal("Could not load OS/2"sv); return Error::from_string_literal("Could not load OS/2");
auto os2 = OS2(opt_os2_slice.value()); auto os2 = OS2(opt_os2_slice.value());
Optional<Kern> kern {}; Optional<Kern> kern {};
@ -507,7 +507,7 @@ ErrorOr<NonnullRefPtr<Font>> Font::try_load_from_offset(ReadonlyBytes buffer, u3
auto subtable = opt_subtable.value(); auto subtable = opt_subtable.value();
auto platform = subtable.platform_id(); auto platform = subtable.platform_id();
if (!platform.has_value()) if (!platform.has_value())
return Error::from_string_literal("Invalid Platform ID"sv); return Error::from_string_literal("Invalid Platform ID");
if (platform.value() == Cmap::Subtable::Platform::Windows) { if (platform.value() == Cmap::Subtable::Platform::Windows) {
if (subtable.encoding_id() == (u16)Cmap::Subtable::WindowsEncoding::UnicodeFullRepertoire) { if (subtable.encoding_id() == (u16)Cmap::Subtable::WindowsEncoding::UnicodeFullRepertoire) {

View File

@ -60,12 +60,12 @@ ErrorOr<NonnullRefPtr<Font>> Font::try_load_from_externally_owned_memory(Readonl
{ {
// https://www.w3.org/TR/WOFF/#WOFFHeader // https://www.w3.org/TR/WOFF/#WOFFHeader
if (buffer.size() < WOFF_HEADER_SIZE) if (buffer.size() < WOFF_HEADER_SIZE)
return Error::from_string_literal("WOFF file too small"sv); return Error::from_string_literal("WOFF file too small");
// The signature field in the WOFF header MUST contain the "magic number" 0x774F4646. If the field does not contain this value, user agents MUST reject the file as invalid. // The signature field in the WOFF header MUST contain the "magic number" 0x774F4646. If the field does not contain this value, user agents MUST reject the file as invalid.
u32 signature = be_u32(buffer.data()); u32 signature = be_u32(buffer.data());
if (signature != WOFF_SIGNATURE) if (signature != WOFF_SIGNATURE)
return Error::from_string_literal("Invalid WOFF signature"sv); return Error::from_string_literal("Invalid WOFF signature");
// The flavor field corresponds to the "sfnt version" field found at the beginning of an sfnt file, // The flavor field corresponds to the "sfnt version" field found at the beginning of an sfnt file,
// indicating the type of font data contained. Although only fonts of type 0x00010000 (the version number 1.0 as a 16.16 fixed-point value, indicating TrueType glyph data) // indicating the type of font data contained. Although only fonts of type 0x00010000 (the version number 1.0 as a 16.16 fixed-point value, indicating TrueType glyph data)
// and 0x4F54544F (the tag 'OTTO', indicating CFF glyph data) are widely supported at present, // and 0x4F54544F (the tag 'OTTO', indicating CFF glyph data) are widely supported at present,
@ -85,17 +85,17 @@ ErrorOr<NonnullRefPtr<Font>> Font::try_load_from_externally_owned_memory(Readonl
u32 priv_offset = be_u32(buffer.offset(36)); // Offset to private data block, from beginning of WOFF file. u32 priv_offset = be_u32(buffer.offset(36)); // Offset to private data block, from beginning of WOFF file.
u32 priv_length = be_u32(buffer.offset(40)); // Length of private data block. u32 priv_length = be_u32(buffer.offset(40)); // Length of private data block.
if (length > buffer.size()) if (length > buffer.size())
return Error::from_string_literal("Invalid WOFF length"sv); return Error::from_string_literal("Invalid WOFF length");
if (reserved != 0) if (reserved != 0)
return Error::from_string_literal("Invalid WOFF reserved field"sv); return Error::from_string_literal("Invalid WOFF reserved field");
if (meta_length == 0 && meta_offset != 0) if (meta_length == 0 && meta_offset != 0)
return Error::from_string_literal("Invalid WOFF meta block offset"sv); return Error::from_string_literal("Invalid WOFF meta block offset");
if (priv_length == 0 && priv_offset != 0) if (priv_length == 0 && priv_offset != 0)
return Error::from_string_literal("Invalid WOFF private block offset"sv); return Error::from_string_literal("Invalid WOFF private block offset");
if (WOFF_HEADER_SIZE + num_tables * WOFF_TABLE_SIZE > length) if (WOFF_HEADER_SIZE + num_tables * WOFF_TABLE_SIZE > length)
return Error::from_string_literal("Truncated WOFF table directory"sv); return Error::from_string_literal("Truncated WOFF table directory");
if (total_sfnt_size > 10 * MiB) if (total_sfnt_size > 10 * MiB)
return Error::from_string_literal("Uncompressed font is more than 10 MiB"sv); return Error::from_string_literal("Uncompressed font is more than 10 MiB");
auto font_buffer = TRY(ByteBuffer::create_zeroed(total_sfnt_size)); auto font_buffer = TRY(ByteBuffer::create_zeroed(total_sfnt_size));
// ISO-IEC 14496-22:2019 4.5.1 Offset table // ISO-IEC 14496-22:2019 4.5.1 Offset table
@ -116,19 +116,19 @@ ErrorOr<NonnullRefPtr<Font>> Font::try_load_from_externally_owned_memory(Readonl
u32 orig_checksum = be_u32(buffer.offset(base_offset + 16)); u32 orig_checksum = be_u32(buffer.offset(base_offset + 16));
if ((size_t)offset + comp_length > length) if ((size_t)offset + comp_length > length)
return Error::from_string_literal("Truncated WOFF table"sv); return Error::from_string_literal("Truncated WOFF table");
if (font_buffer_offset + orig_length > font_buffer.size()) if (font_buffer_offset + orig_length > font_buffer.size())
return Error::from_string_literal("Uncompressed WOFF table too big"sv); return Error::from_string_literal("Uncompressed WOFF table too big");
if (comp_length < orig_length) { if (comp_length < orig_length) {
auto decompressed = Compress::Zlib::decompress_all(buffer.slice(offset, comp_length)); auto decompressed = Compress::Zlib::decompress_all(buffer.slice(offset, comp_length));
if (!decompressed.has_value()) if (!decompressed.has_value())
return Error::from_string_literal("Could not decompress WOFF table"sv); return Error::from_string_literal("Could not decompress WOFF table");
if (orig_length != decompressed->size()) if (orig_length != decompressed->size())
return Error::from_string_literal("Invalid decompressed WOFF table length"sv); return Error::from_string_literal("Invalid decompressed WOFF table length");
font_buffer.overwrite(font_buffer_offset, decompressed->data(), orig_length); font_buffer.overwrite(font_buffer_offset, decompressed->data(), orig_length);
} else { } else {
if (comp_length != orig_length) if (comp_length != orig_length)
return Error::from_string_literal("Invalid uncompressed WOFF table length"sv); return Error::from_string_literal("Invalid uncompressed WOFF table length");
font_buffer.overwrite(font_buffer_offset, buffer.data() + offset, orig_length); font_buffer.overwrite(font_buffer_offset, buffer.data() + offset, orig_length);
} }

View File

@ -695,20 +695,20 @@ size_t GIFImageDecoderPlugin::frame_count()
ErrorOr<ImageFrameDescriptor> GIFImageDecoderPlugin::frame(size_t index) ErrorOr<ImageFrameDescriptor> GIFImageDecoderPlugin::frame(size_t index)
{ {
if (m_context->error_state >= GIFLoadingContext::ErrorState::FailedToDecodeAnyFrame) { if (m_context->error_state >= GIFLoadingContext::ErrorState::FailedToDecodeAnyFrame) {
return Error::from_string_literal("GIFImageDecoderPlugin: Decoding failed"sv); return Error::from_string_literal("GIFImageDecoderPlugin: Decoding failed");
} }
if (m_context->state < GIFLoadingContext::State::FrameDescriptorsLoaded) { if (m_context->state < GIFLoadingContext::State::FrameDescriptorsLoaded) {
if (!load_gif_frame_descriptors(*m_context)) { if (!load_gif_frame_descriptors(*m_context)) {
m_context->error_state = GIFLoadingContext::ErrorState::FailedToLoadFrameDescriptors; m_context->error_state = GIFLoadingContext::ErrorState::FailedToLoadFrameDescriptors;
return Error::from_string_literal("GIFImageDecoderPlugin: Decoding failed"sv); return Error::from_string_literal("GIFImageDecoderPlugin: Decoding failed");
} }
} }
if (m_context->error_state == GIFLoadingContext::ErrorState::NoError && !decode_frame(*m_context, index)) { if (m_context->error_state == GIFLoadingContext::ErrorState::NoError && !decode_frame(*m_context, index)) {
if (m_context->state < GIFLoadingContext::State::FrameComplete || !decode_frame(*m_context, 0)) { if (m_context->state < GIFLoadingContext::State::FrameComplete || !decode_frame(*m_context, 0)) {
m_context->error_state = GIFLoadingContext::ErrorState::FailedToDecodeAnyFrame; m_context->error_state = GIFLoadingContext::ErrorState::FailedToDecodeAnyFrame;
return Error::from_string_literal("GIFImageDecoderPlugin: Decoding failed"sv); return Error::from_string_literal("GIFImageDecoderPlugin: Decoding failed");
} }
m_context->error_state = GIFLoadingContext::ErrorState::FailedToDecodeAllFrames; m_context->error_state = GIFLoadingContext::ErrorState::FailedToDecodeAllFrames;
} }

View File

@ -342,17 +342,17 @@ size_t ICOImageDecoderPlugin::frame_count()
ErrorOr<ImageFrameDescriptor> ICOImageDecoderPlugin::frame(size_t index) ErrorOr<ImageFrameDescriptor> ICOImageDecoderPlugin::frame(size_t index)
{ {
if (index > 0) if (index > 0)
return Error::from_string_literal("ICOImageDecoderPlugin: Invalid frame index"sv); return Error::from_string_literal("ICOImageDecoderPlugin: Invalid frame index");
if (m_context->state == ICOLoadingContext::State::Error) if (m_context->state == ICOLoadingContext::State::Error)
return Error::from_string_literal("ICOImageDecoderPlugin: Decoding failed"sv); return Error::from_string_literal("ICOImageDecoderPlugin: Decoding failed");
if (m_context->state < ICOLoadingContext::State::BitmapDecoded) { if (m_context->state < ICOLoadingContext::State::BitmapDecoded) {
// NOTE: This forces the chunk decoding to happen. // NOTE: This forces the chunk decoding to happen.
bool success = load_ico_bitmap(*m_context, {}); bool success = load_ico_bitmap(*m_context, {});
if (!success) { if (!success) {
m_context->state = ICOLoadingContext::State::Error; m_context->state = ICOLoadingContext::State::Error;
return Error::from_string_literal("ICOImageDecoderPlugin: Decoding failed"sv); return Error::from_string_literal("ICOImageDecoderPlugin: Decoding failed");
} }
m_context->state = ICOLoadingContext::State::BitmapDecoded; m_context->state = ICOLoadingContext::State::BitmapDecoded;
} }

View File

@ -1285,15 +1285,15 @@ size_t JPGImageDecoderPlugin::frame_count()
ErrorOr<ImageFrameDescriptor> JPGImageDecoderPlugin::frame(size_t index) ErrorOr<ImageFrameDescriptor> JPGImageDecoderPlugin::frame(size_t index)
{ {
if (index > 0) if (index > 0)
return Error::from_string_literal("JPGImageDecoderPlugin: Invalid frame index"sv); return Error::from_string_literal("JPGImageDecoderPlugin: Invalid frame index");
if (m_context->state == JPGLoadingContext::State::Error) if (m_context->state == JPGLoadingContext::State::Error)
return Error::from_string_literal("JPGImageDecoderPlugin: Decoding failed"sv); return Error::from_string_literal("JPGImageDecoderPlugin: Decoding failed");
if (m_context->state < JPGLoadingContext::State::BitmapDecoded) { if (m_context->state < JPGLoadingContext::State::BitmapDecoded) {
if (!decode_jpg(*m_context)) { if (!decode_jpg(*m_context)) {
m_context->state = JPGLoadingContext::State::Error; m_context->state = JPGLoadingContext::State::Error;
return Error::from_string_literal("JPGImageDecoderPlugin: Decoding failed"sv); return Error::from_string_literal("JPGImageDecoderPlugin: Decoding failed");
} }
m_context->state = JPGLoadingContext::State::BitmapDecoded; m_context->state = JPGLoadingContext::State::BitmapDecoded;
} }

View File

@ -407,7 +407,7 @@ NEVER_INLINE FLATTEN static ErrorOr<void> unfilter(PNGLoadingContext& context)
for (int i = 0; i < context.width; ++i) { for (int i = 0; i < context.width; ++i) {
auto& pixel = (Pixel&)context.bitmap->scanline(y)[i]; auto& pixel = (Pixel&)context.bitmap->scanline(y)[i];
if (palette_index[i] >= context.palette_data.size()) if (palette_index[i] >= context.palette_data.size())
return Error::from_string_literal("PNGImageDecoderPlugin: Palette index out of range"sv); return Error::from_string_literal("PNGImageDecoderPlugin: Palette index out of range");
auto& color = context.palette_data.at((int)palette_index[i]); auto& color = context.palette_data.at((int)palette_index[i]);
auto transparency = context.palette_transparency_data.size() >= palette_index[i] + 1u auto transparency = context.palette_transparency_data.size() >= palette_index[i] + 1u
? context.palette_transparency_data.data()[palette_index[i]] ? context.palette_transparency_data.data()[palette_index[i]]
@ -428,7 +428,7 @@ NEVER_INLINE FLATTEN static ErrorOr<void> unfilter(PNGLoadingContext& context)
auto palette_index = (palette_indices[i / pixels_per_byte] >> bit_offset) & mask; auto palette_index = (palette_indices[i / pixels_per_byte] >> bit_offset) & mask;
auto& pixel = (Pixel&)context.bitmap->scanline(y)[i]; auto& pixel = (Pixel&)context.bitmap->scanline(y)[i];
if ((size_t)palette_index >= context.palette_data.size()) if ((size_t)palette_index >= context.palette_data.size())
return Error::from_string_literal("PNGImageDecoderPlugin: Palette index out of range"sv); return Error::from_string_literal("PNGImageDecoderPlugin: Palette index out of range");
auto& color = context.palette_data.at(palette_index); auto& color = context.palette_data.at(palette_index);
auto transparency = context.palette_transparency_data.size() >= palette_index + 1u auto transparency = context.palette_transparency_data.size() >= palette_index + 1u
? context.palette_transparency_data.data()[palette_index] ? context.palette_transparency_data.data()[palette_index]
@ -578,23 +578,23 @@ static ErrorOr<void> decode_png_bitmap_simple(PNGLoadingContext& context)
PNG::FilterType filter; PNG::FilterType filter;
if (!streamer.read(filter)) { if (!streamer.read(filter)) {
context.state = PNGLoadingContext::State::Error; context.state = PNGLoadingContext::State::Error;
return Error::from_string_literal("PNGImageDecoderPlugin: Decoding failed"sv); return Error::from_string_literal("PNGImageDecoderPlugin: Decoding failed");
} }
if (to_underlying(filter) > 4) { if (to_underlying(filter) > 4) {
context.state = PNGLoadingContext::State::Error; context.state = PNGLoadingContext::State::Error;
return Error::from_string_literal("PNGImageDecoderPlugin: Invalid PNG filter"sv); return Error::from_string_literal("PNGImageDecoderPlugin: Invalid PNG filter");
} }
context.scanlines.append({ filter }); context.scanlines.append({ filter });
auto& scanline_buffer = context.scanlines.last().data; auto& scanline_buffer = context.scanlines.last().data;
auto row_size = context.compute_row_size_for_width(context.width); auto row_size = context.compute_row_size_for_width(context.width);
if (row_size.has_overflow()) if (row_size.has_overflow())
return Error::from_string_literal("PNGImageDecoderPlugin: Row size overflow"sv); return Error::from_string_literal("PNGImageDecoderPlugin: Row size overflow");
if (!streamer.wrap_bytes(scanline_buffer, row_size.value())) { if (!streamer.wrap_bytes(scanline_buffer, row_size.value())) {
context.state = PNGLoadingContext::State::Error; context.state = PNGLoadingContext::State::Error;
return Error::from_string_literal("PNGImageDecoderPlugin: Decoding failed"sv); return Error::from_string_literal("PNGImageDecoderPlugin: Decoding failed");
} }
} }
@ -673,12 +673,12 @@ static ErrorOr<void> decode_adam7_pass(PNGLoadingContext& context, Streamer& str
PNG::FilterType filter; PNG::FilterType filter;
if (!streamer.read(filter)) { if (!streamer.read(filter)) {
context.state = PNGLoadingContext::State::Error; context.state = PNGLoadingContext::State::Error;
return Error::from_string_literal("PNGImageDecoderPlugin: Decoding failed"sv); return Error::from_string_literal("PNGImageDecoderPlugin: Decoding failed");
} }
if (to_underlying(filter) > 4) { if (to_underlying(filter) > 4) {
context.state = PNGLoadingContext::State::Error; context.state = PNGLoadingContext::State::Error;
return Error::from_string_literal("PNGImageDecoderPlugin: Invalid PNG filter"sv); return Error::from_string_literal("PNGImageDecoderPlugin: Invalid PNG filter");
} }
subimage_context.scanlines.append({ filter }); subimage_context.scanlines.append({ filter });
@ -686,10 +686,10 @@ static ErrorOr<void> decode_adam7_pass(PNGLoadingContext& context, Streamer& str
auto row_size = context.compute_row_size_for_width(subimage_context.width); auto row_size = context.compute_row_size_for_width(subimage_context.width);
if (row_size.has_overflow()) if (row_size.has_overflow())
return Error::from_string_literal("PNGImageDecoderPlugin: Row size overflow"sv); return Error::from_string_literal("PNGImageDecoderPlugin: Row size overflow");
if (!streamer.wrap_bytes(scanline_buffer, row_size.value())) { if (!streamer.wrap_bytes(scanline_buffer, row_size.value())) {
context.state = PNGLoadingContext::State::Error; context.state = PNGLoadingContext::State::Error;
return Error::from_string_literal("PNGImageDecoderPlugin: Decoding failed"sv); return Error::from_string_literal("PNGImageDecoderPlugin: Decoding failed");
} }
} }
@ -718,22 +718,22 @@ static ErrorOr<void> decode_png_bitmap(PNGLoadingContext& context)
{ {
if (context.state < PNGLoadingContext::State::ChunksDecoded) { if (context.state < PNGLoadingContext::State::ChunksDecoded) {
if (!decode_png_chunks(context)) if (!decode_png_chunks(context))
return Error::from_string_literal("PNGImageDecoderPlugin: Decoding failed"sv); return Error::from_string_literal("PNGImageDecoderPlugin: Decoding failed");
} }
if (context.state >= PNGLoadingContext::State::BitmapDecoded) if (context.state >= PNGLoadingContext::State::BitmapDecoded)
return {}; return {};
if (context.width == -1 || context.height == -1) if (context.width == -1 || context.height == -1)
return Error::from_string_literal("PNGImageDecoderPlugin: Didn't see an IHDR chunk."sv); return Error::from_string_literal("PNGImageDecoderPlugin: Didn't see an IHDR chunk.");
if (context.color_type == PNG::ColorType::IndexedColor && context.palette_data.is_empty()) if (context.color_type == PNG::ColorType::IndexedColor && context.palette_data.is_empty())
return Error::from_string_literal("PNGImageDecoderPlugin: Didn't see a PLTE chunk for a palletized image, or it was empty."sv); return Error::from_string_literal("PNGImageDecoderPlugin: Didn't see a PLTE chunk for a palletized image, or it was empty.");
auto result = Compress::Zlib::decompress_all(context.compressed_data.span()); auto result = Compress::Zlib::decompress_all(context.compressed_data.span());
if (!result.has_value()) { if (!result.has_value()) {
context.state = PNGLoadingContext::State::Error; context.state = PNGLoadingContext::State::Error;
return Error::from_string_literal("PNGImageDecoderPlugin: Decompression failed"sv); return Error::from_string_literal("PNGImageDecoderPlugin: Decompression failed");
} }
context.decompression_buffer = &result.value(); context.decompression_buffer = &result.value();
context.compressed_data.clear(); context.compressed_data.clear();
@ -748,7 +748,7 @@ static ErrorOr<void> decode_png_bitmap(PNGLoadingContext& context)
break; break;
default: default:
context.state = PNGLoadingContext::State::Error; context.state = PNGLoadingContext::State::Error;
return Error::from_string_literal("PNGImageDecoderPlugin: Invalid interlace method"sv); return Error::from_string_literal("PNGImageDecoderPlugin: Invalid interlace method");
} }
context.decompression_buffer = nullptr; context.decompression_buffer = nullptr;
@ -960,10 +960,10 @@ size_t PNGImageDecoderPlugin::frame_count()
ErrorOr<ImageFrameDescriptor> PNGImageDecoderPlugin::frame(size_t index) ErrorOr<ImageFrameDescriptor> PNGImageDecoderPlugin::frame(size_t index)
{ {
if (index > 0) if (index > 0)
return Error::from_string_literal("PNGImageDecoderPlugin: Invalid frame index"sv); return Error::from_string_literal("PNGImageDecoderPlugin: Invalid frame index");
if (m_context->state == PNGLoadingContext::State::Error) if (m_context->state == PNGLoadingContext::State::Error)
return Error::from_string_literal("PNGImageDecoderPlugin: Decoding failed"sv); return Error::from_string_literal("PNGImageDecoderPlugin: Decoding failed");
if (m_context->state < PNGLoadingContext::State::BitmapDecoded) { if (m_context->state < PNGLoadingContext::State::BitmapDecoded) {
// NOTE: This forces the chunk decoding to happen. // NOTE: This forces the chunk decoding to happen.

View File

@ -145,15 +145,15 @@ template<typename TContext>
ErrorOr<ImageFrameDescriptor> PortableImageDecoderPlugin<TContext>::frame(size_t index) ErrorOr<ImageFrameDescriptor> PortableImageDecoderPlugin<TContext>::frame(size_t index)
{ {
if (index > 0) if (index > 0)
return Error::from_string_literal("PortableImageDecoderPlugin: Invalid frame index"sv); return Error::from_string_literal("PortableImageDecoderPlugin: Invalid frame index");
if (m_context->state == TContext::State::Error) if (m_context->state == TContext::State::Error)
return Error::from_string_literal("PortableImageDecoderPlugin: Decoding failed"sv); return Error::from_string_literal("PortableImageDecoderPlugin: Decoding failed");
if (m_context->state < TContext::State::Decoded) { if (m_context->state < TContext::State::Decoded) {
bool success = decode(*m_context); bool success = decode(*m_context);
if (!success) if (!success)
return Error::from_string_literal("PortableImageDecoderPlugin: Decoding failed"sv); return Error::from_string_literal("PortableImageDecoderPlugin: Decoding failed");
} }
VERIFY(m_context->bitmap); VERIFY(m_context->bitmap);

View File

@ -26,9 +26,9 @@ static ErrorOr<QOIHeader> decode_qoi_header(InputMemoryStream& stream)
QOIHeader header; QOIHeader header;
stream >> Bytes { &header, sizeof(header) }; stream >> Bytes { &header, sizeof(header) };
if (stream.handle_any_error()) if (stream.handle_any_error())
return Error::from_string_literal("Invalid QOI image: end of stream while reading header"sv); return Error::from_string_literal("Invalid QOI image: end of stream while reading header");
if (StringView { header.magic, array_size(header.magic) } != QOI_MAGIC) if (StringView { header.magic, array_size(header.magic) } != QOI_MAGIC)
return Error::from_string_literal("Invalid QOI image: incorrect header magic"sv); return Error::from_string_literal("Invalid QOI image: incorrect header magic");
header.width = AK::convert_between_host_and_big_endian(header.width); header.width = AK::convert_between_host_and_big_endian(header.width);
header.height = AK::convert_between_host_and_big_endian(header.height); header.height = AK::convert_between_host_and_big_endian(header.height);
return header; return header;
@ -39,7 +39,7 @@ static ErrorOr<Color> decode_qoi_op_rgb(InputMemoryStream& stream, Color pixel)
u8 bytes[4]; u8 bytes[4];
stream >> Bytes { &bytes, array_size(bytes) }; stream >> Bytes { &bytes, array_size(bytes) };
if (stream.handle_any_error()) if (stream.handle_any_error())
return Error::from_string_literal("Invalid QOI image: end of stream while reading QOI_OP_RGB chunk"sv); return Error::from_string_literal("Invalid QOI image: end of stream while reading QOI_OP_RGB chunk");
VERIFY(bytes[0] == QOI_OP_RGB); VERIFY(bytes[0] == QOI_OP_RGB);
// The alpha value remains unchanged from the previous pixel. // The alpha value remains unchanged from the previous pixel.
@ -51,7 +51,7 @@ static ErrorOr<Color> decode_qoi_op_rgba(InputMemoryStream& stream)
u8 bytes[5]; u8 bytes[5];
stream >> Bytes { &bytes, array_size(bytes) }; stream >> Bytes { &bytes, array_size(bytes) };
if (stream.handle_any_error()) if (stream.handle_any_error())
return Error::from_string_literal("Invalid QOI image: end of stream while reading QOI_OP_RGBA chunk"sv); return Error::from_string_literal("Invalid QOI image: end of stream while reading QOI_OP_RGBA chunk");
VERIFY(bytes[0] == QOI_OP_RGBA); VERIFY(bytes[0] == QOI_OP_RGBA);
return Color { bytes[1], bytes[2], bytes[3], bytes[4] }; return Color { bytes[1], bytes[2], bytes[3], bytes[4] };
} }
@ -61,7 +61,7 @@ static ErrorOr<u8> decode_qoi_op_index(InputMemoryStream& stream)
u8 byte; u8 byte;
stream >> byte; stream >> byte;
if (stream.handle_any_error()) if (stream.handle_any_error())
return Error::from_string_literal("Invalid QOI image: end of stream while reading QOI_OP_INDEX chunk"sv); return Error::from_string_literal("Invalid QOI image: end of stream while reading QOI_OP_INDEX chunk");
VERIFY((byte & QOI_MASK_2) == QOI_OP_INDEX); VERIFY((byte & QOI_MASK_2) == QOI_OP_INDEX);
u8 index = byte & ~QOI_MASK_2; u8 index = byte & ~QOI_MASK_2;
VERIFY(index <= 63); VERIFY(index <= 63);
@ -73,7 +73,7 @@ static ErrorOr<Color> decode_qoi_op_diff(InputMemoryStream& stream, Color pixel)
u8 byte; u8 byte;
stream >> byte; stream >> byte;
if (stream.handle_any_error()) if (stream.handle_any_error())
return Error::from_string_literal("Invalid QOI image: end of stream while reading QOI_OP_DIFF chunk"sv); return Error::from_string_literal("Invalid QOI image: end of stream while reading QOI_OP_DIFF chunk");
VERIFY((byte & QOI_MASK_2) == QOI_OP_DIFF); VERIFY((byte & QOI_MASK_2) == QOI_OP_DIFF);
u8 dr = (byte & 0b00110000) >> 4; u8 dr = (byte & 0b00110000) >> 4;
u8 dg = (byte & 0b00001100) >> 2; u8 dg = (byte & 0b00001100) >> 2;
@ -94,7 +94,7 @@ static ErrorOr<Color> decode_qoi_op_luma(InputMemoryStream& stream, Color pixel)
u8 bytes[2]; u8 bytes[2];
stream >> Bytes { &bytes, array_size(bytes) }; stream >> Bytes { &bytes, array_size(bytes) };
if (stream.handle_any_error()) if (stream.handle_any_error())
return Error::from_string_literal("Invalid QOI image: end of stream while reading QOI_OP_LUMA chunk"sv); return Error::from_string_literal("Invalid QOI image: end of stream while reading QOI_OP_LUMA chunk");
VERIFY((bytes[0] & QOI_MASK_2) == QOI_OP_LUMA); VERIFY((bytes[0] & QOI_MASK_2) == QOI_OP_LUMA);
u8 diff_green = (bytes[0] & ~QOI_MASK_2); u8 diff_green = (bytes[0] & ~QOI_MASK_2);
u8 dr_dg = (bytes[1] & 0b11110000) >> 4; u8 dr_dg = (bytes[1] & 0b11110000) >> 4;
@ -114,7 +114,7 @@ static ErrorOr<u8> decode_qoi_op_run(InputMemoryStream& stream)
u8 byte; u8 byte;
stream >> byte; stream >> byte;
if (stream.handle_any_error()) if (stream.handle_any_error())
return Error::from_string_literal("Invalid QOI image: end of stream while reading QOI_OP_RUN chunk"sv); return Error::from_string_literal("Invalid QOI image: end of stream while reading QOI_OP_RUN chunk");
VERIFY((byte & QOI_MASK_2) == QOI_OP_RUN); VERIFY((byte & QOI_MASK_2) == QOI_OP_RUN);
u8 run = byte & ~QOI_MASK_2; u8 run = byte & ~QOI_MASK_2;
@ -123,7 +123,7 @@ static ErrorOr<u8> decode_qoi_op_run(InputMemoryStream& stream)
// Note that the run-lengths 63 and 64 (b111110 and b111111) are illegal as they are occupied by the QOI_OP_RGB and QOI_OP_RGBA tags. // Note that the run-lengths 63 and 64 (b111110 and b111111) are illegal as they are occupied by the QOI_OP_RGB and QOI_OP_RGBA tags.
if (run == QOI_OP_RGB || run == QOI_OP_RGBA) if (run == QOI_OP_RGB || run == QOI_OP_RGBA)
return Error::from_string_literal("Invalid QOI image: illegal run length"sv); return Error::from_string_literal("Invalid QOI image: illegal run length");
VERIFY(run >= 1 && run <= 62); VERIFY(run >= 1 && run <= 62);
return run; return run;
@ -134,11 +134,11 @@ static ErrorOr<void> decode_qoi_end_marker(InputMemoryStream& stream)
u8 bytes[array_size(END_MARKER)]; u8 bytes[array_size(END_MARKER)];
stream >> Bytes { &bytes, array_size(bytes) }; stream >> Bytes { &bytes, array_size(bytes) };
if (stream.handle_any_error()) if (stream.handle_any_error())
return Error::from_string_literal("Invalid QOI image: end of stream while reading end marker"sv); return Error::from_string_literal("Invalid QOI image: end of stream while reading end marker");
if (!stream.eof()) if (!stream.eof())
return Error::from_string_literal("Invalid QOI image: expected end of stream but more bytes are available"sv); return Error::from_string_literal("Invalid QOI image: expected end of stream but more bytes are available");
if (memcmp(&END_MARKER, &bytes, array_size(bytes)) != 0) if (memcmp(&END_MARKER, &bytes, array_size(bytes)) != 0)
return Error::from_string_literal("Invalid QOI image: incorrect end marker"sv); return Error::from_string_literal("Invalid QOI image: incorrect end marker");
return {}; return {};
} }
@ -146,9 +146,9 @@ static ErrorOr<NonnullRefPtr<Bitmap>> decode_qoi_image(InputMemoryStream& stream
{ {
// FIXME: Why is Gfx::Bitmap's size signed? Makes no sense whatsoever. // FIXME: Why is Gfx::Bitmap's size signed? Makes no sense whatsoever.
if (width > NumericLimits<int>::max()) if (width > NumericLimits<int>::max())
return Error::from_string_literal("Cannot create bitmap for QOI image of valid size, width exceeds maximum Gfx::Bitmap width"sv); return Error::from_string_literal("Cannot create bitmap for QOI image of valid size, width exceeds maximum Gfx::Bitmap width");
if (height > NumericLimits<int>::max()) if (height > NumericLimits<int>::max())
return Error::from_string_literal("Cannot create bitmap for QOI image of valid size, height exceeds maximum Gfx::Bitmap height"sv); return Error::from_string_literal("Cannot create bitmap for QOI image of valid size, height exceeds maximum Gfx::Bitmap height");
auto bitmap = TRY(Bitmap::try_create(BitmapFormat::BGRA8888, { width, height })); auto bitmap = TRY(Bitmap::try_create(BitmapFormat::BGRA8888, { width, height }));
@ -163,7 +163,7 @@ static ErrorOr<NonnullRefPtr<Bitmap>> decode_qoi_image(InputMemoryStream& stream
if (run == 0) { if (run == 0) {
u8 tag = stream.peek_or_error(); u8 tag = stream.peek_or_error();
if (stream.handle_any_error()) if (stream.handle_any_error())
return Error::from_string_literal("Invalid QOI image: end of stream while reading chunk tag"sv); return Error::from_string_literal("Invalid QOI image: end of stream while reading chunk tag");
if (tag == QOI_OP_RGB) if (tag == QOI_OP_RGB)
pixel = TRY(decode_qoi_op_rgb(stream, pixel)); pixel = TRY(decode_qoi_op_rgb(stream, pixel));
else if (tag == QOI_OP_RGBA) else if (tag == QOI_OP_RGBA)
@ -177,7 +177,7 @@ static ErrorOr<NonnullRefPtr<Bitmap>> decode_qoi_image(InputMemoryStream& stream
else if ((tag & QOI_MASK_2) == QOI_OP_RUN) else if ((tag & QOI_MASK_2) == QOI_OP_RUN)
run = TRY(decode_qoi_op_run(stream)); run = TRY(decode_qoi_op_run(stream));
else else
return Error::from_string_literal("Invalid QOI image: unknown chunk tag"sv); return Error::from_string_literal("Invalid QOI image: unknown chunk tag");
} }
auto index_position = (pixel.red() * 3 + pixel.green() * 5 + pixel.blue() * 7 + pixel.alpha() * 11) % 64; auto index_position = (pixel.red() * 3 + pixel.green() * 5 + pixel.blue() * 7 + pixel.alpha() * 11) % 64;
previous_pixels[index_position] = pixel; previous_pixels[index_position] = pixel;
@ -232,7 +232,7 @@ bool QOIImageDecoderPlugin::sniff()
ErrorOr<ImageFrameDescriptor> QOIImageDecoderPlugin::frame(size_t index) ErrorOr<ImageFrameDescriptor> QOIImageDecoderPlugin::frame(size_t index)
{ {
if (index > 0) if (index > 0)
return Error::from_string_literal("Invalid frame index"sv); return Error::from_string_literal("Invalid frame index");
if (m_context->state == QOILoadingContext::State::NotDecoded) { if (m_context->state == QOILoadingContext::State::NotDecoded) {
InputMemoryStream stream { { m_context->data, m_context->data_size } }; InputMemoryStream stream { { m_context->data, m_context->data_size } };

View File

@ -56,7 +56,7 @@ ErrorOr<void> decode(Decoder& decoder, Gfx::ShareableBitmap& shareable_bitmap)
u32 raw_bitmap_format; u32 raw_bitmap_format;
TRY(decoder.decode(raw_bitmap_format)); TRY(decoder.decode(raw_bitmap_format));
if (!Gfx::is_valid_bitmap_format(raw_bitmap_format)) if (!Gfx::is_valid_bitmap_format(raw_bitmap_format))
return Error::from_string_literal("IPC: Invalid Gfx::ShareableBitmap format"sv); return Error::from_string_literal("IPC: Invalid Gfx::ShareableBitmap format");
auto bitmap_format = (Gfx::BitmapFormat)raw_bitmap_format; auto bitmap_format = (Gfx::BitmapFormat)raw_bitmap_format;
Vector<Gfx::ARGB32> palette; Vector<Gfx::ARGB32> palette;
if (Gfx::Bitmap::is_indexed(bitmap_format)) { if (Gfx::Bitmap::is_indexed(bitmap_format)) {

View File

@ -30,7 +30,7 @@ ErrorOr<void> ConnectionBase::post_message(MessageBuffer buffer)
// NOTE: If this connection is being shut down, but has not yet been destroyed, // NOTE: If this connection is being shut down, but has not yet been destroyed,
// the socket will be closed. Don't try to send more messages. // the socket will be closed. Don't try to send more messages.
if (!m_socket->is_open()) if (!m_socket->is_open())
return Error::from_string_literal("Trying to post_message during IPC shutdown"sv); return Error::from_string_literal("Trying to post_message during IPC shutdown");
// Prepend the message size. // Prepend the message size.
uint32_t message_size = buffer.data.size(); uint32_t message_size = buffer.data.size();
@ -57,9 +57,9 @@ ErrorOr<void> ConnectionBase::post_message(MessageBuffer buffer)
shutdown_with_error(error); shutdown_with_error(error);
switch (error.code()) { switch (error.code()) {
case EPIPE: case EPIPE:
return Error::from_string_literal("IPC::Connection::post_message: Disconnected from peer"sv); return Error::from_string_literal("IPC::Connection::post_message: Disconnected from peer");
case EAGAIN: case EAGAIN:
return Error::from_string_literal("IPC::Connection::post_message: Peer buffer overflowed"sv); return Error::from_string_literal("IPC::Connection::post_message: Peer buffer overflowed");
default: default:
return Error::from_syscall("IPC::Connection::post_message write"sv, -error.code()); return Error::from_syscall("IPC::Connection::post_message write"sv, -error.code());
} }
@ -141,7 +141,7 @@ ErrorOr<Vector<u8>> ConnectionBase::read_as_much_as_possible_from_socket_without
deferred_invoke([this] { shutdown(); }); deferred_invoke([this] { shutdown(); });
if (!bytes.is_empty()) if (!bytes.is_empty())
break; break;
return Error::from_string_literal("IPC connection EOF"sv); return Error::from_string_literal("IPC connection EOF");
} }
bytes.append(bytes_read.data(), bytes_read.size()); bytes.append(bytes_read.data(), bytes_read.size());
@ -169,7 +169,7 @@ ErrorOr<void> ConnectionBase::drain_messages_from_peer()
auto remaining_bytes = TRY(ByteBuffer::copy(bytes.span().slice(index))); auto remaining_bytes = TRY(ByteBuffer::copy(bytes.span().slice(index)));
if (!m_unprocessed_bytes.is_empty()) { if (!m_unprocessed_bytes.is_empty()) {
shutdown(); shutdown();
return Error::from_string_literal("drain_messages_from_peer: Already have unprocessed bytes"sv); return Error::from_string_literal("drain_messages_from_peer: Already have unprocessed bytes");
} }
m_unprocessed_bytes = move(remaining_bytes); m_unprocessed_bytes = move(remaining_bytes);
} }

View File

@ -58,7 +58,7 @@ public:
u32 size; u32 size;
TRY(decode(size)); TRY(decode(size));
if (size > NumericLimits<i32>::max()) if (size > NumericLimits<i32>::max())
return Error::from_string_literal("IPC: Invalid HashMap size"sv); return Error::from_string_literal("IPC: Invalid HashMap size");
for (size_t i = 0; i < size; ++i) { for (size_t i = 0; i < size; ++i) {
K key; K key;
@ -76,7 +76,7 @@ public:
u32 size; u32 size;
TRY(decode(size)); TRY(decode(size));
if (size > NumericLimits<i32>::max()) if (size > NumericLimits<i32>::max())
return Error::from_string_literal("IPC: Invalid HashMap size"sv); return Error::from_string_literal("IPC: Invalid HashMap size");
for (size_t i = 0; i < size; ++i) { for (size_t i = 0; i < size; ++i) {
K key; K key;
@ -109,7 +109,7 @@ public:
u64 size; u64 size;
TRY(decode(size)); TRY(decode(size));
if (size > NumericLimits<i32>::max()) if (size > NumericLimits<i32>::max())
return Error::from_string_literal("IPC: Invalid Vector size"sv); return Error::from_string_literal("IPC: Invalid Vector size");
VERIFY(vector.is_empty()); VERIFY(vector.is_empty());
TRY(vector.try_ensure_capacity(size)); TRY(vector.try_ensure_capacity(size));
for (size_t i = 0; i < size; ++i) { for (size_t i = 0; i < size; ++i) {

View File

@ -90,7 +90,7 @@ ErrorOr<void> Database::add_schema(SchemaDef const& schema)
VERIFY(is_open()); VERIFY(is_open());
if (!m_schemas->insert(schema.key())) { if (!m_schemas->insert(schema.key())) {
warnln("Duplicate schema name {}"sv, schema.name()); warnln("Duplicate schema name {}"sv, schema.name());
return Error::from_string_literal("Duplicate schema name"sv); return Error::from_string_literal("Duplicate schema name");
} }
return {}; return {};
} }
@ -127,7 +127,7 @@ ErrorOr<void> Database::add_table(TableDef& table)
VERIFY(is_open()); VERIFY(is_open());
if (!m_tables->insert(table.key())) { if (!m_tables->insert(table.key())) {
warnln("Duplicate table name '{}'.'{}'"sv, table.parent()->name(), table.name()); warnln("Duplicate table name '{}'.'{}'"sv, table.parent()->name(), table.name());
return Error::from_string_literal("Duplicate table name"sv); return Error::from_string_literal("Duplicate table name");
} }
for (auto& column : table.columns()) { for (auto& column : table.columns()) {
VERIFY(m_table_columns->insert(column.key())); VERIFY(m_table_columns->insert(column.key()));
@ -159,7 +159,7 @@ ErrorOr<RefPtr<TableDef>> Database::get_table(String const& schema, String const
auto schema_def = TRY(get_schema(schema)); auto schema_def = TRY(get_schema(schema));
if (!schema_def) { if (!schema_def) {
warnln("Schema '{}' does not exist"sv, schema); warnln("Schema '{}' does not exist"sv, schema);
return Error::from_string_literal("Schema does not exist"sv); return Error::from_string_literal("Schema does not exist");
} }
auto ret = TableDef::construct(schema_def, name); auto ret = TableDef::construct(schema_def, name);
ret->set_pointer((*table_iterator).pointer()); ret->set_pointer((*table_iterator).pointer());

View File

@ -35,11 +35,11 @@ ErrorOr<void> Heap::open()
if (stat(name().characters(), &stat_buffer) != 0) { if (stat(name().characters(), &stat_buffer) != 0) {
if (errno != ENOENT) { if (errno != ENOENT) {
warnln("Heap::open({}): could not stat: {}"sv, name(), strerror(errno)); warnln("Heap::open({}): could not stat: {}"sv, name(), strerror(errno));
return Error::from_string_literal("Heap::open(): could not stat file"sv); return Error::from_string_literal("Heap::open(): could not stat file");
} }
} else if (!S_ISREG(stat_buffer.st_mode)) { } else if (!S_ISREG(stat_buffer.st_mode)) {
warnln("Heap::open({}): can only use regular files"sv, name()); warnln("Heap::open({}): can only use regular files"sv, name());
return Error::from_string_literal("Heap::open(): can only use regular files"sv); return Error::from_string_literal("Heap::open(): can only use regular files");
} else { } else {
file_size = stat_buffer.st_size; file_size = stat_buffer.st_size;
} }
@ -49,7 +49,7 @@ ErrorOr<void> Heap::open()
auto file_or_error = Core::File::open(name(), Core::OpenMode::ReadWrite); auto file_or_error = Core::File::open(name(), Core::OpenMode::ReadWrite);
if (file_or_error.is_error()) { if (file_or_error.is_error()) {
warnln("Heap::open({}): could not open: {}"sv, name(), file_or_error.error()); warnln("Heap::open({}): could not open: {}"sv, name(), file_or_error.error());
return Error::from_string_literal("Heap::open(): could not open file"sv); return Error::from_string_literal("Heap::open(): could not open file");
} }
m_file = file_or_error.value(); m_file = file_or_error.value();
if (file_size > 0) { if (file_size > 0) {
@ -68,7 +68,7 @@ ErrorOr<ByteBuffer> Heap::read_block(u32 block)
{ {
if (m_file.is_null()) { if (m_file.is_null()) {
warnln("Heap({})::read_block({}): Heap file not opened"sv, name(), block); warnln("Heap({})::read_block({}): Heap file not opened"sv, name(), block);
return Error::from_string_literal("Heap()::read_block(): Heap file not opened"sv); return Error::from_string_literal("Heap()::read_block(): Heap file not opened");
} }
auto buffer_or_empty = m_write_ahead_log.get(block); auto buffer_or_empty = m_write_ahead_log.get(block);
if (buffer_or_empty.has_value()) if (buffer_or_empty.has_value())
@ -76,14 +76,14 @@ ErrorOr<ByteBuffer> Heap::read_block(u32 block)
if (block >= m_next_block) { if (block >= m_next_block) {
warnln("Heap({})::read_block({}): block # out of range (>= {})"sv, name(), block, m_next_block); warnln("Heap({})::read_block({}): block # out of range (>= {})"sv, name(), block, m_next_block);
return Error::from_string_literal("Heap()::read_block(): block # out of range"sv); return Error::from_string_literal("Heap()::read_block(): block # out of range");
} }
dbgln_if(SQL_DEBUG, "Read heap block {}", block); dbgln_if(SQL_DEBUG, "Read heap block {}", block);
TRY(seek_block(block)); TRY(seek_block(block));
auto ret = m_file->read(BLOCKSIZE); auto ret = m_file->read(BLOCKSIZE);
if (ret.is_empty()) { if (ret.is_empty()) {
warnln("Heap({})::read_block({}): Could not read block"sv, name(), block); warnln("Heap({})::read_block({}): Could not read block"sv, name(), block);
return Error::from_string_literal("Heap()::read_block(): Could not read block"sv); return Error::from_string_literal("Heap()::read_block(): Could not read block");
} }
dbgln_if(SQL_DEBUG, "{:02x} {:02x} {:02x} {:02x} {:02x} {:02x} {:02x} {:02x}", dbgln_if(SQL_DEBUG, "{:02x} {:02x} {:02x} {:02x} {:02x} {:02x} {:02x} {:02x}",
*ret.offset_pointer(0), *ret.offset_pointer(1), *ret.offset_pointer(0), *ret.offset_pointer(1),
@ -97,23 +97,23 @@ ErrorOr<void> Heap::write_block(u32 block, ByteBuffer& buffer)
{ {
if (m_file.is_null()) { if (m_file.is_null()) {
warnln("Heap({})::write_block({}): Heap file not opened"sv, name(), block); warnln("Heap({})::write_block({}): Heap file not opened"sv, name(), block);
return Error::from_string_literal("Heap()::write_block(): Heap file not opened"sv); return Error::from_string_literal("Heap()::write_block(): Heap file not opened");
} }
if (block > m_next_block) { if (block > m_next_block) {
warnln("Heap({})::write_block({}): block # out of range (> {})"sv, name(), block, m_next_block); warnln("Heap({})::write_block({}): block # out of range (> {})"sv, name(), block, m_next_block);
return Error::from_string_literal("Heap()::write_block(): block # out of range"sv); return Error::from_string_literal("Heap()::write_block(): block # out of range");
} }
TRY(seek_block(block)); TRY(seek_block(block));
dbgln_if(SQL_DEBUG, "Write heap block {} size {}", block, buffer.size()); dbgln_if(SQL_DEBUG, "Write heap block {} size {}", block, buffer.size());
if (buffer.size() > BLOCKSIZE) { if (buffer.size() > BLOCKSIZE) {
warnln("Heap({})::write_block({}): Oversized block ({} > {})"sv, name(), block, buffer.size(), BLOCKSIZE); warnln("Heap({})::write_block({}): Oversized block ({} > {})"sv, name(), block, buffer.size(), BLOCKSIZE);
return Error::from_string_literal("Heap()::write_block(): Oversized block"sv); return Error::from_string_literal("Heap()::write_block(): Oversized block");
} }
auto sz = buffer.size(); auto sz = buffer.size();
if (sz < BLOCKSIZE) { if (sz < BLOCKSIZE) {
if (buffer.try_resize(BLOCKSIZE).is_error()) { if (buffer.try_resize(BLOCKSIZE).is_error()) {
warnln("Heap({})::write_block({}): Could not align block of size {} to {}"sv, name(), block, buffer.size(), BLOCKSIZE); warnln("Heap({})::write_block({}): Could not align block of size {} to {}"sv, name(), block, buffer.size(), BLOCKSIZE);
return Error::from_string_literal("Heap()::write_block(): Could not align block"sv); return Error::from_string_literal("Heap()::write_block(): Could not align block");
} }
memset(buffer.offset_pointer((int)sz), 0, BLOCKSIZE - sz); memset(buffer.offset_pointer((int)sz), 0, BLOCKSIZE - sz);
} }
@ -128,28 +128,28 @@ ErrorOr<void> Heap::write_block(u32 block, ByteBuffer& buffer)
return {}; return {};
} }
warnln("Heap({})::write_block({}): Could not full write block"sv, name(), block); warnln("Heap({})::write_block({}): Could not full write block"sv, name(), block);
return Error::from_string_literal("Heap()::write_block(): Could not full write block"sv); return Error::from_string_literal("Heap()::write_block(): Could not full write block");
} }
ErrorOr<void> Heap::seek_block(u32 block) ErrorOr<void> Heap::seek_block(u32 block)
{ {
if (m_file.is_null()) { if (m_file.is_null()) {
warnln("Heap({})::seek_block({}): Heap file not opened"sv, name(), block); warnln("Heap({})::seek_block({}): Heap file not opened"sv, name(), block);
return Error::from_string_literal("Heap()::seek_block(): Heap file not opened"sv); return Error::from_string_literal("Heap()::seek_block(): Heap file not opened");
} }
if (block == m_end_of_file) { if (block == m_end_of_file) {
off_t pos; off_t pos;
if (!m_file->seek(0, Core::SeekMode::FromEndPosition, &pos)) { if (!m_file->seek(0, Core::SeekMode::FromEndPosition, &pos)) {
warnln("Heap({})::seek_block({}): Error seeking end of file: {}"sv, name(), block, m_file->error_string()); warnln("Heap({})::seek_block({}): Error seeking end of file: {}"sv, name(), block, m_file->error_string());
return Error::from_string_literal("Heap()::seek_block(): Error seeking end of file"sv); return Error::from_string_literal("Heap()::seek_block(): Error seeking end of file");
} }
} else if (block > m_end_of_file) { } else if (block > m_end_of_file) {
warnln("Heap({})::seek_block({}): Cannot seek beyond end of file at block {}"sv, name(), block, m_end_of_file); warnln("Heap({})::seek_block({}): Cannot seek beyond end of file at block {}"sv, name(), block, m_end_of_file);
return Error::from_string_literal("Heap()::seek_block(): Cannot seek beyond end of file"sv); return Error::from_string_literal("Heap()::seek_block(): Cannot seek beyond end of file");
} else { } else {
if (!m_file->seek(block * BLOCKSIZE)) { if (!m_file->seek(block * BLOCKSIZE)) {
warnln("Heap({})::seek_block({}): Error seeking: {}"sv, name(), block, m_file->error_string()); warnln("Heap({})::seek_block({}): Error seeking: {}"sv, name(), block, m_file->error_string());
return Error::from_string_literal("Heap()::seek_block(): Error seeking: {}"sv); return Error::from_string_literal("Heap()::seek_block(): Error seeking: {}");
} }
} }
return {}; return {};
@ -206,7 +206,7 @@ ErrorOr<void> Heap::read_zero_block()
auto file_id = StringView(file_id_buffer); auto file_id = StringView(file_id_buffer);
if (file_id != FILE_ID) { if (file_id != FILE_ID) {
warnln("{}: Zero page corrupt. This is probably not a {} heap file"sv, name(), FILE_ID); warnln("{}: Zero page corrupt. This is probably not a {} heap file"sv, name(), FILE_ID);
return Error::from_string_literal("Heap()::read_zero_block(): Zero page corrupt. This is probably not a SerenitySQL heap file"sv); return Error::from_string_literal("Heap()::read_zero_block(): Zero page corrupt. This is probably not a SerenitySQL heap file");
} }
dbgln_if(SQL_DEBUG, "Read zero block from {}", name()); dbgln_if(SQL_DEBUG, "Read zero block from {}", name());
memcpy(&m_version, buffer.offset_pointer(VERSION_OFFSET), sizeof(u32)); memcpy(&m_version, buffer.offset_pointer(VERSION_OFFSET), sizeof(u32));

View File

@ -91,7 +91,7 @@ ErrorOr<NonnullOwnPtr<TLSv12>> TLSv12::connect(String const& host, u16 port, Opt
tls_socket->try_disambiguate_error(); tls_socket->try_disambiguate_error();
// FIXME: Should return richer information here. // FIXME: Should return richer information here.
return AK::Error::from_string_literal(alert_name(static_cast<AlertDescription>(256 - result))); return AK::Error::from_string_view(alert_name(static_cast<AlertDescription>(256 - result)));
} }
ErrorOr<NonnullOwnPtr<TLSv12>> TLSv12::connect(String const& host, Core::Stream::Socket& underlying_stream, Options options) ErrorOr<NonnullOwnPtr<TLSv12>> TLSv12::connect(String const& host, Core::Stream::Socket& underlying_stream, Options options)
@ -112,7 +112,7 @@ ErrorOr<NonnullOwnPtr<TLSv12>> TLSv12::connect(String const& host, Core::Stream:
tls_socket->try_disambiguate_error(); tls_socket->try_disambiguate_error();
// FIXME: Should return richer information here. // FIXME: Should return richer information here.
return AK::Error::from_string_literal(alert_name(static_cast<AlertDescription>(256 - result))); return AK::Error::from_string_view(alert_name(static_cast<AlertDescription>(256 - result)));
} }
void TLSv12::setup_connection() void TLSv12::setup_connection()

View File

@ -75,17 +75,17 @@ enum class AlertDescription : u8 {
#undef ENUMERATE_ALERT_DESCRIPTION #undef ENUMERATE_ALERT_DESCRIPTION
}; };
constexpr static char const* alert_name(AlertDescription descriptor) constexpr static StringView alert_name(AlertDescription descriptor)
{ {
#define ENUMERATE_ALERT_DESCRIPTION(name, value) \ #define ENUMERATE_ALERT_DESCRIPTION(name, value) \
case AlertDescription::name: \ case AlertDescription::name: \
return #name; return #name##sv;
switch (descriptor) { switch (descriptor) {
ENUMERATE_ALERT_DESCRIPTIONS ENUMERATE_ALERT_DESCRIPTIONS
} }
return "Unknown"; return "Unknown"sv;
#undef ENUMERATE_ALERT_DESCRIPTION #undef ENUMERATE_ALERT_DESCRIPTION
} }

View File

@ -31,7 +31,7 @@ struct Context {
struct ValidationError : public Error { struct ValidationError : public Error {
ValidationError(String error) ValidationError(String error)
: Error(Error::from_string_literal(error)) : Error(Error::from_string_view(error))
, error_string(move(error)) , error_string(move(error))
{ {
} }

View File

@ -184,7 +184,7 @@ ErrorOr<DHCPv4Client::Interfaces> DHCPv4Client::get_discoverable_interfaces()
if (json.is_error() || !json.value().is_array()) { if (json.is_error() || !json.value().is_array()) {
dbgln("Error: No network adapters available"); dbgln("Error: No network adapters available");
return Error::from_string_literal("No network adapters available"sv); return Error::from_string_literal("No network adapters available");
} }
Vector<InterfaceDescriptor> ifnames_to_immediately_discover, ifnames_to_attempt_later; Vector<InterfaceDescriptor> ifnames_to_immediately_discover, ifnames_to_attempt_later;

View File

@ -39,7 +39,7 @@ ErrorOr<void> VirtualScreenBackend::set_head_mode_setting(GraphicsHeadModeSettin
mode_setting.horizontal_stride = static_cast<int>(mode_setting.horizontal_active * sizeof(Gfx::ARGB32)); mode_setting.horizontal_stride = static_cast<int>(mode_setting.horizontal_active * sizeof(Gfx::ARGB32));
m_pitch = mode_setting.horizontal_stride; m_pitch = mode_setting.horizontal_stride;
if (static_cast<int>(mode_setting.horizontal_active * sizeof(Gfx::ARGB32)) != mode_setting.horizontal_stride) if (static_cast<int>(mode_setting.horizontal_active * sizeof(Gfx::ARGB32)) != mode_setting.horizontal_stride)
return Error::from_string_literal("Unsupported pitch"sv); return Error::from_string_literal("Unsupported pitch");
m_width = mode_setting.horizontal_active; m_width = mode_setting.horizontal_active;
return {}; return {};

View File

@ -128,7 +128,7 @@ ErrorOr<off_t> print_space_usage(String const& path, DuOption const& du_option,
auto di = Core::DirIterator(path, Core::DirIterator::SkipParentAndBaseDir); auto di = Core::DirIterator(path, Core::DirIterator::SkipParentAndBaseDir);
if (di.has_error()) { if (di.has_error()) {
outln("du: cannot read directory '{}': {}", path, di.error_string()); outln("du: cannot read directory '{}': {}", path, di.error_string());
return Error::from_string_literal("An error occurred. See previous error."sv); return Error::from_string_literal("An error occurred. See previous error.");
} }
while (di.has_next()) { while (di.has_next()) {

View File

@ -11,7 +11,7 @@ ErrorOr<int> serenity_main(Main::Arguments)
{ {
auto document = Video::MatroskaReader::parse_matroska_from_file("/home/anon/Videos/test-webm.webm"); auto document = Video::MatroskaReader::parse_matroska_from_file("/home/anon/Videos/test-webm.webm");
if (!document) { if (!document) {
return Error::from_string_literal("Failed to parse :("sv); return Error::from_string_literal("Failed to parse :(");
} }
outln("DocType is {}", document->header().doc_type.characters()); outln("DocType is {}", document->header().doc_type.characters());

View File

@ -36,7 +36,7 @@ ErrorOr<int> serenity_main(Main::Arguments arguments)
if (account.has_password()) { if (account.has_password()) {
auto password = TRY(Core::get_password()); auto password = TRY(Core::get_password());
if (!account.authenticate(password)) if (!account.authenticate(password))
return Error::from_string_literal("Incorrect or disabled password."sv); return Error::from_string_literal("Incorrect or disabled password.");
} }
} }

View File

@ -848,7 +848,7 @@ ErrorOr<int> serenity_main(Main::Arguments arguments)
int status; int status;
if (g_pid == -1) { if (g_pid == -1) {
if (child_argv.is_empty()) if (child_argv.is_empty())
return Error::from_string_literal("Expected either a pid or some arguments"sv); return Error::from_string_literal("Expected either a pid or some arguments");
auto pid = TRY(Core::System::fork()); auto pid = TRY(Core::System::fork());