forked from open62541pp/open62541pp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstring_utils.cpp
53 lines (47 loc) · 1.41 KB
/
string_utils.cpp
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
#include "open62541pp/detail/string_utils.hpp"
#include <cstdio> // vsnprintf
#include <cstring>
namespace opcua::detail {
UA_String toNativeString(std::string_view src) noexcept {
UA_String s{src.size(), nullptr};
if (src.data() == nullptr) {
return s;
}
if (!src.empty()) {
s.data = (UA_Byte*)src.data(); // NOLINT
} else {
s.data = static_cast<UA_Byte*>(UA_EMPTY_ARRAY_SENTINEL); // NOLINT
}
return s;
}
UA_String allocNativeString(std::string_view src) {
UA_String s{src.size(), nullptr};
if (src.data() == nullptr) {
return s;
}
if (!src.empty()) {
s.data = static_cast<UA_Byte*>(UA_malloc(s.length)); // NOLINT
std::memcpy(s.data, src.data(), src.size());
} else {
s.data = static_cast<UA_Byte*>(UA_EMPTY_ARRAY_SENTINEL); // NOLINT
}
return s;
}
std::string toString(const char* format, va_list args) {
// NOLINTBEGIN
va_list argsCopy{};
va_copy(argsCopy, args);
const int charsToWrite = std::vsnprintf(nullptr, 0, format, argsCopy);
va_end(argsCopy);
// NOLINTEND
if (charsToWrite < 0) {
return {};
}
std::string buffer(charsToWrite, '\0');
const int charsWritten = std::vsnprintf(buffer.data(), buffer.size() + 1, format, args);
if (charsWritten < 0 || charsWritten > charsToWrite) {
return {};
}
return buffer;
}
} // namespace opcua::detail