From b42b950688fdbad5d976bc00f8890c09d4d6f8de Mon Sep 17 00:00:00 2001 From: Linus Groh Date: Thu, 22 Sep 2022 23:30:17 +0100 Subject: [PATCH] LibWeb: Implement MimeType serialization --- .../Libraries/LibWeb/MimeSniff/MimeType.cpp | 40 +++++++++++++++++++ .../Libraries/LibWeb/MimeSniff/MimeType.h | 2 + 2 files changed, 42 insertions(+) diff --git a/Userland/Libraries/LibWeb/MimeSniff/MimeType.cpp b/Userland/Libraries/LibWeb/MimeSniff/MimeType.cpp index 83c74b3454..a6b23a702d 100644 --- a/Userland/Libraries/LibWeb/MimeSniff/MimeType.cpp +++ b/Userland/Libraries/LibWeb/MimeSniff/MimeType.cpp @@ -1,5 +1,6 @@ /* * Copyright (c) 2022, Luke Wilde + * Copyright (c) 2022, Linus Groh * * SPDX-License-Identifier: BSD-2-Clause */ @@ -172,6 +173,45 @@ String MimeType::essence() const return String::formatted("{}/{}", m_type, m_subtype); } +// https://mimesniff.spec.whatwg.org/#serialize-a-mime-type +String MimeType::serialized() const +{ + // 1. Let serialization be the concatenation of mimeType’s type, U+002F (/), and mimeType’s subtype. + StringBuilder serialization; + serialization.append(m_type); + serialization.append('/'); + serialization.append(m_subtype); + + // 2. For each name → value of mimeType’s parameters: + for (auto [name, value] : m_parameters) { + // 1. Append U+003B (;) to serialization. + serialization.append(';'); + + // 2. Append name to serialization. + serialization.append(name); + + // 3. Append U+003D (=) to serialization. + serialization.append('='); + + // 4. If value does not solely contain HTTP token code points or value is the empty string, then: + if (!contains_only_http_token_code_points(value) || value.is_empty()) { + // 1. Precede each occurence of U+0022 (") or U+005C (\) in value with U+005C (\). + value = value.replace("\""sv, "\\\""sv, ReplaceMode::All); + value = value.replace("\\"sv, "\\\\"sv, ReplaceMode::All); + + // 2. Prepend U+0022 (") to value. + // 3. Append U+0022 (") to value. + value = String::formatted("\"{}\"", value); + } + + // 5. Append value to serialization. + serialization.append(value); + } + + // 3. Return serialization. + return serialization.to_string(); +} + void MimeType::set_parameter(String const& name, String const& value) { // https://mimesniff.spec.whatwg.org/#parameters diff --git a/Userland/Libraries/LibWeb/MimeSniff/MimeType.h b/Userland/Libraries/LibWeb/MimeSniff/MimeType.h index e90bc237ce..19f9b7e1d1 100644 --- a/Userland/Libraries/LibWeb/MimeSniff/MimeType.h +++ b/Userland/Libraries/LibWeb/MimeSniff/MimeType.h @@ -1,5 +1,6 @@ /* * Copyright (c) 2022, Luke Wilde + * Copyright (c) 2022, Linus Groh * * SPDX-License-Identifier: BSD-2-Clause */ @@ -26,6 +27,7 @@ public: void set_parameter(String const& name, String const& value); String essence() const; + String serialized() const; private: // https://mimesniff.spec.whatwg.org/#type