86 lines
2.9 KiB
C++
86 lines
2.9 KiB
C++
#ifndef UTILS_H
|
||
#define UTILS_H
|
||
|
||
#include <chrono>
|
||
#include <string>
|
||
|
||
#include "nlohmann/json.hpp"
|
||
|
||
using json = nlohmann::json;
|
||
|
||
namespace utils
|
||
{
|
||
// 时间相关工具。
|
||
std::string get_current_time();
|
||
std::string get_current_timestamp();
|
||
|
||
// 通用 JSON 响应构造。
|
||
json create_error_response(int code, const std::string &message, const std::string &details = "");
|
||
json create_success_response(const json &data = {}, const std::string &message = "Success");
|
||
|
||
// UTF-8 校验与清洗。
|
||
bool is_valid_utf8(const std::string &str);
|
||
std::string sanitize_utf8(const std::string &str);
|
||
|
||
// 业务 API 响应格式。
|
||
json create_api_response(bool success, int code, const std::string &msg,
|
||
const std::string &req_code = "", const std::string &req_from = "",
|
||
const std::string &req_cmd = "", const json &res_data = json::object());
|
||
|
||
// Base64 与 URDF 处理。
|
||
std::string base64_decode(const std::string &encoded_string);
|
||
std::string base64_to_urdf(const std::string &base64_urdf);
|
||
bool save_base64_urdf_to_file(const std::string &base64_urdf, const std::string &filename);
|
||
bool validate_urdf_base64(const std::string &base64_urdf);
|
||
bool save_urdf_string_to_file(const std::string &urdf_content, const std::string &filename);
|
||
|
||
} // namespace utils
|
||
|
||
class StringUtils
|
||
{
|
||
public:
|
||
/**
|
||
* @brief 将包含单个分隔符的字符串拆分为两部分。
|
||
* @param str 要拆分的字符串。
|
||
* @param delimiter 分隔符,默认为 `_`。
|
||
* @return 第一个元素为分隔符前的内容,第二个元素为分隔符后的内容。
|
||
*/
|
||
static std::pair<std::string, std::string> splitByDelimiter(
|
||
const std::string &str,
|
||
char delimiter = '_');
|
||
|
||
/**
|
||
* @brief 专门拆分 `A_B` 形式的字符串。
|
||
* @param str 要拆分的字符串。
|
||
* @return 拆分后的两段内容。
|
||
*/
|
||
static std::pair<std::string, std::string> splitA_B(const std::string &str);
|
||
|
||
/**
|
||
* @brief 将字符串按分隔符拆成两段,并通过引用返回结果。
|
||
* @param str 要拆分的字符串。
|
||
* @param part1 返回第一段。
|
||
* @param part2 返回第二段。
|
||
* @param delimiter 分隔符,默认为 `_`。
|
||
* @return 找到分隔符返回 true,否则返回 false。
|
||
*/
|
||
static bool splitToTwoParts(
|
||
const std::string &str,
|
||
std::string &part1,
|
||
std::string &part2,
|
||
char delimiter = '_');
|
||
|
||
/**
|
||
* @brief 严格拆分字符串,要求只出现一个分隔符。
|
||
* @param str 要拆分的字符串。
|
||
* @param delimiter 分隔符,默认为 `_`。
|
||
* @return 拆分后的两段内容。
|
||
* @throws std::invalid_argument 当分隔符不存在或出现多次时抛出异常。
|
||
*/
|
||
static std::pair<std::string, std::string> splitStrict(
|
||
const std::string &str,
|
||
char delimiter = '_');
|
||
};
|
||
|
||
#endif // UTILS_H
|