Bitcoin ABC  0.22.13
P2P Digital Currency
spanparsing.cpp
Go to the documentation of this file.
1 // Copyright (c) 2018 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 <string>
10 #include <vector>
11 
12 namespace spanparsing {
13 
14 bool Const(const std::string &str, Span<const char> &sp) {
15  if (size_t(sp.size()) >= str.size() &&
16  std::equal(str.begin(), str.end(), sp.begin())) {
17  sp = sp.subspan(str.size());
18  return true;
19  }
20  return false;
21 }
22 
23 bool Func(const std::string &str, Span<const char> &sp) {
24  if (size_t(sp.size()) >= str.size() + 2 && sp[str.size()] == '(' &&
25  sp[sp.size() - 1] == ')' &&
26  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  int level = 0;
35  auto it = sp.begin();
36  while (it != sp.end()) {
37  if (*it == '(') {
38  ++level;
39  } else if (level && *it == ')') {
40  --level;
41  } else if (level == 0 && (*it == ')' || *it == ',')) {
42  break;
43  }
44  ++it;
45  }
46  Span<const char> ret = sp.first(it - sp.begin());
47  sp = sp.subspan(it - sp.begin());
48  return ret;
49 }
50 
51 std::vector<Span<const char>> Split(const Span<const char> &sp, char sep) {
52  std::vector<Span<const char>> ret;
53  auto it = sp.begin();
54  auto start = it;
55  while (it != sp.end()) {
56  if (*it == sep) {
57  ret.emplace_back(start, it);
58  start = it + 1;
59  }
60  ++it;
61  }
62  ret.emplace_back(start, it);
63  return ret;
64 }
65 
66 } // namespace spanparsing
constexpr std::ptrdiff_t size() const noexcept
Definition: span.h:55
bool Func(const std::string &str, Span< const char > &sp)
Parse a function call.
Definition: spanparsing.cpp:23
constexpr C * end() const noexcept
Definition: span.h:52
bool Const(const std::string &str, Span< const char > &sp)
Parse a constant.
Definition: spanparsing.cpp:14
std::vector< Span< const char > > Split(const Span< const char > &sp, char sep)
Split a string on every instance of sep, returning a vector.
Definition: spanparsing.cpp:51
Span< const char > Expr(Span< const char > &sp)
Extract the expression that sp begins with.
Definition: spanparsing.cpp:33
constexpr Span< C > subspan(std::ptrdiff_t offset) const noexcept
Definition: span.h:60
constexpr Span< C > first(std::ptrdiff_t count) const noexcept
Definition: span.h:67
constexpr C * begin() const noexcept
Definition: span.h:51
A Span is an object that can refer to a contiguous sequence of objects.
Definition: span.h:17