Skip to content

refactor(fl::string): drop StrN<N> template, make basic_string the public class - #2961

Merged
zackees merged 7 commits into
masterfrom
feat/string-base-span-api
Jun 7, 2026
Merged

zackees merged 7 commits into
masterfrom
feat/string-base-span-api

Conversation

@zackees

@zackees zackees commented Jun 7, 2026 •

Copy link
Copy Markdown
Member

Motivated by the #2886 comment thread: collapse fl::sstream / fl::string template specializations onto a single concrete base.

Two commits on the branch:

  1. 1866f55 (initial PR) added vocabulary aliases (string_base, stringN) + doc — addressed naming but not structure.
  2. 5033e43 (this commit) drops the fl::StrN<N> template entirely and makes fl::basic_string the public, directly-constructible concrete class.

What changed

Type Before After
fl::basic_string type-erased base, protected ctor (only callable by StrN<N>) type-erased class, public ctor — (char*, fl::size) OR fl::span<char>
fl::StrN<N> template wrapper holding a char[N] inline buffer removed
fl::string : public StrN<FASTLED_STR_INLINED_SIZE> plus composite-formatter overloads : public basic_string with co-located char mInlineBuffer[64] plus the same composite-formatter overloads
string_view(StrN<N>&) templated ctor on string_view string_view(const basic_string&) (single ctor, defined where basic_string is complete)
substring() / substr() / trim() on StrN<N>, returns StrN on fl::string, returns string

Direct basic_string usage (new)

char buf[256];
fl::basic_string s(fl::span<char>(buf, 256));  // span overload
fl::basic_string s2(buf, 256);                  // ptr+size overload
s.append("hello, ").append(42);

Lifetime contract: the buffer must outlive the basic_string, and the basic_string must not be trivially relocated (the internal mInlineOffset is computed from this at construction). For member-stored use, prefer fl::string (which co-locates the buffer inside itself).

Callers migrated

  • src/platforms/esp/32/ota/ota_impl.cpp.hpp — 5 StrN<32> / StrN<64> fields → fl::string. Net +32 bytes on the OTAManager struct (mApSsid grew from 32→64 inline; the other 4 were already 64).
  • tests/fl/stl/string.cpp — ~50 fl::StrN<N> test sites → fl::string. Cross-size StrN tests are now same-size assignment + heap-promotion tests (covering the same behaviors).
  • tests/fl/stl/strstream_integers.cpp — 1 fl::StrN<64> → fl::string.
  • vector.h, basic_vector.h, strstream.h, type_traits.h, cstdio.cpp.hpp — stale StrN<N> doc comments updated.

Why this is non-controversial

