diff --git a/src/util/MimeType.cxx b/src/util/MimeType.cxx index 64822555b..1287895fc 100644 --- a/src/util/MimeType.cxx +++ b/src/util/MimeType.cxx @@ -18,6 +18,7 @@ */ #include "MimeType.hxx" +#include "SplitString.hxx" #include @@ -29,3 +30,24 @@ GetMimeTypeBase(const char *s) ? std::string(s, semicolon) : std::string(s); } + +std::map +ParseMimeTypeParameters(const char *s) +{ + std::map result; + + auto l = SplitString(s, ';', true); + if (!l.empty()) + l.pop_front(); + + for (const auto &i : l) { + const auto eq = i.find('='); + if (eq == i.npos) + continue; + + result.insert(std::make_pair(std::string(&i.front(), eq), + std::string(&i[eq + 1]))); + } + + return result; +} diff --git a/src/util/MimeType.hxx b/src/util/MimeType.hxx index fe8f385b2..679697d7a 100644 --- a/src/util/MimeType.hxx +++ b/src/util/MimeType.hxx @@ -21,6 +21,7 @@ #define MPD_MIME_TYPE_HXX #include +#include /** * Extract the part of the MIME type before the parameters, i.e. the @@ -30,4 +31,13 @@ std::string GetMimeTypeBase(const char *s); +/** + * Parse the parameters from a MIME type string. Parameters are + * separated by semicolon. Example: + * + * "foo/bar; param1=value1; param2=value2" + */ +std::map +ParseMimeTypeParameters(const char *s); + #endif diff --git a/test/MimeTypeTest.hxx b/test/MimeTypeTest.hxx index 0e243e6ba..2d4286279 100644 --- a/test/MimeTypeTest.hxx +++ b/test/MimeTypeTest.hxx @@ -13,6 +13,7 @@ class MimeTypeTest : public CppUnit::TestFixture { CPPUNIT_TEST_SUITE(MimeTypeTest); CPPUNIT_TEST(TestBase); + CPPUNIT_TEST(TestParameters); CPPUNIT_TEST_SUITE_END(); public: @@ -25,4 +26,24 @@ public: CPPUNIT_ASSERT("foo/bar" == GetMimeTypeBase("foo/bar; x=y")); CPPUNIT_ASSERT("foo/bar" == GetMimeTypeBase("foo/bar;x=y")); } + + void TestParameters() { + CPPUNIT_ASSERT(ParseMimeTypeParameters("").empty()); + CPPUNIT_ASSERT(ParseMimeTypeParameters("foo/bar").empty()); + CPPUNIT_ASSERT(ParseMimeTypeParameters("foo/bar;").empty()); + CPPUNIT_ASSERT(ParseMimeTypeParameters("foo/bar;garbage").empty()); + CPPUNIT_ASSERT(ParseMimeTypeParameters("foo/bar; garbage").empty()); + + auto p = ParseMimeTypeParameters("foo/bar;a=b"); + CPPUNIT_ASSERT(!p.empty()); + CPPUNIT_ASSERT(p["a"] == "b"); + CPPUNIT_ASSERT(p.size() == 1); + + p = ParseMimeTypeParameters("foo/bar; a=b;c;d=e ; f=g "); + CPPUNIT_ASSERT(!p.empty()); + CPPUNIT_ASSERT(p["a"] == "b"); + CPPUNIT_ASSERT(p["d"] == "e"); + CPPUNIT_ASSERT(p["f"] == "g"); + CPPUNIT_ASSERT(p.size() == 3); + } };