Files
spark/src/lib/utils/string_utils.h
T

82 lines
1.8 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 Iter, class UIntType>
bool parse_uint(Iter first, Iter last, UIntType &i);
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) {
return parse_uint(s.begin(), s.end(), i);
}
template <class Iter, class UIntType>
inline bool parse_uint(Iter first, Iter last, UIntType &i) {
i = 0;
for (; first != last; first++) {
int digit = (*first - '0');
if (digit < 0 || digit > 9) {
return false;
}
i = i * 10 + digit;
}
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