You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

92 lines
2.5 KiB

/**
* Copyright (c) 2018 Niklas Rosenstein
* MIT licensed.
*
* @description Some useful string functions.
*/
#pragma once
#include <algorithm>
#include <cctype>
#include <functional>
#include <locale>
#include <cstring>
namespace niklasrosenstein {
/**
* Convert a string or data to a hexadecimal representation. The buffer
* must be double the size of the input data.
*/
// @{
inline void tohex(char* buffer, void const* data, size_t size) {
char const pool[] = "0123456789abcdef";
for (size_t i = 0; i < size; ++i) {
unsigned char c = reinterpret_cast<unsigned char const*>(data)[i];
buffer[i * 2 + 0] = pool[(c >> 4) & 0xf];
buffer[i * 2 + 1] = pool[(c >> 0) & 0xf];
}
}
template <class string=std::string>
inline string tohex(void const* data, size_t size) {
string r(size * 2, 0);
tohex(&r[0], data, size);
return r;
}
template <class string=std::string>
inline string tohex(const char* str) {
return tohex<string>(str, std::strlen(str));
}
template <class instring, class outstring=instring>
inline outstring tohex(instring const& str) {
return tohex<outstring>(str.c_str(), str.size());
}
// @}
/**
* Returns true if #c is a whitespace character, false if not.
* Unlike the standard #isspace(), this function does not assert whether
* a valid ASCII character was passed to it. For any character outside of
* the ASCII range, the function returns false.
*/
inline bool isspace(int chr) {
if (chr < 0 || chr > 255) return false;
else return ::isspace(chr);
}
/* Trims a string of whitespace from the left. */
inline std::string& ltrim(std::string& s) {
s.erase(s.begin(), std::find_if(s.begin(), s.end(), [] (auto&& c) { return !std::isspace(c); }));
return s;
}
/* Trims a string of whitespace from the right. */
inline std::string& rtrim(std::string& s) {
s.erase(std::find_if(s.rbegin(), s.rend(), [] (auto&& c) { return !std::isspace(c); }).base(), s.end());
return s;
}
/* Trims a string of whitespace from both ends. */
template <class string>
inline string& trim(string& s) {
return ltrim(rtrim(s));
}
/* Converts a string to lowercase. */
template <class string>
inline string& tolower(string& s) {
std::transform(s.begin(), s.end(), s.begin(), ::tolower);
return s;
}
/* Converts a string to uppercase. */
template <class string>
inline string& toupper(string& s) {
std::transform(s.begin(), s.end(), s.begin(), ::toupper);
return s;
}
} // namespace niklasrosenstein