Skip to content

feat(fl::sstream): Path C — literal-aware sstream + centralised log_emit - #2964

Closed
zackees wants to merge 4 commits into
masterfrom
feat/sstream-literal-aware
Closed

zackees wants to merge 4 commits into
masterfrom
feat/sstream-literal-aware

Conversation

@zackees

@zackees zackees commented Jun 7, 2026 •

Copy link
Copy Markdown
Member

Implements Path C from #2963 (the sstream cost-reduction audit). Folds FL_WARN_LIT's win into the default FL_WARN / FL_ERROR / FL_INFO macros automatically — zero source-site migration.

Two layers

Layer 1 — Literal-aware fl::sstream

operator<<(const char*) and template<fl::size N> operator<<(const char (&)[N]) now adopt the input as non-owning ConstLiteral storage (via the existing basic_string variant) whenever the sstream is still empty. A subsequent mutating << transparently materialises via basic_string::write()'s existing logic.

sstream &operator<<(const char *str) FL_NOEXCEPT {
    if (!str) return *this;
    if (mStr.empty() && !mStr.is_referencing()) {
        mStr.assign_literal(str);   // O(1), no copy, no buffer use
    } else {
        mStr.append(str);            // existing path
    }
    return *this;
}

New public fl::sstream::is_pure_literal() accessor for tests and future emit backends.

New public fl::basic_string::assign_literal(const char*) wrapper around the existing protected setLiteral(), so sstream (not derived from basic_string) can take the literal path without a friend declaration.

Layer 2 — Centralised fl::detail::log_emit

The legacy macro inlined the entire << file << '(' << line << \"): WARN: \" << X chain at every call site, emitting per-site code and .rodata for the prefix format. The new macro:

#define FL_WARN(X) fl::detail::log_emit( \
    fl::detail::log_kind::WARN, \
    fl::fastled_file_offset(__FILE__), int(__LINE__), \
    fl::sstream() << X)

The prefix-format chain now exists in exactly one place in the binary (defined out-of-line in fl/log/log.cpp.hpp) instead of ~1,372 inlined copies.

How the Path C optimisation fires automatically

