Repository navigation
feat(format): add generic {} placeholder to fl::printf/snprintf (#3174) - #3757
Conversation
Callers no longer have to hand-pick between %d / %u / %ld / %s / %p or
write .c_str(): "{}" selects the natural specifier for the argument's C++
type. Also adds the mismatch-safety and malformed-format test coverage
the issue asks for.
Size-safety is the central design constraint. The obvious implementation
-- route "{}" through sstream::operator<< -- is exactly what #3158
rejected ("the operator<< chains still instantiate per-site... doesn't
actually shrink the binary"), a migration worth ~5-10 KB on ESP32-S3;
#3078 measured sstream::operator<<(char) at 1.25 KB alone, and
check_esp32_size.yml gates Blink at 330,000 B.
So "{}" instead picks a FormatSpec and calls the SAME format_arg the '%'
path uses, and is SFINAE-constrained to the type set '%' already
supports. Verified empirically: a TU using "{}" and the same TU using the
hand-picked '%' specifier emit identical symbol tables (nm, 299 symbols,
10 argument types). Passing an unsupported type is a compile error, so no
heavy operator<< chain can be instantiated per call site.
One caveat is documented in the header rather than glossed: format_impl
compiles its "{}" branch even for '%'-only call sites, since the format
string is a runtime pointer. Those sites emit small format_arg_generic<T>
forwarders that tail-call into already-existing format_arg<T>.
Two bugs fixed along the way, neither of them "{}"-specific:
- parse_format_spec advanced past the type character unconditionally. For
a format string ending mid-specifier the type char IS the NUL, so the
pointer stepped past the buffer and the caller's `while (*format)` read
heap garbage. Reproduced pre-fix on "%", "abc%", "%-", "%5", "%.",
"%l", "%#0". This changes '%'-path behavior: snprintf(buf, n, "done %",
42) now yields "done <unknown_format>".
- An unscoped enum fails is_integral but implicitly converts to char, so
"{}" silently selected the char overload: enum Color { GREEN = 66 }
printed "B" instead of "66". Added an is_enum overload routing through
underlying_type. Scoped enums remain a compile error through both "{}"
and %d, unchanged.
Tests: 25 cases in tests/fl/stl/stdio.cpp covering every scenario in the
acceptance criteria -- {} across scalar/string/pointer types, byte-identical
agreement with the equivalent '%' spelling, too-few/extra args, {{ and }}
escaping, lone and trailing braces, mixed {} and %, the documented '%'
mismatch sentinels (asserted, not changed), truncated specifiers at
end-of-string under ASAN, and buffer-boundary truncation. The enum and
OOB tests were both mutation-checked against a reverted fix.
Co-Authored-By: Claude <[email protected]>
📝 WalkthroughWalkthroughadds type-aware ChangesGeneric formatter support
Estimated code review effort: 4 (Complex) | ~45 minutes Sequence Diagram(s)sequenceDiagram
participant Caller
participant fl_snprintf
participant format_impl
participant parse_brace
participant format_arg_generic
Caller->>fl_snprintf: format string and arguments
fl_snprintf->>format_impl: process formatting request
format_impl->>parse_brace: inspect `{}`, `{{`, or `}}`
parse_brace-->>format_impl: parsed brace result
format_impl->>format_arg_generic: format next argument
format_arg_generic-->>format_impl: formatted value
format_impl-->>fl_snprintf: assembled output
fl_snprintf-->>Caller: formatted or truncated string
🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
🧹 Nitpick comments (1)
src/fl/stl/stdio.h (1)
75-91: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value
fl::sprintf's doc block was not updated for{}.
sprintfforwards tosnprintf, so it supports the placeholder too, but its Doxygen block (the declaration at Line 100-116 and the definition-site block) still documents only%specifiers. Worth a one-line pointer there for consistency.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@src/fl/stl/stdio.h` around lines 75 - 91, Update the Doxygen documentation for fl::sprintf at its declaration and definition-site comment to mention that it also supports the {} generic placeholder, consistent with its forwarding to snprintf. Keep the existing % specifier documentation unchanged and add only a concise cross-reference.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Nitpick comments:
In `@src/fl/stl/stdio.h`:
- Around line 75-91: Update the Doxygen documentation for fl::sprintf at its
declaration and definition-site comment to mention that it also supports the {}
generic placeholder, consistent with its forwarding to snprintf. Keep the
existing % specifier documentation unchanged and add only a concise
cross-reference.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro Plus
Run ID: d4ac7e49-b5b1-4bc6-988c-d03d6f8e79bd
📒 Files selected for processing (2)
src/fl/stl/stdio.htests/fl/stl/stdio.cpp
Closes #3174.
Adds a generic
{}placeholder tofl::printf/fl::snprintf/fl::sprintf, plus the mismatch-safety and malformed-format test coverage the issue asks for.Size-safety is the central constraint
The obvious implementation — route
{}throughsstream::operator<<, which already handlesCRGB,vec2,vector, maps — is exactly what #3158 rejected:That migration was worth ~5-10 KB on ESP32-S3, #3078 measured
sstream::operator<<(char)at 1.25 KB alone, andcheck_esp32_size.ymlgates Blink at 330,000 B.So
{}instead picks aFormatSpecand calls the sameformat_argthe%path uses, SFINAE-constrained to the type set%already supports (integral, bool, char, float/double,const char*,fl::string,fl::string_view, pointers, unscoped enums).Verified empirically, not just argued: a TU using
{}and the same TU using the hand-picked%specifier emit identical symbol tables (nm -C, 299 symbols, 10 argument types). Passing an unsupported type is a compile error, so no heavyoperator<<chain can be instantiated per call site.One caveat, documented in the header rather than glossed:
format_implcompiles its{}branch even for%-only call sites, because the format string is a runtime pointer and the branch can't be discarded. Those sites emit smallformat_arg_generic<T>forwarders they didn't have before — each a one-line tail call into an already-existingformat_arg<T>that inlines at-Os, but the cost is tree-wide, not only for{}users.Two bugs fixed along the way — neither is
{}-specific1. Out-of-bounds read in
parse_format_spec. It advanced past the type character unconditionally. For a format string ending mid-specifier the type char is the NUL terminator, so the pointer stepped past the buffer and the caller'swhile (*format)read heap garbage. Reproduced pre-fix with an exact-size heap buffer:Failing inputs:
"%","abc%","%-","%5","%.","%l","%ll","%h","%#0","%.3","%05".%-path behavior:snprintf(buf, n, "done %", 42)now yields"done <unknown_format>". Flagging explicitly since the rest of the PR is additive — happy to split it into its own commit if you'd prefer.2. Unscoped enums silently rendered as a character. An unscoped enum fails
is_integralbut implicitly converts tochar, so{}selected thecharoverload:enum Color { GREEN = 66 }printedBinstead of66. Silent wrong output, and it contradicted the documented compile-error promise. Fixed with anis_enumoverload routing throughunderlying_type.Scoped enums (
enum class) remain a compile error through both{}and%d— unchanged by this PR, sinceformat_arg's body needs an implicit conversion they don't have.Behavior
{}{{/}}{/}{or}{}with no argument left<missing_arg>, matching the%path%pathExisting
%mismatch sentinels (<type_error>,<string_not_hex>,<unknown_format>,(null)) are asserted in tests, not changed.Tests
25 cases in
tests/fl/stl/stdio.cppcovering every acceptance-criteria scenario:{}across scalar/string/pointer types, byte-identical agreement with the equivalent%spelling, too-few/extra args, brace escaping, mixed{}and%, the documented mismatch sentinels, truncated specifiers at end-of-string under ASAN, and buffer-boundary truncation.The enum and OOB regression tests were mutation-checked against a reverted fix — both fail without their fix, so neither is a passing-by-accident test.
Verification
bash test --cpp --clean— 357/357bash test --cpp fl_stl_stdio --debug— ASAN/LSAN/UBSAN cleanbash lint— exit 0nmsymbol-table comparison,{}vs%— identicalNote for the reviewer
#3158's closing comment lists ~12 headers that cannot migrate off
operator<<because "the payload type is not known at the call site" (fl/task/promise.h,fl/stl/json/types.h,fl/stl/shared_ptr.h, …). An unrestricted{}is what would let those migrate, and for those sites it would be size-neutral since they already instantiateoperator<<. I deliberately did not do that here — conservative first landing; it can be added later on evidence rather than speculation.🤖 Generated with Claude Code
Summary by CodeRabbit
New Features
{}placeholders in formatting functions.{{and}}.{}placeholders can be combined with existing%-style formats.Bug Fixes