Branch data Line data Source code
1 : : /* -*- mode: C++; c-basic-offset: 4; indent-tabs-mode: nil; -*- */
2 : : // SPDX-License-Identifier: MIT OR LGPL-2.0-or-later
3 : : // SPDX-FileCopyrightText: 2026 Philip Chimento <philip.chimento@gmail.com>
4 : :
5 : : #pragma once
6 : :
7 : : #include <config.h>
8 : :
9 : : #include <format>
10 : :
11 : : // Shared facilities for GJS's custom formatters
12 : :
13 : : namespace Gjs {
14 : :
15 : : /**
16 : : * Gjs::FormatterBase:
17 : : *
18 : : * Base class for formatters that accept a closed set of single-character
19 : : * format specifiers, and no other formatting options. For example, have a
20 : : * std::formatter specialization inherit from FormatterBase<'?', 't'> in order
21 : : * to support formatting that type with {:?}, {:t}, and {}. In the latter case,
22 : : * spec() will return '\0'.
23 : : */
24 : : template <char... ACCEPTED>
25 : : class FormatterBase {
26 : : char m_spec = '\0';
27 : :
28 : : // std::format_parse_context::iterator is const char* on most platforms, but
29 : : // is allowed to be an opaque type, so don't hardcode it.
30 : : using ParseIter = std::format_parse_context::iterator;
31 : :
32 : : public:
33 : 1257 : constexpr ParseIter parse(std::format_parse_context& cx) {
34 : 1257 : ParseIter it = cx.begin();
35 [ + - + + : 1257 : if (it != cx.end() && ((*it == ACCEPTED) || ...)) {
+ + + + ]
36 : 127 : m_spec = *it;
37 : 127 : ++it;
38 : : }
39 : : // Doesn't consume character if not recognized, letting stdlib error
40 : 1257 : return it;
41 : : }
42 : :
43 : 1349 : [[nodiscard]] constexpr char spec() const { return m_spec; }
44 : : };
45 : :
46 : : } // namespace Gjs
|