forked from OpenVPN/openvpn3
-
Notifications
You must be signed in to change notification settings - Fork 0
/
argv.hpp
133 lines (114 loc) · 2.83 KB
/
argv.hpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
// OpenVPN -- An application to securely tunnel IP networks
// over a single port, with support for SSL/TLS-based
// session authentication and key exchange,
// packet encryption, packet authentication, and
// packet compression.
//
// Copyright (C) 2012-2017 OpenVPN Technologies, Inc.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License Version 3
// as published by the Free Software Foundation.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program in the COPYING file.
// If not, see <http://www.gnu.org/licenses/>.
#ifndef OPENVPN_COMMON_ARGV_H
#define OPENVPN_COMMON_ARGV_H
#include <cstring> // memcpy
#include <string>
#include <vector>
namespace openvpn {
class Argv : public std::vector<std::string>
{
public:
Argv(const size_t capacity=16)
{
reserve(capacity);
}
std::string to_string() const
{
std::string ret;
bool first = true;
for (const auto &s : *this)
{
if (!first)
ret += ' ';
ret += s;
first = false;
}
return ret;
}
};
class ArgvWrapper
{
public:
explicit ArgvWrapper(const std::vector<std::string>& argv)
{
size_t i;
argc = argv.size();
cargv = new char *[argc+1];
for (i = 0; i < argc; ++i)
cargv[i] = string_alloc(argv[i]);
cargv[i] = nullptr;
}
ArgvWrapper(ArgvWrapper&& rhs) noexcept
{
argc = rhs.argc;
cargv = rhs.cargv;
rhs.argc = 0;
rhs.cargv = nullptr;
}
ArgvWrapper& operator=(ArgvWrapper&& rhs) noexcept
{
del();
argc = rhs.argc;
cargv = rhs.cargv;
rhs.argc = 0;
rhs.cargv = nullptr;
return *this;
}
~ArgvWrapper()
{
del();
}
char *const *c_argv() const noexcept
{
return cargv;
}
char **c_argv() noexcept
{
return cargv;
}
size_t c_argc() const noexcept
{
return argc;
}
private:
ArgvWrapper(const ArgvWrapper&) = delete;
ArgvWrapper& operator=(const ArgvWrapper&) = delete;
static char *string_alloc(const std::string& s)
{
const char *sdata = s.c_str();
const size_t slen = s.length();
char *ret = new char[slen+1];
std::memcpy(ret, sdata, slen);
ret[slen] = '\0';
return ret;
}
void del()
{
for (size_t i = 0; i < argc; ++i)
delete [] cargv[i];
delete [] cargv;
}
size_t argc;
char **cargv;
};
}
#endif