ForestHub SDK 0.1.0
C++14 LLM SDK for PC and embedded platforms
Loading...
Searching...
No Matches
strprintf.hpp
Go to the documentation of this file.
1// SPDX-License-Identifier: AGPL-3.0-only
2// Copyright (c) 2026 ForestHub. All rights reserved.
3// For commercial licensing, visit https://github.com/ForestHubAI/fh-sdk
4
5#ifndef FORESTHUB_UTIL_STRPRINTF_HPP
6#define FORESTHUB_UTIL_STRPRINTF_HPP
7
10
11#include <cstdarg>
12#include <cstdio>
13#include <string>
14
15namespace foresthub {
16namespace util {
17
30#if defined(__GNUC__) || defined(__clang__)
31// GCC/Clang: Enable compile-time format string checking.
32// Argument indices: 1 = format string, 2 = first vararg (free function, no implicit 'this')
33inline std::string StrPrintf(const char* fmt, ...) __attribute__((format(printf, 1, 2)));
34#else
35inline std::string StrPrintf(const char* fmt, ...);
36#endif
37
38inline std::string StrPrintf(const char* fmt, ...) {
39 va_list args1, args2;
40 va_start(args1, fmt);
41 va_copy(args2, args1);
42
43 int len = vsnprintf(nullptr, 0, fmt, args1); // Pass 1: measure exact size
44 va_end(args1);
45
46 if (len <= 0) {
47 va_end(args2);
48 return "";
49 }
50
51 std::string result(static_cast<size_t>(len), '\0'); // ONE allocation, exact size
52 vsnprintf(&result[0], static_cast<size_t>(len) + 1, fmt, args2); // Pass 2: write
53 va_end(args2);
54
55 return result; // RVO - no copy
56}
57
58} // namespace util
59} // namespace foresthub
60
61#endif // FORESTHUB_UTIL_STRPRINTF_HPP
Utility types: Optional polyfill, JSON Schema normalization, Ticker.
std::string StrPrintf(const char *fmt,...)
Builds a std::string using printf-style formatting.
Definition strprintf.hpp:38
Top-level namespace for the ForestHub SDK.