xref: /openbmc/bmcweb/include/boost_formatters.hpp (revision d78572018fc2022091ff8b8eb5a7fef2172ba3d6)
1 // SPDX-License-Identifier: Apache-2.0
2 // SPDX-FileCopyrightText: Copyright OpenBMC Authors
3 #pragma once
4 
5 #include <boost/system/error_code.hpp>
6 #include <boost/url/grammar/string_view_base.hpp>
7 #include <boost/url/url_view_base.hpp>
8 
9 #include <concepts>
10 #include <format>
11 #include <string_view>
12 
13 // NOLINTBEGIN(readability-convert-member-functions-to-static, cert-dcl58-cpp)
14 template <std::derived_from<boost::system::error_code> ErrorCodeType>
15 struct std::formatter<ErrorCodeType>
16 {
parsestd::formatter17     constexpr auto parse(std::format_parse_context& ctx)
18     {
19         return ctx.begin();
20     }
21 
formatstd::formatter22     auto format(const ErrorCodeType& ec, auto& ctx) const
23     {
24         return std::format_to(ctx.out(), "{}", ec.what());
25     }
26 };
27 
28 template <std::derived_from<boost::urls::grammar::string_view_base> StringView>
29 struct std::formatter<StringView>
30 {
parsestd::formatter31     constexpr auto parse(std::format_parse_context& ctx)
32     {
33         return ctx.begin();
34     }
formatstd::formatter35     auto format(const StringView& msg, auto& ctx) const
36     {
37         return std::format_to(ctx.out(), "{}",
38                               std::string_view(msg.data(), msg.size()));
39     }
40 };
41 
42 template <std::derived_from<boost::urls::url_view_base> UrlBase>
43 struct std::formatter<UrlBase>
44 {
parsestd::formatter45     constexpr auto parse(std::format_parse_context& ctx)
46     {
47         return ctx.begin();
48     }
formatstd::formatter49     auto format(const UrlBase& msg, auto& ctx) const
50     {
51         return std::format_to(ctx.out(), "{}", std::string_view(msg.buffer()));
52     }
53 };
54 
55 template <std::derived_from<boost::core::string_view> StringView>
56 struct std::formatter<StringView>
57 {
parsestd::formatter58     constexpr auto parse(std::format_parse_context& ctx)
59     {
60         return ctx.begin();
61     }
formatstd::formatter62     auto format(const StringView& msg, auto& ctx) const
63     {
64         return std::format_to(ctx.out(), "{}", std::string_view(msg));
65     }
66 };
67 // NOLINTEND(readability-convert-member-functions-to-static, cert-dcl58-cpp)
68