Bitcoin Core  22.99.0
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 == '(' || *it == '{') {
38  ++level;
39  } else if (level && (*it == ')' || *it == '}')) {
40  --level;
41  } else if (level == 0 && (*it == ')' || *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
spanparsing::Split
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
spanparsing::Func
bool Func(const std::string &str, Span< const char > &sp)
Parse a function call.
Definition: spanparsing.cpp:23
Span::size
constexpr std::size_t size() const noexcept
Definition: span.h:182
Span
A Span is an object that can refer to a contiguous sequence of objects.
Definition: span.h:92
span.h
Span::begin
constexpr C * begin() const noexcept
Definition: span.h:170
spanparsing.h
spanparsing::Const
bool Const(const std::string &str, Span< const char > &sp)
Parse a constant.
Definition: spanparsing.cpp:14
spanparsing::Expr
Span< const char > Expr(Span< const char > &sp)
Extract the expression that sp begins with.
Definition: spanparsing.cpp:32
Span::first
CONSTEXPR_IF_NOT_DEBUG Span< C > first(std::size_t count) const noexcept
Definition: span.h:199
spanparsing
Definition: spanparsing.cpp:12
Span::end
constexpr C * end() const noexcept
Definition: span.h:171
Span::subspan
CONSTEXPR_IF_NOT_DEBUG Span< C > subspan(std::size_t offset) const noexcept
Definition: span.h:189