Toolbox snapshot
The Reactive C++ Toolbox
Loading...
Searching...
No Matches
Argv.cpp
Go to the documentation of this file.
1// The Reactive C++ Toolbox.
2// Copyright (C) 2013-2019 Swirly Cloud Limited
3// Copyright (C) 2021 Reactive Markets Limited
4//
5// Licensed under the Apache License, Version 2.0 (the "License");
6// you may not use this file except in compliance with the License.
7// You may obtain a copy of the License at
8//
9// http://www.apache.org/licenses/LICENSE-2.0
10//
11// Unless required by applicable law or agreed to in writing, software
12// distributed under the License is distributed on an "AS IS" BASIS,
13// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14// See the License for the specific language governing permissions and
15// limitations under the License.
16
17#include "Argv.hpp"
18
19#include <stdexcept>
20
21namespace toolbox {
22inline namespace util {
23using namespace std;
24
26{
27 ++it_;
28 if (val_) {
29 throw runtime_error{"unexpected value for option: " + string{opt_}};
30 }
31 next();
32}
33
35{
36 ++it_;
37 string_view val;
38 if (val_) {
39 val = *val_;
40 } else {
41 if (empty()) {
42 throw runtime_error{"missing value for option: " + string{opt_}};
43 }
44 val = *it_++;
45 }
46 next();
47 return val;
48}
49
50void ArgvLexer::next() noexcept
51{
52 if (empty()) {
53 opt_ = {};
54 val_.reset();
55 return;
56 }
57 const string_view arg{*it_};
58 if (!(arg.size() > 1 && arg[0] == '-')) {
59 // Positional argument.
60 opt_ = {};
61 val_ = arg;
62 return;
63 }
64
65 if (arg[1] == '-') {
66 if (arg.size() == 2) {
67 // Treat double dash as positional argument.
68 opt_ = {};
69 val_ = arg;
70 return;
71 }
72 // Long option.
73 const auto pos = arg.find_first_of('=', 2);
74 opt_ = arg.substr(2, pos - 2);
75 if (pos != string_view::npos) {
76 val_ = arg.substr(pos + 1);
77 } else {
78 val_.reset();
79 }
80 } else {
81 // Short option.
82 opt_ = arg.substr(1, 1);
83 if (arg.size() > 2) {
84 val_ = arg.substr(2);
85 } else {
86 val_.reset();
87 }
88 }
89}
90
91} // namespace util
92} // namespace toolbox
bool empty() const noexcept
Definition Argv.hpp:81
std::string_view arg() const noexcept
Definition Argv.hpp:83
std::string_view pop_value()
Definition Argv.cpp:34
STL namespace.
constexpr auto bind() noexcept
Definition Slot.hpp:92