File: FormatUtil.h

package info (click to toggle)
dolphin-emu 2512%2Bdfsg-2
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 76,328 kB
  • sloc: cpp: 499,023; ansic: 119,674; python: 6,547; sh: 2,338; makefile: 1,093; asm: 726; pascal: 257; javascript: 183; perl: 97; objc: 75; xml: 30
file content (75 lines) | stat: -rw-r--r-- 2,289 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
// Copyright 2020 Dolphin Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later

#pragma once

#include <cstddef>
#include <string_view>

namespace Common
{
constexpr std::size_t CountFmtReplacementFields(std::string_view s)
{
  std::size_t count = 0;
  for (std::size_t i = 0; i < s.size(); ++i)
  {
    if (s[i] != '{')
      continue;

    // If the opening brace is followed by another brace, what we have is
    // an escaped brace, not a replacement field.
    if (i + 1 < s.size() && s[i + 1] == '{')
    {
      // Skip the second brace.
      // This ensures that e.g. {{{}}} is counted correctly: when the first brace character
      // is read and detected as being part of an '{{' escape sequence, the second character
      // is skipped so the most inner brace (the third character) is not detected
      // as the end of an '{{' pair.
      ++i;
      continue;
    }

    ++count;
  }
  return count;
}

static_assert(CountFmtReplacementFields("") == 0);
static_assert(CountFmtReplacementFields("{} test {:x}") == 2);
static_assert(CountFmtReplacementFields("{} {{}} test {{{}}}") == 2);

constexpr bool ContainsNonPositionalArguments(std::string_view s)
{
  for (std::size_t i = 0; i < s.size(); ++i)
  {
    if (s[i] != '{' || i + 1 == s.size())
      continue;

    const char next = s[i + 1];

    // If the opening brace is followed by another brace, what we have is
    // an escaped brace, not a replacement field.
    if (next == '{')
    {
      // Skip the second brace.
      // This ensures that e.g. {{{}}} is counted correctly: when the first brace character
      // is read and detected as being part of an '{{' escape sequence, the second character
      // is skipped so the most inner brace (the third character) is not detected
      // as the end of an '{{' pair.
      ++i;
    }
    else if (next == '}' || next == ':')
    {
      return true;
    }
  }
  return false;
}

static_assert(!ContainsNonPositionalArguments(""));
static_assert(ContainsNonPositionalArguments("{}"));
static_assert(!ContainsNonPositionalArguments("{0}"));
static_assert(ContainsNonPositionalArguments("{:x}"));
static_assert(!ContainsNonPositionalArguments("{0:x}"));
static_assert(!ContainsNonPositionalArguments("{0} {{}} test {{{1}}}"));
}  // namespace Common