From a36a64264207d0651e5a0798ce60264adc0fec54 Mon Sep 17 00:00:00 2001 From: adsads121 <2457758003@qq.com> Date: Wed, 22 Oct 2025 20:05:47 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=20format=20=E5=87=BD?= =?UTF-8?q?=E6=95=B0=E5=8F=8A=E6=B5=8B=E8=AF=95=E7=94=A8=E4=BE=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- format.h | 32 ++++++++++++++++++++++++++++++++ test.cc | 15 +++++++++++++++ 2 files changed, 47 insertions(+) create mode 100644 format.h create mode 100644 test.cc diff --git a/format.h b/format.h new file mode 100644 index 00000000..f201f65c --- /dev/null +++ b/format.h @@ -0,0 +1,32 @@ + +#ifndef FORMAT_SHORT_H // 防止头文件重复包含(重要) +#define FORMAT_SHORT_H + +#include +#include // 假设依赖 fmt 库的基础类型(如 string_view、memory_buffer) + +namespace fmt { + /** + * 快速格式化短字符串,优先使用栈上缓冲区减少堆分配 + * @param format_str 格式化字符串 + * @param args 可变参数列表 + * @return 格式化后的字符串 + */ + template + 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 diff --git a/test.cc b/test.cc new file mode 100644 index 00000000..56e350c8 --- /dev/null +++ b/test.cc @@ -0,0 +1,15 @@ +#include +#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; +} \ No newline at end of file