From ce6d6706a677de6091676e1affdb121ab6775717 Mon Sep 17 00:00:00 2001 From: Max Wipfli Date: Wed, 12 May 2021 10:07:17 +0200 Subject: LibWeb: Use Optional for encoding_from_content_type This patch changes the encoding_from_content_type function to only return an encoding if it actually finds one, and leave it up to the caller to decided on a default to use. It also modifies the caller to expect an Optional (instead of relying on the null state of the String class) as a return value and separates the encoding and MIME type determination. This will be built upon in a further commit. --- Userland/Libraries/LibWeb/Loader/Resource.cpp | 20 ++++++++++++++------ 1 file changed, 14 insertions(+), 6 deletions(-) (limited to 'Userland/Libraries/LibWeb/Loader') diff --git a/Userland/Libraries/LibWeb/Loader/Resource.cpp b/Userland/Libraries/LibWeb/Loader/Resource.cpp index 9231ec341e..0892cc61c9 100644 --- a/Userland/Libraries/LibWeb/Loader/Resource.cpp +++ b/Userland/Libraries/LibWeb/Loader/Resource.cpp @@ -41,7 +41,7 @@ void Resource::for_each_client(Function callback) } } -static String encoding_from_content_type(const String& content_type) +static Optional encoding_from_content_type(const String& content_type) { auto offset = content_type.index_of("charset="); if (offset.has_value()) { @@ -53,7 +53,7 @@ static String encoding_from_content_type(const String& content_type) return encoding; } - return "utf-8"; + return {}; } static String mime_type_from_content_type(const String& content_type) @@ -74,20 +74,28 @@ void Resource::did_load(Badge, ReadonlyBytes data, const HashMap m_loaded = true; auto content_type = headers.get("Content-Type"); + if (content_type.has_value()) { dbgln_if(RESOURCE_DEBUG, "Content-Type header: '{}'", content_type.value()); - m_encoding = encoding_from_content_type(content_type.value()); m_mime_type = mime_type_from_content_type(content_type.value()); } else if (url().protocol() == "data" && !url().data_mime_type().is_empty()) { dbgln_if(RESOURCE_DEBUG, "This is a data URL with mime-type _{}_", url().data_mime_type()); - m_encoding = "utf-8"; // FIXME: This doesn't seem nice. m_mime_type = url().data_mime_type(); } else { - dbgln_if(RESOURCE_DEBUG, "No Content-Type header to go on! Guessing based on filename..."); - m_encoding = "utf-8"; // FIXME: This doesn't seem nice. m_mime_type = Core::guess_mime_type_based_on_filename(url().path()); } + if (content_type.has_value()) { + auto encoding = encoding_from_content_type(content_type.value()); + if (encoding.has_value()) { + dbgln_if(RESOURCE_DEBUG, "Set encoding '{}' from Content-Type", encoding.has_value()); + m_encoding = encoding.value(); + } else { + // FIXME: This doesn't seem nice. + m_encoding = "utf-8"; + } + } + for_each_client([](auto& client) { client.resource_did_load(); }); -- cgit v1.2.3