Skip to content

refactor(printf): replace C snprintf with fl::snprintf in libFastLED.a (#2773 batch-1 item 1.1) - #2774

Closed
zackees wants to merge 2 commits into
masterfrom
feat/2773-eliminate-c-snprintf
Closed

zackees wants to merge 2 commits into
masterfrom
feat/2773-eliminate-c-snprintf

Conversation

@zackees

@zackees zackees commented Jun 5, 2026 •

Copy link
Copy Markdown
Member

Summary

Migrates all 12 C snprintf call sites inside libFastLED.a to the
template-based fl::snprintf (src/fl/stl/stdio.h:659), routing format
output through fl::sstream instead of newlib's heavy _svfprintf_r
engine.

Implements item 1.1 of the binary-size meta-issue: #2773.

Per-file changes

File C snprintf call sites migrated
src/platforms/esp/32/ota/ota_impl.cpp.hpp 7 (hex byte encoding, auth string)
src/fl/net/http/chunked_encoding.cpp.hpp 2 (%zx hex length)
src/fl/net/http/stream_client.cpp.hpp 1 (%u port)
src/fl/stl/asio/ip/tcp.cpp.hpp 1 (%u port)
src/fl/stl/asio/http/server.cpp.hpp 1 (%d HTTP status)

fl::snprintf supports %02x, %zx, %u, %d, %s, %p, %X, %c,
%f, %% with full width/zero-padding flags — verified against the
specifiers used here.

Verification

  • Host C++ unit tests: 309/309 passed (bash test --cpp).

  • ESP32-S3 Blink: builds clean (bash compile esp32s3 --examples Blink --platformio).

  • libFastLED.a no longer has any snprintf relocations:

    for obj in fl.audio+ fl.net+ fl.stl+ platforms+ third_party+; do
      xtensa-esp32s3-elf-objdump -r .pio/build/esp32s3/lib311/FastLED/fl/build/\${obj}.cpp.o \
        | grep -c snprintf
    done
    # all zero after this PR
    
  • Lint: bash lint clean (also includes a drive-by KBI002 fix on
    ci/autoresearch/test_flexio_rx_objectfled.py:172 that the Stop hook
    surfaced — except KeyboardInterrupt: handler now calls
    handle_keyboard_interrupt(ki) before re-raising, matching the
    pattern in ci/autoresearch_loop.py).

Honest size impact: only ~100 B

firmware.bin shrinks from 673,504 B → 673,402 B (–102 B). The original
#2773 estimate of ~11 KB assumed that removing FastLED's C
snprintf references would let the linker drop libc_a-snprintf.o and
therefore _svfprintf_r (11 KB). It does not, because:

libesp_common.a(esp_err_to_name.c.obj)  ──refs──>  snprintf
  └─ called from FastLED:
     fl::detail::Rmt5PeripheralESPImpl::createTxChannel
     fl::detail::Rmt5PeripheralESPImpl::transmit
     fl::detail::Rmt5PeripheralESPImpl::waitAllDone
     fl::detail::Rmt5EncoderImpl::initialize

esp_err_to_name(err) is called inside FastLED's RMT5 layer for
FL_WARN/FL_LOG_RMT messages. Its unknown-error fallback path uses
snprintf to format \"UNKNOWN ERROR (0x%x)\", so the linker pulls
libc_a-snprintf.o even though we've eliminated FastLED's direct
references.

Follow-up that would actually unlock the 11 KB

A separate PR can replace esp_err_to_name(err) in FastLED's RMT layer
with either:

  1. A snprintf-free local helper (lookup table + raw hex code for
    unknown), or
  2. An unconditional elision of the error name when
    FASTLED_LOG_VERBOSITY=0 (Meta: ESP32-S3 binary-size reduction — Batch 1 (~26 KB) + Batch 2 (~26–50 KB) (supersedes #2771) #2773 item 2.3) is set.

Either route closes the gap.

Why ship this even though savings are small

  • Mechanical, low-risk migration that's a prerequisite for the
    eventual 11 KB win.
  • Removes 18 cross-TU symbol references that were tying libFastLED.a
    to newlib's printf engine — useful for any future
    esp_err_to_name-replacement work.
  • Adds no API surface; pure internal refactor.
  • Sets up clean ground for Meta: ESP32-S3 binary-size reduction — Batch 1 (~26 KB) + Batch 2 (~26–50 KB) (supersedes #2771) #2773 item 1.5 (lint rule banning direct
    ::snprintf/::printf in src/) — the next PR can add the rule
    without any pre-existing violations to grandfather.

Test plan

  • bash test --cpp → 309/309 pass
  • bash compile esp32s3 --examples Blink --platformio → builds clean
  • bash lint → clean
  • Manual verification: objdump -r on all lib311/FastLED/fl/build/*.cpp.o shows zero snprintf relocations
  • CI green

Closes none (item 1.1 of #2773; the meta-issue stays open for the other
seven items).

🤖 Generated with Claude Code

Summary by CodeRabbit

  • Chores
    • Standardized string-formatting across networking and firmware update code.
    • Added a C/C++ lint check to enforce use of project-safe printf wrappers.
  • Bug Fixes
    • Improved keyboard-interrupt handling in test utilities for more reliable error capture.

#2773 item 1.1)

Migrates all 12 C `snprintf` call sites inside libFastLED.a to the
template-based `fl::snprintf` (`src/fl/stl/stdio.h:659`), which routes
formatting through `fl::sstream` instead of newlib's `_svfprintf_r`.

Per-file:
- src/platforms/esp/32/ota/ota_impl.cpp.hpp (7 sites — hex encoding, auth string)
- src/fl/net/http/chunked_encoding.cpp.hpp  (2 sites — %zx hex)
- src/fl/net/http/stream_client.cpp.hpp     (1 site — %u port)
- src/fl/stl/asio/ip/tcp.cpp.hpp            (1 site — %u port)
- src/fl/stl/asio/http/server.cpp.hpp       (1 site — %d HTTP status)

Verified `_svfprintf_r` no longer has a libFastLED.a reference after
this change (`objdump -r .pio/build/.../platforms+.cpp.o | grep snprintf`
returns nothing). esp32s3 Blink builds clean; host tests pass 309/309.

## Net `firmware.bin` impact: only ~100 B

Saving is much smaller than #2773's original ~11 KB estimate. The
remaining `_svfprintf_r` (11 KB) is now pulled entirely by
ESP-IDF code that FastLED still depends on:

- `libesp_common.a(esp_err_to_name.c.obj)` references `snprintf` for its
  unknown-error fallback path
- `esp_err_to_name(err)` is called by FastLED's `rmt5_peripheral_esp.cpp.hpp`
  (and other RMT layers) inside FL_WARN/FL_LOG_RMT messages

A follow-up PR that replaces `esp_err_to_name(err)` with a snprintf-free
helper (or unconditionally elides the error name from FL_WARN in release
builds) would close the gap and unlock the original 11 KB win.

Note: this PR also includes a drive-by fix for a KBI002 lint failure on
`ci/autoresearch/test_flexio_rx_objectfled.py` that the Stop hook surfaced
during commit — handler now calls `handle_keyboard_interrupt(ki)` before
re-raising, matching the pattern in `ci/autoresearch_loop.py`.

Issue: #2773

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@coderabbitai

coderabbitai Bot commented Jun 5, 2026 •

Copy link
Copy Markdown

Review Change Stack

Caution

Review failed

The pull request is closed.

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 9ba6e2ac-3d31-4108-8885-54a7e910690f

📥 Commits

Reviewing files that changed from the base of the PR and between cf220bd and 55bde0a.

📒 Files selected for processing (3)
  • ci/lint_cpp/cstdio_printf_checker.py
  • ci/lint_cpp/run_all_checkers.py
  • ci/lint_cpp/test_cstdio_printf_checker.py

📝 Walkthrough

Walkthrough

CI test KeyboardInterrupt exceptions now route through a global handler. Across multiple C++ files, snprintf calls are replaced with fl::snprintf by including fl/stl/stdio.h. A new CI checker flags raw cstdio printf-family usage and is registered and tested.

Changes

KeyboardInterrupt Handler Integration

Layer / File(s) Summary
Global interrupt handler routing
ci/autoresearch/test_flexio_rx_objectfled.py
Serial port initialization captures KeyboardInterrupt as ki and passes it to handle_keyboard_interrupt(ki) from the global interrupt handler instead of a bare catch block.

snprintf to fl::snprintf Migration

Layer / File(s) Summary
HTTP and TCP snprintf wrapping
src/fl/net/http/chunked_encoding.cpp.hpp, src/fl/net/http/stream_client.cpp.hpp, src/fl/stl/asio/http/server.cpp.hpp, src/fl/stl/asio/ip/tcp.cpp.hpp
Adds fl/stl/stdio.h and replaces snprintf with fl::snprintf for chunk-size strings, client port formatting, server status-code formatting, and TCP socket port formatting.
ESP32 OTA snprintf wrapping
src/platforms/esp/32/ota/ota_impl.cpp.hpp
Adds fl/stl/stdio.h and replaces snprintf with fl::snprintf across nonce generation, auth verification hex encoding, expected-response, firmware MD5 hex computation, and UDP OTA auth response formatting.

C stdio usage CI checker and tests

Layer / File(s) Summary
Checker implementation and CLI
ci/lint_cpp/cstdio_printf_checker.py
Adds CstdioPrintfChecker that detects raw printf/snprintf/fprintf-family uses (with opt-out marker), skips excluded paths, and exposes a main() CLI to run over src/ or a single file.
Runner registration and tests
ci/lint_cpp/run_all_checkers.py, ci/lint_cpp/test_cstdio_printf_checker.py
Registers the checker for the src scope and adds unit tests covering forbidden/allowed patterns, comment/include ignoring, path exclusions, opt-out behavior, and format-specifier edge cases.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

  • FastLED/FastLED#2277: Related KeyboardInterrupt forwarding changes in autoresearch serial-open paths addressing similar exception propagation.

Poem

🐰 I hop through code with careful paws,
swapping snprintf for safer laws,
when Ctrl+C rings the test-run bell,
I send it where the handlers dwell.
A tiny wrapper, neat and spry—hip, hop, hooray!

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 50.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly and specifically describes the main change: replacing C snprintf with fl::snprintf throughout libFastLED.a, with context indicating this is batch-1 item 1.1 of a larger refactoring effort (#2773).
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ 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/2773-eliminate-c-snprintf
⚔️ Resolve merge conflicts
  • Resolve merge conflict in branch feat/2773-eliminate-c-snprintf

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 and usage tips.

@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.

Actionable comments posted: 1

🤖 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.

Inline comments:
In `@ci/autoresearch/test_flexio_rx_objectfled.py`:
- Around line 175-177: The import of handle_keyboard_interrupt is currently
inside an except block; move the import statement for handle_keyboard_interrupt
to the top-level imports (after the existing from typeguard import typechecked)
so all imports are grouped properly, and then remove the in-block import (the
handle_keyboard_interrupt(ki) call should remain where it's used).
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: ce7d6c39-3810-4362-87b9-df5c2840c499

📥 Commits

Reviewing files that changed from the base of the PR and between b5e51c3 and cf220bd.

📒 Files selected for processing (6)
  • ci/autoresearch/test_flexio_rx_objectfled.py
  • src/fl/net/http/chunked_encoding.cpp.hpp
  • src/fl/net/http/stream_client.cpp.hpp
  • src/fl/stl/asio/http/server.cpp.hpp
  • src/fl/stl/asio/ip/tcp.cpp.hpp
  • src/platforms/esp/32/ota/ota_impl.cpp.hpp

Comment on lines +175 to +177
from ci.util.global_interrupt_handler import handle_keyboard_interrupt

handle_keyboard_interrupt(ki)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Move the import to the top of the file.

The import of handle_keyboard_interrupt should be placed at the top of the file with other imports, not inside the except block. As per coding guidelines, all system imports must be at the top of the file in proper order: standard library, third-party, local.

📦 Proposed fix to move import to top of file

Add the import after line 34 (after from typeguard import typechecked):

 from typeguard import typechecked
+from ci.util.global_interrupt_handler import handle_keyboard_interrupt
 

Then remove the import from the except block:

     except KeyboardInterrupt as ki:
         # Catch Ctrl-C before the bare `Exception`/`SerialException` block so
         # interactive users can abort cleanly without dumping a stack trace.
-        from ci.util.global_interrupt_handler import handle_keyboard_interrupt
-
         handle_keyboard_interrupt(ki)
         raise
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
from ci.util.global_interrupt_handler import handle_keyboard_interrupt
handle_keyboard_interrupt(ki)
handle_keyboard_interrupt(ki)
🤖 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 `@ci/autoresearch/test_flexio_rx_objectfled.py` around lines 175 - 177, The
import of handle_keyboard_interrupt is currently inside an except block; move
the import statement for handle_keyboard_interrupt to the top-level imports
(after the existing from typeguard import typechecked) so all imports are
grouped properly, and then remove the in-block import (the
handle_keyboard_interrupt(ki) call should remain where it's used).

…item 1.5) (#2777)

Adds `CstdioPrintfChecker` to the unified `ci/lint_cpp/` pipeline that
fails CI on direct C `snprintf` / `printf` / `sprintf` / `fprintf` /
`vfprintf` / `vsnprintf` / `vprintf` / `vsprintf` / `vfiprintf` calls
inside `src/`. Implements item **1.5** of the binary-size meta-issue
(#2773) — the regression guard for the cleanup landed in #2774.

Each such call drags newlib's `_svfprintf_r` (~11 KB on xtensa-esp-elf)
into `libFastLED.a`. The repo already ships `fl::snprintf` and
`fl::printf` at `src/fl/stl/stdio.h:659` which route through
`fl::sstream` and don't need the libc engine.

## Allowed forms (verified by tests)

- `fl::snprintf(...)`, `fl::printf(...)` — the FastLED wrappers.
- `obj.printf(...)`, `ptr->printf(...)` — member access.
- `SerialPort::printf(...)`, `MyClass::snprintf(...)` — any
  user-defined class method (qualified by an identifier other than `std`).
- `void printf(const char* fmt, ...)` — function declarations / definitions
  inside a class body (the prefix ends with a type identifier, not `::`).
- `my_snprintf(...)` — sub-word matches (defensive; `\b` already covers).

## Banned forms (verified by tests)

- bare `snprintf(...)`, `printf(...)`, etc. — no prefix.
- explicit `::printf(...)` — root-namespace C call.
- explicit `std::snprintf(...)` — C++ std namespace (still newlib on xtensa).

## Excluded paths (don't link newlib)

- `src/third_party/**` — third-party code defines its own conventions.
- `src/fl/stl/stdio.{h,hpp}` + `src/fl/stl/cstdio.*` — wrapper TUs that
  bridge at the C-API boundary.
- `src/platforms/wasm/**` — Emscripten libc, console-write.
- `src/platforms/{posix,apple,win}/**` — host-only test runners.
- `src/platforms/stub/**` — host-only stub.

## Opt-out

Append `// ok cstdio - <reason>` on the same line for genuine
platform-boundary cases.

## Verification

- 26 unit tests covering every allowed/banned/opt-out/exclusion case
  (`ci/lint_cpp/test_cstdio_printf_checker.py`): 26/26 pass.
- Full `bash lint` pipeline: clean, zero violations on `src/` after
  #2774 lands the snprintf → fl::snprintf migration.
- Registered in `ci/lint_cpp/run_all_checkers.py` under the `src` scope
  alongside the existing `CtypeGlobalChecker` (same shape: ban C
  free-function APIs that have `fl::` template wrappers).

Depends on #2774 — if rebased on master before that PR merges, the
linter would fail on the 12 pre-existing `snprintf` call sites the
PR migrates.

Issue: #2773

Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
@zackees

zackees commented Jun 5, 2026

Copy link
Copy Markdown
Member Author

Closing as fully obsolete after rebase against current master

Rebased this branch onto current master (which already has PR #2775 merged as commit 99ddad448). The result: zero-line diff.

File Status after rebase
src/platforms/esp/32/ota/ota_impl.cpp.hpp identical to master
src/fl/net/http/chunked_encoding.cpp.hpp identical to master
src/fl/net/http/stream_client.cpp.hpp identical to master
src/fl/stl/asio/ip/tcp.cpp.hpp identical to master
src/fl/stl/asio/http/server.cpp.hpp identical to master
ci/autoresearch/test_flexio_rx_objectfled.py master's version is strictly better (top-level from ci.util.global_interrupt_handler import handle_keyboard_interrupt + cleaner comment + KBI002-lint-required structure) — this PR's inline-import variant would be a regression

So nothing left to merge. All 5 snprintf-side source changes are already on master via #2775 (which also includes the BareSnprintfChecker lint guard from item 1.5).

The corrected ~0 B Blink-size impact (vs the original ~11 KB claim) is documented in #2773 here: #2773 (comment)

Closing — no action needed.

@zackees zackees closed this Jun 5, 2026
@fastled-project-sync fastled-project-sync Bot moved this from Triage to Done in FastLED Tracker Jun 5, 2026
@zackees
zackees deleted the feat/2773-eliminate-c-snprintf branch November 17, 2026 07:12
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.

1 participant