Haio 0.2.X
Homebrew Asset IO/CDN
Loading...
Searching...
No Matches
format.cpp
Go to the documentation of this file.
1#include <haio.hpp>
2#include <haio_codecs.hpp>
3
4#include <algorithm>
5#include <cctype>
6
7namespace {
8
9std::string lower(std::string_view value) {
10 std::string out(value);
11 std::ranges::transform(out, out.begin(), [](unsigned char c) {
12 return static_cast<char>(std::tolower(c));
13 });
14 return out;
15}
16
17std::string_view lastExtension(std::string_view path) {
18 const auto slash = path.find_last_of("/\\");
19 const auto dot = path.find_last_of('.');
20 if (dot == std::string_view::npos || (slash != std::string_view::npos && dot < slash)) return {};
21 return path.substr(dot + 1);
22}
23
24}
25
26namespace Haio {
27
28/**
29 * a file name only ever names a container, never the colour inside it. the extension
30 * is not the enumerator name: .jpg is the usual spelling of jpeg, and the netpbm
31 * family answers to four.
32 */
33Format formatFromExtension(std::string_view path) {
34 const auto key = lower(lastExtension(path));
35 for (const auto& entry : formatExtensions) {
36 if (entry.extension == key) return entry.format;
37 }
38 return Format::RAW;
39}
40
41Format formatFromContentType(std::string_view contentType) {
42 auto value = contentType.substr(0, contentType.find(';'));
43 while (!value.empty() && std::isspace(static_cast<unsigned char>(value.front()))) value.remove_prefix(1);
44 while (!value.empty() && std::isspace(static_cast<unsigned char>(value.back()))) value.remove_suffix(1);
45
46 const auto key = lower(value);
47 for (const auto& entry : formatMimes) {
48 if (entry.mime == key) return entry.format;
49 }
50 return Format::RAW;
51}
52
53/** the first extension an enumerator names is the one haio writes */
54std::string_view extensionFor(Format format) {
55 for (const auto& entry : formatExtensions) {
56 if (entry.format == format) return entry.extension;
57 }
58 return "bin";
59}
60
61/** the first mime type an enumerator names is the one haio sends */
62std::string_view contentTypeFor(Format format) {
63 for (const auto& entry : formatMimes) {
64 if (entry.format == format) return entry.mime;
65 }
66 return "application/octet-stream";
67}
68}
Definition haio.hpp:11
Format formatFromContentType(std::string_view contentType)
Definition format.cpp:41
Format formatFromExtension(std::string_view path)
Definition format.cpp:33
std::string_view contentTypeFor(Format format)
Definition format.cpp:62
std::string_view extensionFor(Format format)
Definition format.cpp:54