Files
spark/src/lib/utils/string_utils.h
T
2025-01-03 16:59:07 +00:00

105 lines
2.1 KiB
C++

#pragma once
#include <cstddef>
#include <string>
namespace bts::system::string_utils {
template <int N>
bool copy_to_array(
const std::string &src,
std::array<char, N> &dest,
bool null_terminate = true);
template <class UIntType>
bool parse_uint(const std::string &s, UIntType &i);
void to_upper(std::string &str);
std::string copy_to_upper(const std::string &str);
//////////////////////////////////////////////////
// Definition
//////////////////////////////////////////////////
template <int N>
bool copy_to_array(
const std::string &src, std::array<char, N> &dest, bool null_terminate) {
std::size_t i = 0;
auto sz = dest.size();
if (null_terminate) {
sz--;
}
if (src.size() < sz) {
sz = src.size();
}
for (; i < sz; i++) {
dest[i] = src.at(i);
}
if (null_terminate) {
dest[sz] = '\0';
}
return src.size() < dest.size() ||
(!null_terminate && src.size() == dest.size());
}
template <class UIntType>
inline bool parse_uint(const std::string &s, UIntType &i) {
i = 0;
const auto sz = s.size();
int pow10 = 1;
for (std::size_t n = 0; n < sz; n++) {
switch (s[sz - n - 1]) {
case '0':
break;
case '1':
i += pow10;
break;
case '2':
i += 2 * pow10;
break;
case '3':
i += 3 * pow10;
break;
case '4':
i += 4 * pow10;
break;
case '5':
i += 5 * pow10;
break;
case '6':
i += 6 * pow10;
break;
case '7':
i += 7 * pow10;
break;
case '8':
i += 8 * pow10;
break;
case '9':
i += 9 * pow10;
break;
default:
return false;
}
pow10 *= 10;
}
return true;
}
inline void to_upper(std::string &str) {
for (char &c : str) {
c = toupper(c);
}
}
inline std::string copy_to_upper(const std::string &str) {
std::string s;
s.reserve(str.size());
for (char c : str) {
s.push_back(toupper(c));
}
return s;
}
} // namespace bts::system::string_utils