Skip to content

feat(format): add generic {} placeholder to fl::printf/snprintf (#3174) - #3757

Merged
zackees merged 1 commit into
masterfrom
feat/3174-printf-generic-placeholders
Jul 29, 2026
Merged

zackees merged 1 commit into
masterfrom
feat/3174-printf-generic-placeholders

Conversation

@zackees

@zackees zackees commented Jul 29, 2026 •

Copy link
Copy Markdown
Member

Closes #3174.

Adds a generic {} placeholder to fl::printf / fl::snprintf / fl::sprintf, plus the mismatch-safety and malformed-format test coverage the issue asks for.

fl::printf("led {} at {} -> {}", i, name, color.c_str());   // no %d / %s / .c_str()

Size-safety is the central constraint

The obvious implementation — route {} through sstream::operator<<, which already handles CRGB, vec2, vector, maps — is exactly what #3158 rejected:

"the operator<< chains still instantiate per-site, they just write to the shim instead of to Serial" → "doesn't actually shrink the binary"

That migration was 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, 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 heavy operator<< chain can be instantiated per call site.

One caveat, documented in the header rather than glossed: format_impl compiles 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 small format_arg_generic<T> forwarders they didn't have before — each a one-line tail call into an already-existing format_arg<T> that inlines at -Os, but the cost is tree-wide, not only for {} users.

Two bugs fixed along the way — neither is {}-specific

1. 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's while (*format) read heap garbage. Reproduced pre-fix with an exact-size heap buffer:

!! POINTER PAST NUL for [%]
%  ->  out=[<missing_arg>?3]      <- heap garbage past the terminator

Failing inputs: "%", "abc%", "%-", "%5", "%.", "%l", "%ll", "%h", "%#0", "%.3", "%05".

⚠️ This changes %-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_integral but implicitly converts to char, so {} selected the char overload: enum Color { GREEN = 66 } printed B instead of 66. Silent wrong output, and it contradicted the documented compile-error promise. Fixed with an is_enum overload routing through underlying_type.

Scoped enums (enum class) remain a compile error through both {} and %d — unchanged by this PR, since format_arg's body needs an implicit conversion they don't have.

Behavior

Form Result
{} natural specifier for the argument's type
{{ / }} literal { / }
lone { or } passes through literally
{} with no argument left <missing_arg>, matching the % path
extra arguments ignored, matching the % path
unsupported type compile error

Existing % mismatch sentinels (<type_error>, <string_not_hex>, <unknown_format>, (null)) are asserted in tests, not changed.

Tests

25 cases in tests/fl/stl/stdio.cpp covering 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/357
  • bash test --cpp fl_stl_stdio --debug — ASAN/LSAN/UBSAN clean
  • bash lint — exit 0
  • nm symbol-table comparison, {} vs % — identical

Note 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 instantiate operator<<. 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

    • Added support for generic {} placeholders in formatting functions.
    • Added brace escaping with {{ and }}.
    • Generic placeholders support common scalar, pointer, enum, and character values.
    • {} placeholders can be combined with existing %-style formats.
  • Bug Fixes

    • Improved handling of missing or malformed format arguments.
    • Prevented truncated format specifiers from reading beyond the string.
    • Preserved safe, null-terminated output when formatting into small buffers.

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]>
@coderabbitai

coderabbitai Bot commented Jul 29, 2026 •

Copy link
Copy Markdown

Review Change Stack

📝 Walkthrough

Walkthrough

adds type-aware {} placeholders to fl::printf and fl::snprintf, supports escaped braces and missing-argument sentinels, hardens malformed % parsing, and adds extensive tests for formatting types, mismatches, malformed inputs, print handlers, and buffer boundaries.

Changes

Generic formatter support

Layer / File(s) Summary
Placeholder contract and type dispatch
src/fl/stl/stdio.h
Documents {} formatting, adds type-specific generic formatting and brace parsing, and prevents advancing past truncated format strings.
Placeholder execution paths
src/fl/stl/stdio.h
Updates base and recursive formatting paths to consume {}, format arguments generically, and emit <missing_arg>.
Formatter behavior and boundary tests
tests/fl/stl/stdio.cpp
Covers supported types, argument counts, escaped braces, mixed formats, print-handler output, malformed % formats, mismatch sentinels, truncation, and NUL termination.

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
Loading
🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly and concisely describes the main formatter change in this PR.
Linked Issues check ✅ Passed Adds {} placeholder support, mismatch-safety handling, and tests matching #3174's acceptance criteria.
Out of Scope Changes check ✅ Passed The changes stay focused on formatter behavior, safety fixes, and tests; no unrelated scope is introduced.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/3174-printf-generic-placeholders

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.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 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 {}.

sprintf forwards to snprintf, 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

📥 Commits

Reviewing files that changed from the base of the PR and between 6d18081 and 58e82be.

📒 Files selected for processing (2)
  • src/fl/stl/stdio.h
  • tests/fl/stl/stdio.cpp

@zackees
zackees merged commit f980b3b into master Jul 29, 2026
14 checks passed
@fastled-project-sync fastled-project-sync Bot moved this from Triage to Done in FastLED Tracker Jul 29, 2026
@zackees
zackees deleted the feat/3174-printf-generic-placeholders branch August 21, 2026 19:15
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

feat(format): add generic fl::printf placeholders and mismatch-safety tests

1 participant