media-typer

RFC 6838 media type parsing, formatting, and validation — the parse / format / test triad from npm media-typer 1.1.0.

These helpers work with bare media types such as application/vnd.api+json. They are not full Content-Type header parsers, so callers should strip parameters such as ; charset=UTF-8 before calling polycpp::mime::parse() or polycpp::mime::test().

polycpp::mime::parse() lowercases valid input and throws polycpp::TypeError for empty or invalid media type strings. Leading and trailing C whitespace is trimmed before validation. polycpp::mime::format() validates the type, subtype, and non-empty suffix fields in polycpp::mime::MediaType; it throws polycpp::TypeError when any field is invalid. An empty MediaType::suffix means no structured syntax suffix.

MediaType

struct MediaType

Parsed media type components per RFC 6838.

Public Members

std::string type

Primary type (e.g., “text”, “application”)

std::string subtype

Subtype (e.g., “html”, “vnd.api”)

std::string suffix

Structured syntax suffix (e.g., “xml”, “json”), empty if none.

Functions

MediaType polycpp::mime::parse(const std::string &mediaType)

Parse a bare media type string into its components.

Validates the format per RFC 6838. Input is lowercased. Leading and trailing whitespace is trimmed. This function does not parse full Content-Type header values with parameters; strip parameters before calling it.

Example
auto mt = mime::parse("application/vnd.api+json");
// mt.type == "application"
// mt.subtype == "vnd.api"
// mt.suffix == "json"

Parameters:

mediaType – A media type string (e.g., "application/vnd.api+json").

Throws:

polycpp::TypeError – If the string is not a valid media type.

Returns:

A MediaType with type, subtype, and optional suffix.

std::string polycpp::mime::format(const MediaType &mt)

Format a MediaType object into a media type string.

Validates type, subtype, and suffix components.

Example
MediaType mt{"image", "svg", "xml"};
mime::format(mt); // "image/svg+xml"

Parameters:

mt – The MediaType to format.

Throws:

polycpp::TypeError – If any component is invalid.

Returns:

The formatted string (e.g., "application/vnd.api+json").

bool polycpp::mime::test(const std::string &mediaType)

Test whether a string is a valid bare media type.

This function does not validate full Content-Type header values with parameters; strip parameters before calling it.

Example
mime::test("text/html");       // true
mime::test("image/svg+xml");   // true
mime::test("bogus");           // false

Parameters:

mediaType – A string to test.

Returns:

true if the string matches the RFC 6838 media type format.