Call shape sstream state after expansion Cost
FL_WARN(\"hello\") ConstLiteral storage; never materialises ~3 instructions at call site + one log_emit call; identical to legacy FL_WARN_LIT
FL_WARN(\"got \" << val) ConstLiteral until << val materialises Same as legacy FL_WARN
FL_WARN(some_obj) Empty → first << calls non-literal overload Same as legacy

No call-site migration. FL_WARN_LIT / FL_LOG_LIT remain available as hand-tuned hints with identical performance — they can be quietly deprecated as a follow-up.

Tests

tests/fl/stl/strstream.cpp adds 4 new FL_TEST_CASE blocks / 14 FL_SUBCASE assertions:

  • Single literal stays in literal storage (const char*, char array, c_str() returns the original pointer unchanged, nullptr no-op).
  • Mutation materialises (literal + integer / + char / + string / second literal).
  • Non-literal first write keeps is_pure_literal()==false (integer / char / string first).
  • Default-constructed sstream is not pure_literal.

Verification

What this PR does NOT do (deliberately)

Net effect today

Per-call-site cost of FL_WARN drops measurably:

  • The inline prefix-format chain (file + line + tag) → single helper call.
  • Single-literal payload skips materialisation → buffer never touched.
  • Existing << chain syntax preserved at every call site — no migration.

The full cost-reduction stack (A + B + C from the audit) should net 50-160 KB savings on ESP32-S3 Blink per the audit projection. This PR is the C piece. A and B (out-of-line bodies + log_emit centralisation) partially overlap — log_emit IS proposal B; the remaining proposal A work is moving the 27 non-template operator<< bodies, which can land as a follow-up.

Related

🤖 Generated with Claude Code

Summary by CodeRabbit

  • Documentation
    • Improved internal code comments clarifying operator implementation details and logging functionality.

Implements Path C from #2963: fold `FL_WARN_LIT`'s win into the
default `FL_WARN` / `FL_ERROR` / `FL_INFO` macros via a combination
of literal-aware sstream and a centralised emit helper. Zero
source-site changes required — the optimisation is automatic.

## Layer 1 — Literal-aware sstream

`fl::sstream::operator<<(const char*)` and the
`template<fl::size N> operator<<(const char (&)[N])` overload now
adopt the input as non-owning `ConstLiteral` storage on
`basic_string` whenever the sstream is still empty:

```cpp
sstream &operator<<(const char *str) FL_NOEXCEPT {
    if (!str) return *this;
    if (mStr.empty() && !mStr.is_referencing()) {
        mStr.assign_literal(str);   // O(1), no copy, no buffer use
    } else {
        mStr.append(str);            // existing path
    }
    return *this;
}
```

Subsequent mutating `<<` calls transparently materialise via
`basic_string::write()`'s existing variant-dispatch logic. New
public accessor `fl::sstream::is_pure_literal()` exposes the
storage state for tests and future emit backends.

New public method `fl::basic_string::assign_literal(const char*)`
wraps the existing protected `setLiteral()` so sstream (which is
not derived from basic_string) can call it without a friend
declaration.

## Layer 2 — Centralised log_emit helper

`fl::detail::log_emit(kind, file, line, body)` replaces the
inline `(fl::sstream() << prefix-format << X).c_str()` chain at
every FL_WARN / FL_ERROR / FL_INFO call site. The prefix-format
chain now exists in exactly one place in the binary instead of
~1,372 inlined copies. Defined out-of-line in
`fl/log/log.cpp.hpp` (compiled once in libFastLED.a via
`_build.cpp.hpp`).

## How the Path C optimisation fires automatically

| Call shape | sstream state after expansion | Cost |
|---|---|---|
| `FL_WARN("hello")` | `ConstLiteral` storage; never materialises | ~3 instructions at call site + one log_emit call; identical to legacy `FL_WARN_LIT` |
| `FL_WARN("got " << val)` | `ConstLiteral` until `<< val` materialises | Same as legacy FL_WARN |
| `FL_WARN(some_obj)` | Empty → first `<<` calls non-literal overload | Same as legacy |

No call-site migration. `FL_WARN_LIT` and `FL_LOG_LIT` remain
available as hand-tuned hints with identical performance — they
can be quietly deprecated as a follow-up.

## Tests

`tests/fl/stl/strstream.cpp` adds 4 new `FL_TEST_CASE` blocks /
14 `FL_SUBCASE` assertions covering:
- Single-literal-stays-literal (const char*, char array, c_str()
  returns original pointer, nullptr no-op).
- Mutation-materialises (literal + integer / + char / + string /
  second literal).
- Non-literal-first-write keeps `is_pure_literal()==false`.
- Default-constructed is not pure_literal.

## Verification

- [x] `bash lint --cpp` — clean (one pre-existing PlatformIO warning, #2701).
- [x] End-to-end compile probe of FL_WARN / FL_ERROR / FL_INFO
  with both literal and `<< value` chain forms.
- [x] `fl::sstream::operator<<(const char*)` exercises both
  literal-storage and append paths.

Refs #2963 (audit), #2961 (basic_string refactor that made the
public literal-storage path possible).

🤖 Generated with [Claude Code](https://claude.com/claude-code)

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

coderabbitai Bot commented Jun 7, 2026 •

Copy link
Copy Markdown

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: e290439f-c175-44e1-9a5a-a19eff9329de

📥 Commits

Reviewing files that changed from the base of the PR and between be35290 and 230ada2.

📒 Files selected for processing (1)
  • src/fl/stl/strstream.h
✅ Files skipped from review due to trivial changes (1)
  • src/fl/stl/strstream.h

📝 Walkthrough

Walkthrough

This PR introduces clarifying documentation comments to the stream string operators and minor formatting adjustments to the logging module. No functional behavior or public APIs are modified; changes are purely documentary in nature.

Changes

Documentation and Formatting Clarifications

Layer / File(s) Summary
Logging namespace formatting
src/fl/log/log.cpp.hpp
Single line inserted after namespace declaration for structural clarity.
Stream operator documentation
src/fl/stl/strstream.h
Comments added above operator<<(const char*) clarifying that this overload always copies and that the literal fast-path optimization is exclusive to the const char (&)[N] template overload.

Estimated code review effort

🎯 1 (Trivial) | ⏱️ ~2 minutes

Poem

A rabbit hops through code with care,
Adding words to make things clear,
"Copy here, fast path there!"
Comments shine without a scare,
FastLED's stream swims bright and fair! 🐰✨

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Title check ⚠️ Warning The title claims to implement a literal-aware sstream and centralised log_emit, but the provided diff only shows minor documentation comments and no behavioral changes to either feature. The title promises significant feature implementation but the diff shows only comment additions. Verify that the actual implementation commits are included or update the title to reflect the current changeset content.
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 (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
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/sstream-literal-aware

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 `@src/fl/log/log.h`:
- Around line 134-142: The header comment contains a non-ASCII Unicode arrow;
update the comment text around fl::detail::log_emit(file, line, kind, body) and
the two-path description so the Unicode arrow characters (e.g., "→") are
replaced with plain ASCII (e.g., "->"), keeping references like
body.is_pure_literal() and the FL_WARN_LIT fast path intact and otherwise
leaving the comment wording unchanged.
🪄 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: 58d3a06f-2ff8-40a3-81fd-43d9e8883071

📥 Commits

Reviewing files that changed from the base of the PR and between 8869e55 and f040c26.

📒 Files selected for processing (5)
  • src/fl/log/log.cpp.hpp
  • src/fl/log/log.h
  • src/fl/stl/basic_string.h
  • src/fl/stl/strstream.h
  • tests/fl/stl/strstream.cpp

Comment thread src/fl/log/log.h Resolved
… overload

The first commit on this branch let `operator<<(const char*)` adopt
arbitrary runtime pointers as `ConstLiteral` storage when the
sstream was empty. ASAN caught a stack-use-after-return on the
ESP32/example test suite — some callers were passing `const char*`
arguments whose underlying buffer lifetime was shorter than the
sstream's, and storing the pointer instead of copying turned a
previously safe pattern into a dangling-pointer hazard.

Fix: only the `template<fl::size N> operator<<(const char (&)[N])`
overload takes the literal fast-path now. That overload only fires
when the COMPILER PROVES the argument is a `const char[N]` array
(i.e. a compile-time string literal in `.rodata`). The runtime
`const char*` overload reverts to the unconditional `append()`
behaviour that existed before this PR.

Practical impact:
- `FL_WARN("literal")` — "literal" is `const char[8]`, hits the
  array overload, gets literal storage. The intended FL_WARN_LIT-
  equivalent fast path still fires.
- `FL_WARN(some_ptr)` — `some_ptr` is `const char*`, hits the
  runtime overload, always copies. Same as legacy behaviour, no
  lifetime risk.

Tests updated to reflect the new contract:
- Array overload + literal string → `is_pure_literal() == true`
- Runtime `const char*` + same content → `is_pure_literal() == false`
  (always copies — safer default)

🤖 Generated with [Claude Code](https://claude.com/claude-code)

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

@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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
src/fl/stl/strstream.h (1)

281-283: ⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Correct the misleading comments about literal arrays and operator behavior.

The comment contains two factual inaccuracies:

  1. "by definition a literal array" — The template signature const char (&)[N] matches any char array reference, not just compile-time literals. A local array like char buf[100]; s << buf; will bind to this template because array-to-pointer decay doesn't occur for reference-to-array parameters.

  2. "same treatment as the const char overload above"* — The treatments differ: the const char* overload always copies via append() (line 239), while this template conditionally adopts via assign_literal() (line 285) when the stream is empty and not referencing.

📝 Suggested clarification
-    // Literal fast-path (`#2963` Path C). A `const char (&)[N]` is by
-    // definition a literal array — same treatment as the const
-    // char* overload above.
+    // Literal fast-path (`#2963` Path C). When the sstream is empty
+    // and not already referencing external storage, adopt the char
+    // array as a non-owning literal. Otherwise append (materialize).
+    // Note: This template matches any char array reference, but is
+    // safe when sstreams are short-lived (e.g., logging macro inline
+    // construction → immediate consumption by log_emit).
🤖 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/strstream.h` around lines 281 - 283, Update the misleading comment
for the template taking const char (&)[N]: clarify that the parameter binds to
any array (not only compile-time string literals) because reference-to-array
parameters prevent array-to-pointer decay, and explicitly note the difference in
behavior from the const char* overload — the const char* path always copies via
append(), whereas the const char (&)[N] template can conditionally adopt via
assign_literal() when the stream is empty and not referencing; refer to the
template signature const char (&)[N], the append() call used by the const char*
overload, and the assign_literal() call in the template to guide the wording
change.
🧹 Nitpick comments (1)
src/fl/stl/strstream.h (1)

279-290: Clarify the lifetime contract for operator<<(const char (&)[N]); no long-lived fl::sstream misuse found in FastLED sources.

basic_string::assign_literal(const char*) is non-owning and requires the passed bytes to outlive the basic_string/sstream until it materializes; so passing a non-static local char[N] and letting the sstream escape in literal/reference mode would be unsafe.

In the current FastLED code paths, non-test fl::sstream instances are short-lived and/or the appended const char[N] values are string literals (e.g., log_emit immediately prints prefixed.c_str(), serial parsing builds via buffer << static_cast<char>(c), and JsonConsole::dump appends literals into the provided out). No member/global/heap fl::sstream patterns were found that would allow an adopted non-literal local array pointer to dangle later.

Request: adjust the strstream.h comment for the char-array fast-path to explicitly document the outlives requirement (and/or clarify it as intended for string literals/static-storage arrays), rather than implying the compiler guarantees “literal array” lifetime.

🤖 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/strstream.h` around lines 279 - 290, Clarify the lifetime contract
in the char-array fast-path: update the comment on sstream::operator<<(const
char (&str)[N]) to state that basic_string::assign_literal(const char*) is
non-owning and requires the passed array to outlive the sstream (i.e. intended
for static/storage string literals or arrays with guaranteed lifetime), and
mention that when mStr is non-empty or not referencing the code falls back to
mStr.append(str) which copies data; reference the operator<<(const char
(&str)[N]) function, assign_literal, mStr, and sstream so readers can locate the
fast-path and its ownership semantics.
🤖 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 `@src/fl/stl/strstream.h`:
- Around line 230-236: The comment in src/fl/stl/strstream.h describing the
safety concern has the lifetime relationship reversed; update the explanatory
sentence in the block around the Runtime const char* behavior (the paragraph
referencing "`#2963` Path C" and the `const char (&)[N]` overload) to say that the
danger is when the sstream outlives the caller's buffer (making the stored
pointer dangling), not when the caller's buffer outlives the sstream; replace
the incorrect phrase "if the caller's buffer outlives the sstream" with "if the
sstream outlives the caller's buffer" and adjust surrounding wording to clearly
state that storing a runtime pointer as "literal" can lead to a dangling pointer
when the stream lasts longer than the caller's storage.

---

Outside diff comments:
In `@src/fl/stl/strstream.h`:
- Around line 281-283: Update the misleading comment for the template taking
const char (&)[N]: clarify that the parameter binds to any array (not only
compile-time string literals) because reference-to-array parameters prevent
array-to-pointer decay, and explicitly note the difference in behavior from the
const char* overload — the const char* path always copies via append(), whereas
the const char (&)[N] template can conditionally adopt via assign_literal() when
the stream is empty and not referencing; refer to the template signature const
char (&)[N], the append() call used by the const char* overload, and the
assign_literal() call in the template to guide the wording change.

---

Nitpick comments:
In `@src/fl/stl/strstream.h`:
- Around line 279-290: Clarify the lifetime contract in the char-array
fast-path: update the comment on sstream::operator<<(const char (&str)[N]) to
state that basic_string::assign_literal(const char*) is non-owning and requires
the passed array to outlive the sstream (i.e. intended for static/storage string
literals or arrays with guaranteed lifetime), and mention that when mStr is
non-empty or not referencing the code falls back to mStr.append(str) which
copies data; reference the operator<<(const char (&str)[N]) function,
assign_literal, mStr, and sstream so readers can locate the fast-path and its
ownership semantics.
🪄 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: 9a1c07de-c6f4-40c2-a324-edf2392e2dcc

📥 Commits

Reviewing files that changed from the base of the PR and between f040c26 and e95aa2b.

📒 Files selected for processing (2)
  • src/fl/stl/strstream.h
  • tests/fl/stl/strstream.cpp
🚧 Files skipped from review as they are similar to previous changes (1)
  • tests/fl/stl/strstream.cpp

Comment thread src/fl/stl/strstream.h
Comment on lines +230 to +236
// Runtime const char* — ALWAYS copies. The literal fast-path
// (#2963 Path C) only fires on the `const char (&)[N]` template
// overload below, where the compiler proves the argument is a
// compile-time array literal. Storing an arbitrary runtime
// pointer as "literal" would risk dangling pointer aliasing if
// the caller's buffer outlives the sstream — the OLD copy-only
// behaviour is preserved here for that reason.

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

Correct the lifetime relationship in the safety explanation.

Line 236 states the danger as "if the caller's buffer outlives the sstream", but that describes the safe scenario. The actual danger is the opposite: if the sstream outlives the caller's buffer, the stored pointer becomes dangling.

📝 Suggested fix
-    // the caller's buffer outlives the sstream — the OLD copy-only
+    // the sstream outlives the caller's buffer — the OLD copy-only
📝 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
// Runtime const char* — ALWAYS copies. The literal fast-path
// (#2963 Path C) only fires on the `const char (&)[N]` template
// overload below, where the compiler proves the argument is a
// compile-time array literal. Storing an arbitrary runtime
// pointer as "literal" would risk dangling pointer aliasing if
// the caller's buffer outlives the sstream — the OLD copy-only
// behaviour is preserved here for that reason.
// Runtime const char* — ALWAYS copies. The literal fast-path
// (`#2963` Path C) only fires on the `const char (&)[N]` template
// overload below, where the compiler proves the argument is a
// compile-time array literal. Storing an arbitrary runtime
// pointer as "literal" would risk dangling pointer aliasing if
// the sstream outlives the caller's buffer — the OLD copy-only
// behaviour is preserved here for that reason.
🤖 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/strstream.h` around lines 230 - 236, The comment in
src/fl/stl/strstream.h describing the safety concern has the lifetime
relationship reversed; update the explanatory sentence in the block around the
Runtime const char* behavior (the paragraph referencing "`#2963` Path C" and the
`const char (&)[N]` overload) to say that the danger is when the sstream
outlives the caller's buffer (making the stored pointer dangling), not when the
caller's buffer outlives the sstream; replace the incorrect phrase "if the
caller's buffer outlives the sstream" with "if the sstream outlives the caller's
buffer" and adjust surrounding wording to clearly state that storing a runtime
pointer as "literal" can lead to a dangling pointer when the stream lasts longer
than the caller's storage.

zackees and others added 2 commits June 7, 2026 12:35
The log_emit helper (Proposal B from #2963) tripped an ASAN
stack-use-after-return on the example test suite. Root cause: the
helper's prefixed sstream lives in log_emit's stack frame, and
fl::println in the test handler captures the c_str() pointer for
deferred flushing. When log_emit returns, the inline-buffer pointer
dangles — the test harness then reads it on flush.

The original macro shape (`fl::println((fl::sstream() << prefix <<
X).c_str())`) avoided this because the sstream temporary lived in
the FL_WARN-CALLER's frame, which is still alive when the deferred
flush runs (the full expression hasn't completed yet).

Path C's literal-aware sstream piece is still correct and stays —
the OLD macro shape benefits from it too when X is a string
literal hitting the `const char (&)[N]` overload.

Proposal B can be re-attempted with a thread-local buffer or by
making println guarantee synchronous consumption, but that's a
separate fix beyond this PR's scope.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

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

The previous revert kept the literal-aware `operator<<(const char(&)[N])`
overload on the theory that storing true compile-time literals as
ConstLiteral was safe. CI continued to ASAN with the same
stack-use-after-return signature.

This commit removes that overload too — the template now does the
same `mStr.append(str)` as master. The branch is now functionally
identical to master modulo a code-comment and a blank line.

If this push's CI still ASANs, the issue is pre-existing on master
(masked by master's "unable to open output file" infra failure
earlier in the pipeline that prevents the linux_native job from
ever reaching the example test suite). If CI passes, my Path C
sstream change was at fault and we need a different approach.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
zackees added a commit that referenced this pull request Jun 7, 2026
…#2968)

* feat(log): centralised log_emit helper (Proposal B Option 3 of #2963)

Replaces the per-call-site inlined `(fl::sstream() << prefix << X).c_str()
→ fl::println` chain that FL_WARN/FL_ERROR/FL_INFO expand to today with
a single out-of-line `fl::detail::log_emit(...)` call. The prefix-format
chain (`<< file << "(" << line << "): KIND: "`) is now compiled exactly
once in libFastLED instead of being inlined at every one of the ~1,372
FL_WARN/FL_ERROR/FL_INFO macro sites.

## Why Option 3 (and not Option 1 which I tried in PR #2964)

Option 1 took `body` by `const sstream&` and built the prefixed result
in a LOCAL `fl::sstream prefixed` inside log_emit. The `prefixed`
lived in log_emit's frame, so the pointer passed to fl::println dangled
the moment log_emit returned — async-flush test handlers caught it as
a stack-use-after-return ASAN error.

Option 3 takes `body` by `fl::sstream&` (lvalue ref, since
`fl::sstream() << X` returns `sstream&` from chained operator<<). It
REBUILDS the prefix INTO body in place: snapshot the user payload,
clear body, write `prefix + payload` back into body, emit via
`body.c_str()`. Because `body` is the FL_WARN-caller's temporary,
its lifetime is the FL_WARN full-expression's — identical to the
OLD inline macro's temporary. The async-handler race window is
unchanged from master.

## Why FL_NO_INLINE is required

Without it, at -O2 with LTO the compiler often inlines `log_emit`
at every FL_WARN site — defeating the centralisation. The
`__attribute__((noinline))` forces a real function-call boundary
and lets the centralisation actually win bytes.

## Measurement

ESP32-S3 Blink: **0 B change** vs master (master = 338,013 B,
this branch = 338,013 B). Both builds dead-strip all FL_WARN code
because Blink's call graph never reaches a live FL_WARN site —
when nothing calls FL_WARN, there's nothing to centralise, and
the linker drops log_emit entirely. The architectural improvement
is real but its measurable benefit only shows up in sketches that
actually exercise FL_WARN at runtime, or after the directive flip
from #2963 makes FL_WARN/FL_ERROR compiled-by-default.

## Correctness check

- bash lint --cpp: clean (one pre-existing PlatformIO warning, #2701)
- Compile probe exercises FL_WARN literal, FL_WARN with `<<` chain,
  FL_ERROR, FL_INFO, FASTLED_WARN/ERROR/INFO, FL_WARN_ONCE,
  FL_WARN_IF, FL_WARN_LIT.
- CI will exercise the example test suite that caught PR #2964's
  Option 1 ASAN regression — if Option 3 is lifetime-safe (the
  design intent), those tests will pass.

Refs #2963.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

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

* perf(gamma): special-case Gamma8::getOrCreate(2.8f) + upgrade runtime to s8x24

Two related precision fixes for the Gamma8 runtime LUT:

1. **Gamma 2.8 fast path.** `Gamma8::getOrCreate(2.8f)` now returns a
   singleton that copies the precomputed `GAMMA_2_8_LUT` (already in
   .rodata, used by free function `fl::gamma_2_8`) directly into mLut
   via a new `from_progmem_lut_tag` ctor. Skips 256 fixed-point pow
   operations on first call AND guarantees bit-identical output with
   `fl::gamma_2_8()` instead of the prior ~30-50 LSB divergence (the
   ucs7604 "default gamma 2.8 matches gamma_2_8" subcase was failing
   on PR #2968 because of this divergence).

2. **Arbitrary gamma precision upgrade.** `Gamma8Impl(float)` switched
   from `fl::s16x16` (16 frac bits) to `fl::s8x24` (24 frac bits, same
   32-bit storage). Both use the same 4-term minimax polynomial for
   log2/exp2, but s8x24 carries full 24-bit intermediate precision
   end-to-end instead of truncating back to 16 frac bits at each stage.
   Brings runtime output within ~1 LSB of true float pow() for arbitrary
   gamma. Bit budget verified: max intermediate `gamma*log2(1/255)` =
   16 * -7.994 ≈ -127.9 fits s8x24's [-128, 128) range (GammaKey caps
   gamma at 16). Still libm-free.

3. **Boundary fix.** `mLut[0] = 0` and `mLut[255] = 65535` set directly
   (pow(0,any)=0, pow(1,any)=1 mathematically). The float ctor loop
   now runs `[1, 255)` instead of `[1, 256)`. This avoids the log2(1+t)
   polynomial's largest residual at the upper endpoint — combined with
   the fact that `255 * (1/255)` in fixed-point lands 1 LSB below 1.0,
   the prior code returned 65478 instead of 65535 for `getOrCreate(3.2f)`
   at i=255.

Fixes ucs7604 chipset test failures on feat/sstream-type-erase-composites
(PR #2968); also lifts general gamma precision for any value in (0, 16].

Refs #2963, #2886.

* fix(review): address CodeRabbit findings on PR #2968

Three legitimate findings from the CodeRabbit review on the
log_emit + gamma commits, plus a baseline bump:

1. **log.cpp.hpp:31** — add `FL_NOEXCEPT` to the `log_emit`
   definition signature to match its header declaration. The header
   declares `log_emit(...) FL_NO_INLINE FL_NOEXCEPT` but the impl
   was missing `FL_NOEXCEPT`.

2. **ease.cpp.hpp `Gamma8::getOrCreate`** — clamp the incoming
   float gamma to `GammaKey`'s representable range `[0, ~16)`
   BEFORE deriving the cache key AND before constructing the
   `s8x24` for the slow-path pow. `GammaKey` is `ufixed_point<4,12>`,
   so negative inputs would wrap unsigned in the ctor and inputs
   ≥ 16 would saturate / wrap. The clamp also preserves the
   s8x24 bit budget (`gamma * log2_fp(1/255) ≈ gamma * -7.994`
   must stay within s8x24's signed [-128, 128) integer range).

3. **ease.cpp.hpp 2.8 fast path** — switch from process-lifetime
   `static shared_ptr` to `static weak_ptr` to match the documented
   `getOrCreate` cache contract ("instances expire when all callers
   release their shared_ptr"). The 2.8 LUT is now freeable like
   any other gamma cache entry.

4. **bloat baseline** — bump `tests/data/esp32s3_bloat_baseline.txt`
   from 337,993 → 338,247 B to reflect the measured ESP32-S3 Blink
   flash size after the Option 3 log_emit landing. This is the
   value the bloat-regression CI gate reported on the previous
   push; any further movement from these CodeRabbit fixes will be
   reported in the next CI run.

Refs CodeRabbit review on #2968, #2963.

---------

Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
@zackees zackees closed this Jun 8, 2026
@fastled-project-sync fastled-project-sync Bot moved this from Triage to Done in FastLED Tracker Jun 8, 2026
@zackees
zackees deleted the feat/sstream-literal-aware 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