添加 format 函数及测试用例

This commit is contained in:
adsads121 2025-10-22 20:05:47 +08:00
parent d6bdb69c62
commit a36a642642
2 changed files with 47 additions and 0 deletions

32
format.h Normal file
View File

@ -0,0 +1,32 @@
#ifndef FORMAT_SHORT_H // 防止头文件重复包含(重要)
#define FORMAT_SHORT_H
#include <string>
#include <fmt/format.h> // 假设依赖 fmt 库的基础类型(如 string_view、memory_buffer
namespace fmt {
/**
* 使
* @param format_str
* @param args
* @return
*/
template <typename... Args>
std::string format_short(string_view format_str, const Args&... args) {
constexpr size_t STACK_BUFFER_SIZE = 256; // 栈缓冲区大小
char stack_buffer[STACK_BUFFER_SIZE]; // 栈上分配缓冲区
memory_buffer buf(stack_buffer, stack_buffer + STACK_BUFFER_SIZE);
try {
// 复用 fmt 库的 vformat_to 进行格式化
vformat_to(buf, format_str, make_format_args(args...));
return std::string(buf.data(), buf.size());
} catch (const buffer_overflow&) {
// 缓冲区不足时,降级为动态分配
return format(format_str, args...);
}
}
}
#endif // FORMAT_SHORT_H

15
test.cc Normal file
View File

@ -0,0 +1,15 @@
#include <iostream>
#include "format.h"
int main() {
// Test short string formatting
std::string short_result = fmt::format_short("Hello, {}!", "World");
std::cout << "Short string test: " << short_result << std::endl;
// Test long string (trigger dynamic allocation)
std::string long_str(300, 'a');
std::string long_result = fmt::format_short("{}", long_str);
std::cout << "Long string test: " << (long_result == long_str ? "Success" : "Failed") << std::endl;
return 0;
}