Bitcoin Core  0.19.99
P2P Digital Currency
spanparsing.cpp
Go to the documentation of this file.
1 // Copyright (c) 2018-2019 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 {
16  if ((size_t)sp.size() >= str.size() && 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 {
25  if ((size_t)sp.size() >= str.size() + 2 && sp[str.size()] == '(' && sp[sp.size() - 1] == ')' && std::equal(str.begin(), str.end(), sp.begin())) {
26  sp = sp.subspan(str.size() + 1, sp.size() - str.size() - 2);
27  return true;
28  }
29  return false;
30 }
31 
33 {
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 {
53  std::vector<Span<const char>> ret;
54  auto it = sp.begin();
55  auto start = it;
56  while (it != sp.end()) {
57  if (*it == sep) {
58  ret.emplace_back(start, it);
59  start = it + 1;
60  }
61  ++it;
62  }
63  ret.emplace_back(start, it);
64  return ret;
65 }
66 
67 } // namespace spanparsing
constexpr std::ptrdiff_t size() const noexcept
Definition: span.h:30
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:29
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:32
constexpr Span< C > subspan(std::ptrdiff_t offset) const noexcept
Definition: span.h:33
constexpr Span< C > first(std::ptrdiff_t count) const noexcept
Definition: span.h:35
constexpr C * begin() const noexcept
Definition: span.h:28
A Span is an object that can refer to a contiguous sequence of objects.
Definition: span.h:17
auto it
Definition: validation.cpp:362