Bitcoin Core  27.99.0
P2P Digital Currency
spanparsing.cpp
Go to the documentation of this file.
1 // Copyright (c) 2018-2022 The Bitcoin Core developers
2 // Distributed under the MIT software license, see the accompanying
3 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
4 
5 #include <util/spanparsing.h>
6 
7 #include <span.h>
8 
9 #include <algorithm>
10 #include <cstddef>
11 #include <string>
12 
13 namespace spanparsing {
14 
15 bool Const(const std::string& str, Span<const char>& sp)
16 {
17  if ((size_t)sp.size() >= str.size() && std::equal(str.begin(), str.end(), sp.begin())) {
18  sp = sp.subspan(str.size());
19  return true;
20  }
21  return false;
22 }
23 
24 bool Func(const std::string& str, Span<const char>& sp)
25 {
26  if ((size_t)sp.size() >= str.size() + 2 && sp[str.size()] == '(' && sp[sp.size() - 1] == ')' && std::equal(str.begin(), str.end(), sp.begin())) {
27  sp = sp.subspan(str.size() + 1, sp.size() - str.size() - 2);
28  return true;
29  }
30  return false;
31 }
32 
34 {
35  int level = 0;
36  auto it = sp.begin();
37  while (it != sp.end()) {
38  if (*it == '(' || *it == '{') {
39  ++level;
40  } else if (level && (*it == ')' || *it == '}')) {
41  --level;
42  } else if (level == 0 && (*it == ')' || *it == '}' || *it == ',')) {
43  break;
44  }
45  ++it;
46  }
47  Span<const char> ret = sp.first(it - sp.begin());
48  sp = sp.subspan(it - sp.begin());
49  return ret;
50 }
51 
52 } // namespace spanparsing
int ret
A Span is an object that can refer to a contiguous sequence of objects.
Definition: span.h:98
constexpr std::size_t size() const noexcept
Definition: span.h:187
constexpr C * end() const noexcept
Definition: span.h:176
constexpr C * begin() const noexcept
Definition: span.h:175
CONSTEXPR_IF_NOT_DEBUG Span< C > first(std::size_t count) const noexcept
Definition: span.h:205
CONSTEXPR_IF_NOT_DEBUG Span< C > subspan(std::size_t offset) const noexcept
Definition: span.h:195
Span< const char > Expr(Span< const char > &sp)
Extract the expression that sp begins with.
Definition: spanparsing.cpp:33
bool Const(const std::string &str, Span< const char > &sp)
Parse a constant.
Definition: spanparsing.cpp:15
bool Func(const std::string &str, Span< const char > &sp)
Parse a function call.
Definition: spanparsing.cpp:24