97 lines
2.5 KiB
C++
97 lines
2.5 KiB
C++
#include <algorithm>
|
|
#include <cstring>
|
|
#include <fstream>
|
|
#include <string>
|
|
#include <vector>
|
|
|
|
#include "usenetsearch/StringUtils.h"
|
|
|
|
namespace usenetsearch {
|
|
|
|
std::ostream& operator<<(std::ofstream& out, const std::string& str)
|
|
{
|
|
const std::uint64_t size = str.size();
|
|
out.write(reinterpret_cast<const char*>(&size), sizeof(size));
|
|
out.write(reinterpret_cast<const char*>(str.c_str()), size);
|
|
return out;
|
|
}
|
|
|
|
std::ifstream& operator>>(std::ifstream& in, std::string& str)
|
|
{
|
|
std::uint64_t size{0};
|
|
in.read(reinterpret_cast<char*>(&size), sizeof(size));
|
|
char buf[size];
|
|
in.read(buf, size);
|
|
buf[size] = 0;
|
|
str = buf;
|
|
return in;
|
|
}
|
|
|
|
std::ostream& operator<<(std::ofstream& out, const std::wstring& str)
|
|
{
|
|
const std::uint64_t size = str.size();
|
|
out.write(reinterpret_cast<const char*>(&size), sizeof(size));
|
|
out.write(
|
|
reinterpret_cast<const char*>(str.c_str()),
|
|
size * sizeof(wchar_t)
|
|
);
|
|
return out;
|
|
}
|
|
|
|
std::ifstream& operator>>(std::ifstream& in, std::wstring& str)
|
|
{
|
|
std::uint64_t size{0};
|
|
in.read(reinterpret_cast<char*>(&size), sizeof(size));
|
|
wchar_t buf[size];
|
|
in.read(reinterpret_cast<char*>(buf), size * sizeof(wchar_t));
|
|
buf[size] = 0;
|
|
str = buf;
|
|
return in;
|
|
}
|
|
|
|
std::string StringLeftTrim(const std::string& str)
|
|
{
|
|
std::string s = str;
|
|
s.erase(s.begin(), std::find_if(s.begin(), s.end(),
|
|
std::not1(std::ptr_fun<int, int>(std::isspace))));
|
|
return s;
|
|
}
|
|
|
|
std::string StringRightTrim(const std::string& str)
|
|
{
|
|
std::string s = str;
|
|
s.erase(std::find_if(s.rbegin(), s.rend(),
|
|
std::not1(std::ptr_fun<int, int>(std::isspace))).base(),
|
|
s.end());
|
|
return s;
|
|
}
|
|
|
|
bool StringStartsWith(const std::string& needle, const std::string& haystack)
|
|
{
|
|
return (std::strncmp(haystack.c_str(),needle.c_str(),needle.size()) == 0);
|
|
}
|
|
|
|
bool StringToBoolean(const std::string& str)
|
|
{
|
|
const std::string lstr = StringTrim(StringToLower(str));
|
|
if ((lstr == "true") || (lstr == "yes") || (lstr == "1")) return true;
|
|
if ((lstr == "false") || (lstr == "no") || (lstr == "0")) return false;
|
|
throw StringException(EINVAL,
|
|
"The string \"" + str + "\" is not a valid boolean value."
|
|
);
|
|
}
|
|
|
|
std::string StringToLower(const std::string& str)
|
|
{
|
|
std::string copy = str;
|
|
std::transform(copy.begin(),copy.end(),copy.begin(),::tolower);
|
|
return copy;
|
|
}
|
|
|
|
std::string StringTrim(const std::string& str)
|
|
{
|
|
return StringLeftTrim(StringRightTrim(str));
|
|
}
|
|
|
|
} // namespace usenetsearch
|