aest 0.1.0
Collection of C++ utility libraries
Loading...
Searching...
No Matches
Format.cppm
Go to the documentation of this file.
1
8module;
9#include <algorithm>
10#include <format>
11#include <initializer_list>
12#include <string_view>
13export module aest.colors:format;
14
15import :color;
16
24template <aest::colors::ColorType Color>
25struct std::formatter<Color>
26{
32 constexpr auto parse(std::format_parse_context& ctx)
33 {
34 _useDefault = ctx.begin() == ctx.end() || *ctx.begin() == '}';
35 return _useDefault ? ctx.begin() : _channel.parse(ctx);
36 }
37
44 auto format(const Color& color, std::format_context& ctx) const
45 {
46 auto out = std::format_to(ctx.out(), "{}(", Color::TYPE);
47 std::string_view separator;
48 for (const float value : {color.ch1(), color.ch2(), color.ch3(), color.alpha()})
49 {
50 out = std::ranges::copy(separator, out).out;
51 separator = ", ";
52 if (_useDefault)
53 {
54 out = std::format_to(out, "{:.3f}", value);
55 }
56 else
57 {
58 ctx.advance_to(out);
59 out = _channel.format(value, ctx);
60 }
61 }
62 *out++ = ')';
63 return out;
64 }
65
66private:
67 std::formatter<float> _channel;
68 bool _useDefault = true;
69};
bool _useDefault
Whether the spec was empty, printing three decimals.
Definition Format.cppm:68
constexpr auto parse(std::format_parse_context &ctx)
Parse the spec that every channel is formatted with.
Definition Format.cppm:32
auto format(const Color &color, std::format_context &ctx) const
Write the formatted color to the output of ctx.
Definition Format.cppm:44
std::formatter< float > _channel
Formatter for each channel, set by a non-empty spec.
Definition Format.cppm:67