From 6a0c5c178db3c9f4f5ad08c4a1805bc9106a07f8 Mon Sep 17 00:00:00 2001 From: Hartmut Seichter Date: Mon, 22 Jul 2024 22:40:38 +0200 Subject: [PATCH] formatters for std::format and std::print --- src/core/include/pw/core/formatter.hpp | 69 ++++++++++++++++++++++++++ 1 file changed, 69 insertions(+) create mode 100644 src/core/include/pw/core/formatter.hpp diff --git a/src/core/include/pw/core/formatter.hpp b/src/core/include/pw/core/formatter.hpp new file mode 100644 index 0000000..04be12b --- /dev/null +++ b/src/core/include/pw/core/formatter.hpp @@ -0,0 +1,69 @@ +/* + * Copyright (c) 1999-2021 Hartmut Seichter + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + * + */ + +#ifndef PW_CORE_FORMATTER_HPP +#define PW_CORE_FORMATTER_HPP + +#include +#include +#include + +#include +#include +#include + +template +struct std::formatter> { + + constexpr auto parse(std::format_parse_context& ctx) { return ctx.begin(); } + + constexpr auto format(const pw::vector& v, + std::format_context& ctx) const noexcept { + return std::format_to( + ctx.out(), "{}", + std::accumulate(std::next(std::begin(v)), std::end(v), + std::to_string(v[0]), + [](const auto& prev, const auto& e) { + return prev + " " + std::to_string(e); + })); + } +}; + +template +struct std::formatter> { + + constexpr auto parse(std::format_parse_context& ctx) { return ctx.begin(); } + + constexpr auto format(const pw::matrix& m, + std::format_context& ctx) const noexcept { + return std::format_to( + ctx.out(), "{}", + std::accumulate(std::next(std::begin(m)), std::end(m), + std::format("{}", m[0]), + [](const auto& prev, const auto& e) { + return prev + "\n" + std::format("{}", e); + })); + } +}; + +#endif