StrN<N> was a template that only ever got instantiated at N=32 and N=64 in the entire codebase. The N=32 saving (vs fl::string's 64-byte default) is a 32-byte win on a single OTA field — irrelevant. The template added type-system distinctness (StrN<32> ≠ StrN<64>) that nothing in the codebase relied on. Dropping it removes ~110 lines of redundant constructor / assignment plumbing.

Architecture doc

agents/docs/string-architecture.md rewritten to describe the new two-layer design (basic_string + string), the public span-based construction surface, and where the actual remaining binary duplication lives (basic_string::write at 1,151 B is variant-dispatch + materialize-on-write — already type-erased, separate Stage 5 simplification target per #2886).

Verification

  • bash lint --cpp — clean (one pre-existing PlatformIO warning, #2701)
  • Direct compile probe exercises: basic_string(char*, fl::size), basic_string(fl::span<char>), fl::string defaults + copy + assign, substring() / substr() / trim() on fl::string, string_view(const basic_string&).
  • bash test --cpp — pre-existing build-infra failure ("unable to open output file") reproduces on master without these changes. Compile probe is the meaningful check given the symptom is build-system, not code.

Net diff

13 files changed, 248 insertions(+), 266 deletions(-) — net delete; the StrN template was redundant.

🤖 Generated with Claude Code

Summary by CodeRabbit

  • New Features

    • Unified inline-buffer string with richer constructors, view/interop, substring/trim, concatenation, comparison, and interning APIs (includes std::string interop for WASM).
  • Documentation

    • Added comprehensive string architecture docs covering storage modes, buffer lifetime, formatting flow, and recommended header/usage order.
  • Tests

    • Updated tests to target the unified string implementation across iterators, comparisons, integer-formatting, and heap-promotion scenarios.
  • Breaking Changes

    • Removed the old fixed-size template string wrapper; APIs now use the unified string type.

Adds `fl::string_base` (alias for `fl::basic_string`) and
`fl::stringN<N>` (alias for `fl::StrN<N>`) so newer code can use the
trampoline-pattern vocabulary referenced in design discussions
without churning the ~hundreds of existing `basic_string` / `StrN<N>`
references. Both are `using` aliases — zero ABI change, zero
behavior change.

Also adds `agents/docs/string-architecture.md` documenting:

- The current three-layer architecture (`basic_string` concrete base
  / `StrN<N>` inline-buffer template / `string` default + composite
  overloads) and how it already implements the trampoline pattern
  the bloat-reduction discussion calls for.
- Where the *actual* binary duplication is — per #2886 row #24, the
  1,151 B `basic_string::write` lives in the variant-dispatch
  materialize-on-write logic, not in template instantiation. That's
  algorithmic complexity, not duplicated code.
- The follow-up path when composite formatters (`append<vec2<T>>`,
  `operator<<<container>`) start showing up as bloat: push their
  bodies down into non-template `basic_string` helpers with a
  function-pointer element formatter, rather than reshaping the
  storage classes.

Motivation: #2886 comment thread requesting that
`fl::sstream`/`fl::string` template specializations collapse to a
single concrete base. The architecture is already in place; the
aliases + doc make that visible.

Verified:
- `bash lint` clean (one pre-existing PlatformIO warning, #2701)
- Direct compile probe: `static_assert(sizeof(string_base) ==
  sizeof(basic_string))`, `stringN<32>` / `stringN<>` / `string`
  resolve correctly

🤖 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

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

Replaces the templated StrN wrapper with a concrete fl::string derived from fl::basic_string, adds a span-based constructor and string_view interop, moves many implementations out-of-line, updates comments and ESP32 OTA usage, adds an architecture doc, and converts tests to fl::string.

Changes

String core refactor and documentation

Layer / File(s) Summary
Architecture doc
agents/docs/string-architecture.md
New document describing the three-layer model (basic_string, fl::string wrapper with inline buffer, fl::sstream), trampoline dispatch into non-template basic_string methods, storage modes, and reading order.
basic_string header + impl
src/fl/stl/basic_string.h, src/fl/stl/basic_string.cpp.hpp
Add fl::span forward-declaration, rewrite file-level docs to describe concrete basic_string + wrapper pattern, declare span-taking constructor and out-of-line destructor (FL_NOEXCEPT), add includes and implement span ctor, destructor, and string_view(const basic_string&).
fl::string header changes
src/fl/stl/string.h
Remove StrN template; make fl::string derive from basic_string with an owned mInlineBuffer, convert many inline methods to declarations, add array-literal operator=, and move comparison bodies out-of-line.
fl::string implementation & APIs
src/fl/stl/string.cpp.hpp
Implement factories (from_literal, from_view, interned, copy_no_view), broaden constructors/assignments (C-string, fill, view/span, shared holder), substring/trim, strcmp wrapper (FL_NOEXCEPT), relational/equality operators, operator+=, WASM/std::string interop, and adjust Arduino constructor initialization.
string_view header change
src/fl/stl/string_view.h
Forward-declare basic_string and replace the templated StrN constructor with string_view(const basic_string&) declared out-of-line.
Minor header/comment updates
src/fl/stl/basic_vector.h, src/fl/stl/cstdio.cpp.hpp, src/fl/stl/strstream.h, src/fl/stl/type_traits.h, src/fl/stl/vector.h
Reworded comments and docstrings to reference the basic_string + fl::string wrapper pattern and updated a remark about trim() returning an fl::string.
Platform usage changes
src/platforms/esp/32/ota/ota_impl.cpp.hpp
Replace several fl::StrN fields in ESP32OTA with fl::string and update related comments.
Tests switched to fl::string
tests/fl/stl/string.cpp, tests/fl/stl/strstream_integers.cpp
Convert test cases and assertions from StrN to fl::string, including comparison, iterator, integer-write, and heap-promotion tests and accompanying comments.

Estimated Code Review Effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Poem

🐰 I hopped through headers, buffers, and span,

fl::string now stands where templates once ran.
The docs hum the trampoline's gentle art,
Inline buffers held close, yet ready to part.
A little rabbit cheers this tidy plan.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 26.32% 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 PR title accurately and specifically describes the main refactoring: removing StrN template and promoting basic_string as the public class, which aligns with the extensive changes across the codebase.
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 unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/string-base-span-api

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 `@agents/docs/string-architecture.md`:
- Around line 14-30: Update the fenced code blocks in
agents/docs/string-architecture.md to include an explicit language identifier
(use "text") so markdownlint rule MD040 is satisfied; specifically add ```text
at the start of the ASCII diagrams used around the sstream::operator<<(vec2<T>)
and basic_string::write(...) examples (the two fenced blocks shown in the diff
and the similar block at lines 38-40), and ensure each closing fence remains ```
so the blocks are properly delimited.
🪄 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: b98e5ea4-e220-4578-b6e9-86aad699230c

📥 Commits

Reviewing files that changed from the base of the PR and between 280ffb1 and 1866f55.

📒 Files selected for processing (3)
  • agents/docs/string-architecture.md
  • src/fl/stl/basic_string.h
  • src/fl/stl/string.h

Comment thread agents/docs/string-architecture.md Resolved
…blic class

Implements the structural refactor requested in the #2886 thread:
the historical `fl::StrN<N>` template wrapper goes away. `fl::basic_string`
becomes the directly-constructible concrete class (takes either
`(char*, fl::size)` or `fl::span<char>` for caller-managed storage),
and `fl::string` inherits it directly with a co-located 64-byte
inline buffer. No alias indirection.

## What changes

**Public API:**
- `fl::basic_string(char*, fl::size)` — now public; same semantics
  as before (offset-from-`this` storage).
- `fl::basic_string(fl::span<char>)` — new; delegates to the
  `(char*, size)` ctor. Caller owns the buffer; lifetime contract
  documented in the class header.
- `fl::StrN<N>` template — removed.
- `fl::string` — now directly inherits `basic_string` instead of
  `StrN<FASTLED_STR_INLINED_SIZE>`. Carries its own 64-byte inline
  buffer + heap overflow, same as before.
- `substring()` / `substr()` / `trim()` moved from `StrN<N>` onto
  `fl::string` (return type changed from `StrN` to `string`).
- `fl::string_view(const basic_string&)` ctor replaces the former
  templated `string_view(const StrN<SIZE>&)`.

**Callers migrated:**
- `src/platforms/esp/32/ota/ota_impl.cpp.hpp` — `StrN<32>` /
  `StrN<64>` fields → `fl::string`. The 32-byte savings on
  `mApSsid` is negligible; the OTA struct grows by 32 bytes total
  (~0.01% of an ESP32-S3 RAM budget).
- `tests/fl/stl/string.cpp` (~50 StrN<N> sites) and
  `tests/fl/stl/strstream_integers.cpp` (1 site) → `fl::string`.
  Cross-size StrN tests become same-size assignment/heap-promotion
  tests covering the same behaviors.
- `vector.h`, `basic_vector.h`, `strstream.h`, `type_traits.h`,
  `cstdio.cpp.hpp` — stale `StrN<N>` documentation comments
  updated to reference the new structure.

## Why

[#2886 comment thread](#2886 (comment)) called for `fl::sstream` / `fl::string` template specializations to collapse to a single concrete base. The earlier alias-only PR (commit 1866f55) added vocabulary (`string_base` / `stringN`) but didn't move structure — this commit drops the template wrapper entirely so there's only one storage class and the public name on the carrier IS `basic_string`. No aliases.

Template instantiation cost of `StrN<N>` was already minimal (only N=32 and N=64 in use), so this commit doesn't materially change binary size today; it's a clarity + future-proofing change. The actual remaining bloat target — `basic_string::write` at 1,151 B (issue #2886 row #24) — is variant-dispatch + materialize-on-write logic, already type-erased; that's a separate Stage 5 simplification.

## Architecture doc

`agents/docs/string-architecture.md` rewritten to reflect the two-
layer design (basic_string + string), document the span-based
public construction, and capture where the actual binary
duplication lives (and doesn't).

## Verification

- [x] `bash lint --cpp` — clean (one pre-existing PlatformIO warning, #2701)
- [x] Direct compile probe of the new API surface (span ctor, `(char*, size)` ctor, fl::string still works, substring/trim moved, string_view(basic_string&) ctor)
- [ ] `bash test --cpp` — pre-existing build-infra failure (reproduces on master without these changes); unable to verify end-to-end in this session

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

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@zackees zackees changed the title docs(fl::string): add string_base + stringN aliases and trampoline-pattern architecture doc refactor(fl::string): drop StrN&lt;N&gt; template, make basic_string the public class Jun 7, 2026

@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: 2

🧹 Nitpick comments (1)
src/fl/stl/basic_string.h (1)

437-437: 💤 Low value

Consider using = default instead of empty body for the destructor.

The guideline for src/**/*.h states function definitions should go in .cpp.hpp files. While an empty destructor body is trivial, using = default would be more consistent with the pattern and avoids any ambiguity about whether this is a definition:

~basic_string() FL_NOEXCEPT = default;

Alternatively, if the empty body is intentional (e.g., to ensure the destructor isn't trivial for some reason), this can be left as-is.

🤖 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/basic_string.h` at line 437, Replace the empty-body destructor
with a defaulted declaration to follow header-only definitions guideline: change
the destructor for basic_string (~basic_string() FL_NOEXCEPT) to be defaulted
(i.e., use = default) so it remains a declaration rather than an out-of-line
definition and aligns with the src/**/*.h pattern.

Source: Coding guidelines

🤖 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/string.h`:
- Around line 227-230: substr adds start + length before bounds checks which can
overflow when length == npos or is very large; update substr(fl::size start,
fl::size length) to handle fl::string::npos and overflow by first checking if
length == npos (set end = size()), otherwise ensure length does not exceed
remaining size (if length > size() - start then end = size(), else end = start +
length), and keep using substring(start, end); reference symbols: substr,
substring, size, and npos.

In `@tests/fl/stl/string.cpp`:
- Around line 4872-4876: The test subcase for heap-promotion doesn't actually
guarantee exceeding the inline buffer; update the FL_SUBCASE("Copy long string
that overflows the inline buffer") to construct an fl::string whose length is >
FASTLED_STR_INLINED_SIZE (e.g., FASTLED_STR_INLINED_SIZE + 1) instead of using
the current short literal so that fl::string big(...) forces heap promotion;
ensure the copied tiny variable and the final FL_CHECK compare against that same
long content.

---

Nitpick comments:
In `@src/fl/stl/basic_string.h`:
- Line 437: Replace the empty-body destructor with a defaulted declaration to
follow header-only definitions guideline: change the destructor for basic_string
(~basic_string() FL_NOEXCEPT) to be defaulted (i.e., use = default) so it
remains a declaration rather than an out-of-line definition and aligns with the
src/**/*.h pattern.
🪄 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: ed11218e-8fb1-4e62-8196-10a51734a264

📥 Commits

Reviewing files that changed from the base of the PR and between 1866f55 and 5033e43.

📒 Files selected for processing (13)
  • agents/docs/string-architecture.md
  • src/fl/stl/basic_string.cpp.hpp
  • src/fl/stl/basic_string.h
  • src/fl/stl/basic_vector.h
  • src/fl/stl/cstdio.cpp.hpp
  • src/fl/stl/string.h
  • src/fl/stl/string_view.h
  • src/fl/stl/strstream.h
  • src/fl/stl/type_traits.h
  • src/fl/stl/vector.h
  • src/platforms/esp/32/ota/ota_impl.cpp.hpp
  • tests/fl/stl/string.cpp
  • tests/fl/stl/strstream_integers.cpp
✅ Files skipped from review due to trivial changes (6)
  • src/fl/stl/strstream.h
  • src/fl/stl/basic_vector.h
  • src/fl/stl/type_traits.h
  • src/fl/stl/vector.h
  • src/fl/stl/cstdio.cpp.hpp
  • agents/docs/string-architecture.md

Comment thread src/fl/stl/string.h Resolved
Comment thread tests/fl/stl/string.cpp Resolved
zackees and others added 2 commits June 7, 2026 09:15
Header churn cleanup. Every `fl::string` member whose body doesn't
depend on a caller-side template parameter moves from inline
definitions in `string.h` to out-of-line definitions in
`string.cpp.hpp`:

- Constructors: `string()`, `string(const char*)`, `(ptr, len)`,
  `(size, char)`, `(const string&)`, `(string&&)`,
  `(const basic_string&)`, `(const string_view&)`,
  `(const span<char>&)`, `(const span<const char>&)`,
  `(const shared_ptr<StringHolder>&)`
- Assignment: `operator=(const string&)`, `operator=(string&&)`,
  `operator=(const char*)`, `assign(string_view)`
- Substring family: `substring()`, `substr()` (×2), `trim()`
- Comparison: `operator>`, `>=`, `<`, `<=`, `==`, `!=`
- Concatenation: `operator+=(const string&)` (non-template)
- Static factories: `from_literal()`, `from_view()` (×2),
  `interned()` (×3), `copy_no_view()`
- WASM-only `std::string` interop ctors / `operator=` / `append`

What stays inline in `string.h`:
- Template constructors: `string(InputIt, InputIt)` and
  `string(const char (&)[N])`
- Template assignment `operator=(const char (&)[N])`
- Composite-formatter `append<T>()` overloads (vec2, span, vector,
  optional, …)
- `operator+=(const T&)` template

`_build.cpp.hpp` already pulls in `string.cpp.hpp`, so the moved
bodies land in `libFastLED.a` exactly once — same final binary
layout, less header noise for every TU that just declares strings.

string.h: 566 → 438 lines (-128). string.cpp.hpp: 167 → 377 (+210).

## Verification

- [x] `bash lint --cpp` — clean (one pre-existing PlatformIO warning, #2701)
- [x] Compile probe covering: default + copy + move + ptr/len /
  span / string_view ctors, `operator=`, comparison operators,
  `operator+=`, `substring()`/`trim()`, `from_literal()`,
  `interned()`, plus template ctors (`InputIt` + `const char(&)[N]`)
  and direct `basic_string(char*, size)` + `basic_string(span)` use.

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

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Four fixes on top of the prior commits:

1. **uno build failure** — `string::string(const ::String&)` (Arduino
   conversion ctor) had no explicit base-class initialiser. Pre-
   refactor it inherited `StrN<N>`'s implicit default; post-refactor
   `basic_string` has no default ctor (it requires the buffer), so
   the Arduino ctor failed to compile on the AVR toolchain that
   exercises this code path. Added the explicit base init.

2. **`substr(start, length)` overflow** (CodeRabbit #2961) — the
   previous body computed `start + length` before bounds-checking,
   which overflows when `length == npos` (the standard "to end of
   string" idiom) or any large value. Now: if `length == npos` or
   `start + length` would wrap past `size()`, we clamp `end` to
   `size()` directly without the overflowing addition.

3. **Heap-promotion test claim is now true** (CodeRabbit #2961) —
   the "Copy long string that overflows the inline buffer" subcase
   used a 48-char literal which fits in `FASTLED_STR_INLINED_SIZE`
   (default 64), so heap promotion never fired and the test passed
   for the wrong reason. Replaced with a >64-byte literal + an
   explicit `FL_CHECK(big.size() > FASTLED_STR_INLINED_SIZE)` so
   the test actually exercises the promotion path.

4. **Destructor moved to `.cpp.hpp`** (CodeRabbit #2961) — per the
   project's header-thin convention, `~basic_string()` is now
   declared in `basic_string.h` and defined (empty body) in
   `basic_string.cpp.hpp`. Not `= default` — the convention here
   is "definitions live in cpp.hpp", not "defaulted in header".

5. Markdown code-fence language identifiers — added `text` to the
   ASCII trampoline diagram in `agents/docs/string-architecture.md`
   so markdownlint MD040 is satisfied.

🤖 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: 3

♻️ Duplicate comments (1)
src/fl/stl/string.cpp.hpp (1)

173-176: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

substr(start, length) still overflows on npos / large lengths.

Line 174 adds two unsigned values before clamping. When length == npos or just exceeds the remaining suffix, start + length can wrap and substring() returns the wrong slice instead of the suffix.

Proposed fix
 string string::substr(fl::size start, fl::size length) const FL_NOEXCEPT {
-    fl::size end = start + length;
-    if (end > size()) end = size();
-    return substring(start, end);
+    if (start >= size()) return string();
+    if (length == npos || length > (size() - start)) {
+        length = size() - start;
+    }
+    return substring(start, start + length);
 }
🤖 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/string.cpp.hpp` around lines 173 - 176, The current
string::substr(start, length) computes end = start + length which can overflow
when length == npos or length > size() - start; change the logic in
string::substr to avoid unsigned wraparound by first checking if length == npos
or length > (size() - start) and in those cases set end = size(), otherwise set
end = start + length, then call substring(start, end); reference symbols:
string::substr, substring, size(), npos, start, length.
🤖 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/string.cpp.hpp`:
- Around line 74-75: The strcmp implementation and related compare paths
currently call fl::strcmp on c_str() (e.g., string::strcmp and the compare
overloads around lines 210-223), which is unsafe for view-backed,
non-null-terminated strings; change these to use the length-aware comparison
provided by basic_string::compare (or an equivalent memcmp-based compare using
size()) so comparisons respect size() and handle embedded NULs correctly—replace
calls to fl::strcmp(a.c_str(), b.c_str()) with a.length-aware call like
a.basic_string::compare(b) (or a size-limited memcmp) in string::strcmp and the
other compare overloads referenced.
- Around line 147-149: The operator string::operator=(const char*) currently
calls fl::strlen(str) unconditionally and will dereference a null pointer;
update this method to guard against nullptr by treating a null input as an empty
string (e.g., if str == nullptr use length 0 or pass an empty literal) before
calling copy, so behavior matches the class constructor's null-as-empty contract
and still returns *this and preserves FL_NOEXCEPT.
- Around line 48-63: The interned(const char*, fl::size) family currently
creates a new shared StringHolder directly and never uses global_interner(), so
either route these functions through the global interner or rename them to
clarify they only create shared storage; to fix, change string::interned(const
char*, fl::size) to call global_interner().intern(...) (and have the other
overloads forward to that) so deduplication occurs via global_interner(), or if
you intend no deduplication, rename string::interned to something like
make_shared_string and document that it only calls setSharedHolder with a new
StringHolder; update callers of string::interned and keep string::intern()
behavior unchanged.

---

Duplicate comments:
In `@src/fl/stl/string.cpp.hpp`:
- Around line 173-176: The current string::substr(start, length) computes end =
start + length which can overflow when length == npos or length > size() -
start; change the logic in string::substr to avoid unsigned wraparound by first
checking if length == npos or length > (size() - start) and in those cases set
end = size(), otherwise set end = start + length, then call substring(start,
end); reference symbols: string::substr, substring, size(), npos, start, length.
🪄 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: 9435a2f5-9d4a-40fd-aeb4-068e788a7896

📥 Commits

Reviewing files that changed from the base of the PR and between 5033e43 and 0b48121.

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

Comment thread src/fl/stl/string.cpp.hpp Resolved
Comment thread src/fl/stl/string.cpp.hpp Resolved
Comment thread src/fl/stl/string.cpp.hpp Resolved
Two remaining CodeRabbit findings from #2961:

1. **`operator=(const char* str)` now matches the `string(const
   char*)` ctor contract**: nullptr → empty string. Previously
   `fl::strlen(nullptr)` was undefined behavior; the corresponding
   constructor at the same time was already null-safe, so the
   assignment path is brought in line.

2. **Comparison operators are length-aware**: `operator<`, `<=`,
   `>`, `>=` now go through a new private `string_compare(...)`
   helper that uses `memcmp` over `min(a.size, b.size)` and breaks
   ties by length. This is correct for view-backed strings
   (`setView`) where the underlying buffer may not be NUL-
   terminated at `size()` even though `c_str()` materialises one
   on demand, and it sidesteps `strcmp`'s short-circuit on any
   future embedded-NUL content. Sign convention matches
   `memcmp`/`strcmp`.

(The `interned()` deduplication concern CR also raised is
pre-existing behavior — every prior version of `string::interned()`
created a fresh `StringHolder` rather than routing through the
global interner. Out of scope for this refactor; tracking as a
follow-up.)

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

Caution

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

⚠️ Outside diff range comments (2)
src/fl/stl/basic_string.h (2)

38-43: ⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Replace non-ASCII punctuation in header comments.

This file currently uses Unicode punctuation (…, —). Please switch those to ASCII equivalents (..., --) to match repo encoding standards.

Proposed fix
-/// (write, append, find, replace, resize, hashing, …) and is
+/// (write, append, find, replace, resize, hashing, ...) and is
@@
-/// (vec2, vector, span, …). See `agents/docs/string-architecture.md`.
+/// (vec2, vector, span, ...). See `agents/docs/string-architecture.md`.
@@
-    // AND the basic_string must not be trivially relocated (bitwise
+    // AND the basic_string must not be trivially relocated (bitwise
@@
-    // copied to a different address) — `mInlineOffset` is computed
+    // copied to a different address) -- `mInlineOffset` is computed

As per coding guidelines, “Source code in this repo must be 7-bit ASCII only (no emoji/unicode math glyphs in headers/impls).”

Also applies to: 449-450

🤖 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/basic_string.h` around lines 38 - 43, Header comment uses Unicode
punctuation characters (ellipsis and em-dash) in the docblock describing
basic_string and fl::string; replace all non-ASCII punctuation (e.g., “…”, “—”)
with ASCII equivalents ("..." and "--") in this comment and any other
occurrences (notably lines referenced around basic_string and fl::string) so the
file complies with the repo's 7-bit ASCII policy.

Source: Coding guidelines


455-458: ⚠️ Potential issue | 🔴 Critical

Fix basic_string inline-buffer offset signedness; remove non-ASCII punctuation in basic_string.h.

  • basic_string(char* inlineBuffer, ...) stores inlineBuffer - this into fl::size, so if inlineBuffer is located at an address lower than this, the subtraction is negative and can wrap—then inlineBufferPtr() computes an invalid pointer (memory corruption/crash). Store the offset as fl::ptrdiff_t instead.
  • src/fl/stl/basic_string.h contains non-ASCII comment punctuation (ellipsis “…” and em dash “—”), violating the 7-bit ASCII-only rule.
Proposed fix
-    basic_string(char* inlineBuffer, fl::size inlineCapacity) FL_NOEXCEPT
-        : mInlineOffset(static_cast<fl::size>(
-              inlineBuffer -
-              static_cast<char*>(static_cast<void*>(this))))
+    basic_string(char* inlineBuffer, fl::size inlineCapacity) FL_NOEXCEPT
+        : mInlineOffset(
+              inlineBuffer - static_cast<char*>(static_cast<void*>(this)))
         , mInlineCapacity(inlineCapacity)
         , mLength(0)
         , mStorage() // empty variant = inline mode
     {}
@@
-    fl::size mInlineOffset;
+    fl::ptrdiff_t mInlineOffset;
🤖 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/basic_string.h` around lines 455 - 458, The inline-buffer offset
in basic_string's constructor is stored in an unsigned fl::size causing negative
pointer differences to wrap; change the type of mInlineOffset to a signed
fl::ptrdiff_t and store the result of (inlineBuffer -
static_cast<char*>(static_cast<void*>(this))) into that signed type so
inlineBufferPtr() computes a valid pointer; update all uses/assignments and any
ctor initializer that references mInlineOffset (the basic_string(char*
inlineBuffer, fl::size inlineCapacity) ctor and related accessors) to use
fl::ptrdiff_t instead of fl::size. Also scan src/fl/stl/basic_string.h comments
and replace non-ASCII punctuation (the ellipsis “…” and em dash “—”) with ASCII
equivalents (...) and (--) to satisfy the 7-bit ASCII rule.
🤖 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.

Outside diff comments:
In `@src/fl/stl/basic_string.h`:
- Around line 38-43: Header comment uses Unicode punctuation characters
(ellipsis and em-dash) in the docblock describing basic_string and fl::string;
replace all non-ASCII punctuation (e.g., “…”, “—”) with ASCII equivalents ("..."
and "--") in this comment and any other occurrences (notably lines referenced
around basic_string and fl::string) so the file complies with the repo's 7-bit
ASCII policy.
- Around line 455-458: The inline-buffer offset in basic_string's constructor is
stored in an unsigned fl::size causing negative pointer differences to wrap;
change the type of mInlineOffset to a signed fl::ptrdiff_t and store the result
of (inlineBuffer - static_cast<char*>(static_cast<void*>(this))) into that
signed type so inlineBufferPtr() computes a valid pointer; update all
uses/assignments and any ctor initializer that references mInlineOffset (the
basic_string(char* inlineBuffer, fl::size inlineCapacity) ctor and related
accessors) to use fl::ptrdiff_t instead of fl::size. Also scan
src/fl/stl/basic_string.h comments and replace non-ASCII punctuation (the
ellipsis “…” and em dash “—”) with ASCII equivalents (...) and (--) to satisfy
the 7-bit ASCII rule.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 5b7cc751-7b5f-4b53-a848-cf5dac97b13f

📥 Commits

Reviewing files that changed from the base of the PR and between 0b48121 and e3ecdf8.

📒 Files selected for processing (5)
  • agents/docs/string-architecture.md
  • src/fl/stl/basic_string.cpp.hpp
  • src/fl/stl/basic_string.h
  • src/fl/stl/string.cpp.hpp
  • tests/fl/stl/string.cpp
✅ Files skipped from review due to trivial changes (1)
  • agents/docs/string-architecture.md
🚧 Files skipped from review as they are similar to previous changes (3)
  • src/fl/stl/basic_string.cpp.hpp
  • tests/fl/stl/string.cpp
  • src/fl/stl/string.cpp.hpp

…rner

Closes the last open CodeRabbit finding on #2961.

Previously `string::interned()` family wrapped each input in a
fresh `StringHolder`, so two calls with identical content produced
two distinct holders — no deduplication, contrary to the name.
This commit routes all three overloads through
`fl::global_interner().intern(...)`, matching the semantics of
`string::intern()` and giving callers actual O(1) average-case
deduplication via the interner's hash map.

Behavior change: yes — callers that relied on `interned()`
returning a NEW holder per call (rather than a deduplicated one)
would observe shared identity now. Searching the tree, no caller
appears to depend on the old behavior; `intern()` already
de-duplicated and was used for the same purpose. The function
name "interned" implies the new behavior, so this is a bugfix.

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

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Now that all string logic lives in `fl::basic_string` (compiled
exactly once), bring back the templated inline-buffer wrapper as
`fl::string_n<N>` so callers can pick an inline size that fits
their workload.

Three layers:

  fl::string  →  fl::string_n<N>  →  fl::basic_string
  (composites)   (inline buffer)     (all the bytes)

Per-N instantiations of `string_n<N>` are constructor stubs
(`: basic_string(mInlineBuffer, N) {}` plus a one-line body that
calls a non-template helper on the base). Identical stubs fold
under COMDAT; non-trivial code stays in basic_string. No measurable
bloat per added N value.

Public aliases:
- `fl::string_small` = `string_n<32>` — constrained MCUs
- `fl::string` extends `string_n<FASTLED_STR_INLINED_SIZE>` (64
  by default) with composite-type formatters (CRGB, vec2, span,
  vector, optional, …), substring/trim, factories, comparisons
- `fl::string_large` = `string_n<256>` — text-heavy paths

All three layout-compatible; cross-size copy/move/assign works
because the underlying basic_string storage policy is uniform.
Choosing a size is purely an "expected inline length" knob —
exceeding it triggers heap-backed StringHolder promotion in any
case.

## Implementation

- `string.h` — new `template <fl::size N> class string_n` with
  the standard ctor set (default, char*, char*+len, size+char,
  copy + cross-size copy template, move, basic_string, string_view,
  span/span-const, shared_ptr, InputIt, char[N]) + assignment ops.
  `fl::string` now inherits `string_n<FASTLED_STR_INLINED_SIZE>`
  instead of `basic_string` directly; its `mInlineBuffer` field
  is gone (lives in the base template now).
- `string.cpp.hpp` — `fl::string`'s non-template ctors become
  one-line forwarders to the equivalent `string_n<...>` ctors,
  so the buffer-init logic exists in exactly one place.
- `agents/docs/string-architecture.md` — rewritten to describe
  the three-layer design + the "why this isn't bloat" rationale.

## Verification

- [x] `bash lint --cpp` — clean (one pre-existing PlatformIO warning, #2701)
- [x] Compile probe: `fl::string_small`, `fl::string`,
  `fl::string_large` construct + cross-size copy + assignment;
  `fl::string` keeps the full pre-PR API (substring/trim,
  factories, comparisons, operator+=); `basic_string(char*, size)`
  and `basic_string(span)` still work for callers who manage
  their own buffer.

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

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@zackees
zackees merged commit fefca7b into master Jun 7, 2026
5 of 7 checks passed
@fastled-project-sync fastled-project-sync Bot moved this from Triage to Done in FastLED Tracker Jun 7, 2026
zackees added a commit that referenced this pull request Jun 8, 2026
Two pre-existing failures in `bash test fl_stl_string --cpp` on master:

1. `fl::printf_detail::format_float` (the underlying impl behind
   `fl::ftoa` and printf's `%f`) was emitting "0.0"/"1.0" for
   `precision=2` calls on integer-valued floats. The legacy
   pad-zero loop terminated at `temp_multiplier > 1`, dropping the
   final zero, and the digit-emission branch was guarded by
   `frac_part > 0`, suppressing all fractional output when zero.
   Replaced with a clean exact-`precision`-digit emitter that
   computes each digit positionally so "0.0f" -> "0.00",
   "1.0f" -> "1.00", "-1.5f" -> "-1.50", and small negatives like
   "-0.05f" preserve their sign even when the integer part rounds
   to zero.

2. Test "substr/substring on heap-promoted string (>64 chars)"
   used a 64-char literal — exactly `FASTLED_STR_INLINED_SIZE` —
   so the string stayed inline and `FL_CHECK_GT(s.size(), 64)`
   fired. Extended the literal to 66 chars to actually heap-
   promote.

Together these unblock the `unit tests linux` CI gate that was
failing on every PR branched from master after #2961/#2962.

Closes #2970

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

* fix(fl::ftoa): honor precision, pad trailing zeros; fix substr test data

Two pre-existing failures in `bash test fl_stl_string --cpp` on master:

1. `fl::printf_detail::format_float` (the underlying impl behind
   `fl::ftoa` and printf's `%f`) was emitting "0.0"/"1.0" for
   `precision=2` calls on integer-valued floats. The legacy
   pad-zero loop terminated at `temp_multiplier > 1`, dropping the
   final zero, and the digit-emission branch was guarded by
   `frac_part > 0`, suppressing all fractional output when zero.
   Replaced with a clean exact-`precision`-digit emitter that
   computes each digit positionally so "0.0f" -> "0.00",
   "1.0f" -> "1.00", "-1.5f" -> "-1.50", and small negatives like
   "-0.05f" preserve their sign even when the integer part rounds
   to zero.

2. Test "substr/substring on heap-promoted string (>64 chars)"
   used a 64-char literal — exactly `FASTLED_STR_INLINED_SIZE` —
   so the string stayed inline and `FL_CHECK_GT(s.size(), 64)`
   fired. Extended the literal to 66 chars to actually heap-
   promote.

Together these unblock the `unit tests linux` CI gate that was
failing on every PR branched from master after #2961/#2962.

Closes #2970

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

* chore(bloat): bump esp32s3 baseline 338247 -> 338368 (+121 B from ftoa rewrite)

format_float in src/fl/stl/stdio.h grew by ~121 B after the rewrite to
honor the precision/pad argument. Update the baseline so the bloat-
regression gate passes. Net regression is small and one-time (the gate
exists to catch ongoing drift, not intentional fixes).

---------

Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
@zackees
zackees deleted the feat/string-base-span-api 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.

1 participant