microfmt
Zero-allocation C++ formatting for constrained environments
Loading...
Searching...
No Matches
exception.hpp
Go to the documentation of this file.
1// SPDX-FileCopyrightText: 2026 Jarosław Pelczar <jarek@jpelczar.com>
2//
3// SPDX-License-Identifier: BSD-2-Clause
4
5#pragma once
6
7// std-interop-file: opt-in formatter for std::exception-derived types and std::system_error.
8
9#include "../microfmt.hpp"
10#include <exception>
11#include <system_error>
12#include <type_traits>
13
14namespace microfmt {
15
16template <typename T> struct formatter<T, std::enable_if_t<std::is_base_of_v<std::exception, T>>> {
17 constexpr void parse(format_parse_context &) noexcept {}
18
19 // low-level formatting: raw character pointers and integer width conversions bounded by the buffer sizes checked
20 // here.
21 RELOCO_BEGIN_UNSAFE_CODE
22 void format(const T &value, const sink &out) const noexcept {
23 const char *msg = value.what();
24 if (msg != nullptr) {
25 out.write(msg);
26 } else {
27 out.write("<unknown exception>");
28 }
29 }
31};
32
33template <> struct formatter<std::system_error> {
34 constexpr void parse(format_parse_context &) noexcept {}
35
36 // low-level formatting: raw character pointers and integer width conversions bounded by the buffer sizes checked
37 // here.
38 RELOCO_BEGIN_UNSAFE_CODE
39 void format(const std::system_error &value, const sink &out) const noexcept {
40 const char *msg = value.what();
41 if (msg != nullptr) {
42 out.write(msg);
43 }
44
45 const auto ec = value.code();
46 out.write(" [");
47 out.write(ec.category().name());
48 out.write(":");
49
50 // Directly format the error value as an integer
51 const formatter<int> int_fmt;
52 int_fmt.format(ec.value(), out);
53
54 out.write("]");
55 }
57};
58
59} // namespace microfmt
Definition microfmt.hpp:881
Definition assert.hpp:19
reloco::sink sink
Type-erased, zero-allocation output sink.
Definition microfmt.hpp:46
RELOCO_END_UNSAFE_CODE
Definition remote_object.hpp:132
RELOCO_BEGIN_UNSAFE_CODE void format(const T &value, const sink &out) const noexcept
Definition exception.hpp:22
constexpr void parse(format_parse_context &) noexcept
Definition exception.hpp:17
RELOCO_BEGIN_UNSAFE_CODE void format(const std::system_error &value, const sink &out) const noexcept
Definition exception.hpp:39
constexpr void parse(format_parse_context &) noexcept
Definition exception.hpp:34
Definition microfmt.hpp:985