2025-01-03 18:17:59 +08:00
|
|
|
#ifndef TOOLKIT_H
|
|
|
|
#define TOOLKIT_H
|
|
|
|
|
|
|
|
#include <charconv>
|
2025-01-06 14:51:33 +08:00
|
|
|
#include <cstring>
|
2025-01-03 18:17:59 +08:00
|
|
|
#include <expected>
|
2025-01-04 12:42:03 +08:00
|
|
|
#include <type_traits>
|
2025-01-06 14:11:58 +08:00
|
|
|
#include <string>
|
2025-01-06 14:51:33 +08:00
|
|
|
#include <cstdlib>
|
2025-01-06 14:11:58 +08:00
|
|
|
#include <ios>
|
2025-01-03 18:17:59 +08:00
|
|
|
|
|
|
|
//use for to_chars
|
|
|
|
constexpr size_t buffer_size = 32;
|
|
|
|
|
2025-01-06 14:11:58 +08:00
|
|
|
template <typename T>
|
|
|
|
concept _num_type = requires {
|
|
|
|
std::is_same_v<T, int> ||
|
|
|
|
std::is_same_v<T, float> ||
|
|
|
|
std::is_same_v<T, long> ||
|
|
|
|
std::is_same_v<T, double>;
|
|
|
|
};
|
|
|
|
|
2025-01-03 18:17:59 +08:00
|
|
|
namespace toolkit{
|
|
|
|
template<typename T>
|
2025-01-06 14:11:58 +08:00
|
|
|
std::expected<std::string, std::string> to_string(T value){
|
|
|
|
if constexpr (std::is_same_v<T, int> || std::is_same_v<T, float> || std::is_same_v<T, double>){
|
|
|
|
char buffer[buffer_size];
|
|
|
|
auto res = std::to_chars(buffer, buffer + buffer_size, value);
|
|
|
|
if (res.ec != std::errc()) {
|
|
|
|
return std::unexpected(std::make_error_code(res.ec).message());
|
|
|
|
}
|
|
|
|
return std::string(buffer, res.ptr - buffer);
|
|
|
|
} else if constexpr (std::is_same_v<typename std::remove_const<T>::type,
|
|
|
|
char *>) {
|
|
|
|
return std::to_string(value);
|
2025-01-03 18:17:59 +08:00
|
|
|
}
|
|
|
|
}
|
2025-01-06 14:11:58 +08:00
|
|
|
|
2025-01-04 12:42:03 +08:00
|
|
|
template<typename T = double>// requires std::is_same_v<T, std::string>
|
|
|
|
std::expected<T, std::string> stoi(const std::string& str){
|
|
|
|
T value;
|
|
|
|
auto res = std::from_chars(str.c_str(), str.c_str() + str.size(), value);
|
|
|
|
if(res.ec != std::errc()){
|
|
|
|
return std::unexpected(std::make_error_code(res.ec).message());
|
|
|
|
}
|
|
|
|
return value;
|
|
|
|
}
|
2025-01-06 14:51:33 +08:00
|
|
|
|
|
|
|
template <typename T>
|
|
|
|
requires std::is_same_v<std::string, T> || std::is_same_v<const char*, T>
|
|
|
|
std::string replace_string(const std::string& str, T d, T e){
|
|
|
|
std::string result = str;
|
|
|
|
if(d == e){
|
|
|
|
return result;
|
|
|
|
}
|
|
|
|
size_t len = 0;
|
|
|
|
while(true){
|
2025-01-06 14:58:59 +08:00
|
|
|
auto pos = result.find(d);
|
2025-01-06 14:51:33 +08:00
|
|
|
if(pos == std::string::npos){
|
|
|
|
return result;
|
|
|
|
}
|
|
|
|
if constexpr(std::is_same_v<T, const char*>){
|
|
|
|
len = std::strlen(d);
|
|
|
|
}else{
|
|
|
|
len = d.length();
|
|
|
|
}
|
|
|
|
result = result.replace(pos, len ,e);
|
|
|
|
}
|
|
|
|
}
|
2025-01-03 18:17:59 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
#endif
|