Debian Codegraph @

Source/Core/Common/FormatUtil.h

raw symbols SCIP
1 // Copyright 2020 Dolphin Emulator Project
2 // SPDX-License-Identifier: GPL-2.0-or-later
3
4 #pragma once
5
6 #include <cstddef>
7 #include <string_view>
8
9 namespace Common
10 {
11 constexpr std::size_t CountFmtReplacementFields(std::string_view s)
12 {
13 std::size_t count = 0;
14 for (std::size_t i = 0; i < s.size(); ++i)
15 {
16 if (s[i] != '{')
17 continue;
18
19 // If the opening brace is followed by another brace, what we have is
20 // an escaped brace, not a replacement field.
21 if (i + 1 < s.size() && s[i + 1] == '{')
22 {
23 // Skip the second brace.
24 // This ensures that e.g. {{{}}} is counted correctly: when the first brace character
25 // is read and detected as being part of an '{{' escape sequence, the second character
26 // is skipped so the most inner brace (the third character) is not detected
27 // as the end of an '{{' pair.
28 ++i;
29 continue;
30 }
31
32 ++count;
33 }
34 return count;
35 }
36
37 static_assert(CountFmtReplacementFields("") == 0);
38 static_assert(CountFmtReplacementFields("{} test {:x}") == 2);
39 static_assert(CountFmtReplacementFields("{} {{}} test {{{}}}") == 2);
40
41 constexpr bool ContainsNonPositionalArguments(std::string_view s)
42 {
43 for (std::size_t i = 0; i < s.size(); ++i)
44 {
45 if (s[i] != '{' || i + 1 == s.size())
46 continue;
47
48 const char next = s[i + 1];
49
50 // If the opening brace is followed by another brace, what we have is
51 // an escaped brace, not a replacement field.
52 if (next == '{')
53 {
54 // Skip the second brace.
55 // This ensures that e.g. {{{}}} is counted correctly: when the first brace character
56 // is read and detected as being part of an '{{' escape sequence, the second character
57 // is skipped so the most inner brace (the third character) is not detected
58 // as the end of an '{{' pair.
59 ++i;
60 }
61 else if (next == '}' || next == ':')
62 {
63 return true;
64 }
65 }
66 return false;
67 }
68
69 static_assert(!ContainsNonPositionalArguments(""));
70 static_assert(ContainsNonPositionalArguments("{}"));
71 static_assert(!ContainsNonPositionalArguments("{0}"));
72 static_assert(ContainsNonPositionalArguments("{:x}"));
73 static_assert(!ContainsNonPositionalArguments("{0:x}"));
74 static_assert(!ContainsNonPositionalArguments("{0} {{}} test {{{1}}}"));
75 } // namespace Common