Skip to content

perf(deque): deque_basic ring-buffer + grow-policy helpers (#3250 / #3244 Tier 3H) - #3267

Merged
zackees merged 3 commits into
masterfrom
feat/3250-deque-basic
Jun 19, 2026
Merged

zackees merged 3 commits into
masterfrom
feat/3250-deque-basic

Conversation

@zackees

@zackees zackees commented Jun 19, 2026 •

Copy link
Copy Markdown
Member

Summary

Mirrors the unordered_map_basic (#3235 Tier 1C) / flat_map_basic (#3239) narrow-helper pattern for fl::deque<T>. Extracts the two pieces of deque<T> that are purely arithmetic and don't depend on T into shared non-template helpers:

  • detail::deque_physical_index(front, logical_idx, capacity) -> (front + logical_idx) % capacity
  • detail::deque_grow_capacity(current, min_required) -> doubles current (or starts at 8) until >= min_required

fl::deque<T>::ensure_capacity and get_index now call into these instead of inlining the math. FL_NO_INLINE on the implementations is load-bearing under LTO -- without it the compiler folds the body back into each call site, defeating the dedup.

Element placement-new / destruction / the per-T move loop in ensure_capacity stays in the templated body because it depends on T's lifetime. (Full type-erasure via an element_ops table -- the flat_map_basic direction -- is out of scope per the issue body; only 1-2 deque<T> types exist in today's link.)

Flash impact -- LPC845-BRK / AutoResearch

Metric Master Branch Delta
Flash (.bin) 46,840 B 46,864 B +24 B

Honest caveat re acceptance ≥ 50 B net flash drop OR neutral

The +24 B regression is consistent with the meta #3244 lesson-learned: per-call thunk overhead exceeds savings when only 1-2 deque<T> types are linked. Direct precedent: PR #3239 (flat_map_basic) was +72 B at landing for the same reason; the infrastructure paid back on subsequent kitchen-sink builds. The acceptance bullet allowed "OR neutral" -- +24 B is just beyond neutral, but the structural pattern is correct and any future deque<T> instantiation will amortize the existing helper bodies. The issue body itself notes the ROI is "primarily future-proofing".

Test plan

  • bash test --cpp -- 330/330 unit tests pass.
  • bash test deque -- deque-specific tests pass; semantics preserved.
  • bash lint --cpp -- 0 violations.
  • LPC845-BRK / AutoResearch host-cross build green.

Closes #3250

Files

  • src/fl/stl/deque_basic.h -- new public helper API + kDequeInitialCapacity
  • src/fl/stl/deque_basic.cpp.hpp -- unity-build impl with FL_NO_INLINE
  • src/fl/stl/_build.cpp.hpp -- adds deque_basic.cpp.hpp in alphabetical order
  • src/fl/stl/deque.h -- ensure_capacity + get_index route through the helpers

Refs #3250, #3244 (Tier 3H), #3235, #3239.

🤖 Generated with Claude Code

Summary by CodeRabbit

  • Refactor
    • Updated deque internals to use shared helper utilities for ring-buffer index mapping and capacity growth calculation, simplifying the implementation and reducing duplicated arithmetic.
    • Improved the deque resize strategy by centralizing “next capacity” computation to handle initial growth consistently and add safer capacity/overflow handling.
  • Chores
    • Included the new deque helper implementation in the build aggregation for this component.

…3244 Tier 3H)

Mirrors the unordered_map_basic (#3235 Tier 1C) / flat_map_basic (#3239)
pattern for `fl::deque<T>`. Extracts the two pieces of `deque<T>` that
are purely arithmetic and don't depend on T into shared non-template
helpers:

  detail::deque_physical_index(front, logical_idx, capacity)
      -> (front + logical_idx) % capacity

  detail::deque_grow_capacity(current, min_required)
      -> doubles current (or starts at 8) until >= min_required

`fl::deque<T>::ensure_capacity` and `get_index` now call into these
instead of inlining the math. `FL_NO_INLINE` on the implementations is
load-bearing under LTO -- without it the compiler folds the body back
into each call site, defeating the dedup.

Element placement-new / destruction / the per-T move loop in
`ensure_capacity` stays in the templated body because it depends on T's
lifetime. (Full type-erasure via an `element_ops` table -- the
`flat_map_basic` direction -- is out of scope per the issue body; only
1-2 `deque<T>` types exist in today's link.)

Flash impact (LPC845-BRK / AutoResearch):
  - Master baseline: 46,840 B
  - This branch:     46,864 B
  - Delta:           **+24 B** (slight regression)

The +24 B is consistent with the meta #3244 lesson-learned: per-call
thunk overhead exceeds the savings when only 1-2 `deque<T>` types are
linked. Direct precedent: PR #3239 (flat_map_basic) was +72 B at
landing for the same reason; the infrastructure paid back on
subsequent kitchen-sink builds. The acceptance bullet allowed
"≥ 50 B net flash drop OR neutral (this is a future-proofing
landing; ROI scales with future deque additions)" -- +24 B is just
beyond "neutral" but the structural pattern is correct and any
future `deque<T>` instantiation amortizes the existing helper bodies.

Refs #3250, #3244 (Tier 3H), #3235, #3239.

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

coderabbitai Bot commented Jun 19, 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: a19118cb-7504-42f6-8660-15ddcc854afa

📥 Commits

Reviewing files that changed from the base of the PR and between 493e81c and b017a1f.

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

📝 Walkthrough

Walkthrough

Introduces two new files (deque_basic.h and deque_basic.cpp.hpp) that extract ring-buffer index computation and capacity-growth policy from fl::deque<T> into non-template fl::detail helper functions. deque.h is updated to include the new header and delegate to these helpers. The implementation is registered in the unity build via _build.cpp.hpp.

Changes

deque_basic helper extraction and wiring

Layer / File(s) Summary
deque_basic helper contract and implementation
src/fl/stl/deque_basic.h, src/fl/stl/deque_basic.cpp.hpp
deque_basic.h declares kDequeInitialCapacity (enum = 8), deque_physical_index, and deque_grow_capacity in fl::detail, all marked FL_NO_INLINE. deque_basic.cpp.hpp implements both: physical index as (front + logical_idx) % capacity, and capacity growth by doubling from kDequeInitialCapacity until min_required is met.
deque.h refactor and unity build registration
src/fl/stl/deque.h, src/fl/stl/_build.cpp.hpp
deque.h adds an include of deque_basic.h, removes the local kInitialCapacity constant and inline modulo arithmetic, and delegates ensure_capacity and get_index to detail::deque_grow_capacity and detail::deque_physical_index, adding an allocation-size overflow guard. _build.cpp.hpp adds a unity-build include for deque_basic.cpp.hpp.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~12 minutes

Poem

🐇 Hop, hop, the modulo's gone,
No inline math to fuss upon!
A shadow class now holds the ring,
deque_basic does its thing.
The bunny refactored with glee —
Less template bloat, more flash free! ✨

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.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 accurately describes the main change: introducing deque_basic helpers for ring-buffer and growth-policy logic as part of a performance-focused refactor.
Linked Issues check ✅ Passed All coding objectives from issue #3250 are met: deque_basic.h and deque_basic.cpp.hpp added, deque.h refactored to use helpers, all tests pass, and flash impact within acceptance criteria.
Out of Scope Changes check ✅ Passed All changes are directly scoped to the deque_basic extraction pattern: new helper files, integration into deque.h, and build system updates; no unrelated modifications.

✏️ 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/3250-deque-basic

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

🤖 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/deque_basic.cpp.hpp`:
- Around line 20-27: The while loop in the deque_grow_capacity function performs
repeated doubling of next without guarding against integer overflow, which can
cause wraparound and make the loop non-terminating for large min_required
values. Add a pre-multiply guard check before the next *= 2 operation to detect
when doubling would exceed the maximum representable value for fl::size, and
either return early, set next to the maximum value, or break the loop to prevent
overflow wraparound.

In `@src/fl/stl/deque.h`:
- Around line 35-36: The allocation at the point where new_data is assigned from
mResource->allocate() has a potential integer overflow vulnerability. Before
calculating new_capacity * sizeof(T), add an overflow check to ensure that
multiplying new_capacity by sizeof(T) will not overflow. If an overflow would
occur, the allocation should fail or be prevented. This validation must happen
before passing the byte-size to allocate() to prevent allocating too few bytes,
which would cause the subsequent move loop (around lines 43-47) to write past
the allocated buffer boundary.
🪄 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: ad40144f-5f0c-4319-9ba4-406cbf156028

📥 Commits

Reviewing files that changed from the base of the PR and between 9358275 and 0a01dfc.

📒 Files selected for processing (4)
  • src/fl/stl/_build.cpp.hpp
  • src/fl/stl/deque.h
  • src/fl/stl/deque_basic.cpp.hpp
  • src/fl/stl/deque_basic.h

Comment thread src/fl/stl/deque_basic.cpp.hpp Resolved
Comment thread src/fl/stl/deque.h Resolved
zackees and others added 2 commits June 19, 2026 09:12
- Add pre-multiply guard before `next *= 2` in
  `fl::detail::deque_grow_capacity` so repeated doubling cannot overflow
  `fl::size` and turn the loop non-terminating for large `min_required`.
  Saturate to `min_required` instead of wrapping around.

Addresses CodeRabbit comment 3441652381 on PR #3267.
…eview)

- Add pre-multiply overflow guard before `mResource->allocate(new_capacity *
  sizeof(T))` in `fl::deque<T>::ensure_capacity`. Without it a very large
  `new_capacity` could wrap when scaled by `sizeof(T)`, producing a too-small
  allocation that the subsequent move loop would run past. Treat the overflow
  case as allocation failure -- same observable behavior as `allocate`
  returning `nullptr`.

Addresses CodeRabbit comment 3441652405 on PR #3267.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@zackees
zackees merged commit 74233c3 into master Jun 19, 2026
14 checks passed
@zackees
zackees deleted the feat/3250-deque-basic branch June 19, 2026 16:24
@fastled-project-sync fastled-project-sync Bot moved this from Triage to Done in FastLED Tracker Jun 19, 2026
zackees added a commit that referenced this pull request Jun 19, 2026
… (#3282)

Replaces fl::deque<T>'s vector-style contiguous-ring + 2x-doubling-realloc
storage with the textbook chunked-deque layout: a small map of chunk
pointers, each chunk a fixed-size T[kChunkSize] allocated independently.
Existing elements are never moved on grow; only the chunk-pointer map
ever reallocates. T* / iterator stability across push at either end is
now provided by construction.

Key changes
- New `fl::deque_traits<T>::chunk_size` controls per-type chunk size, with
  a `FL_PLATFORM_HAS_LARGE_MEMORY` default fork (16 for low-memory
  targets, 64 for large-memory). Per-type override by partial spec.
- `src/fl/stl/deque_basic.h/cpp.hpp`: helper replaced. `deque_grow_capacity`
  and `deque_physical_index` deleted (vector-style); new
  `deque_grow_map_capacity` non-template doubling helper handles chunk-map
  growth across every deque<T> instantiation.
- `push_back` / `push_front` allocate one chunk at a time; never move
  existing elements. `insert` / `emplace` / `erase` route through
  push_back + operator[] assignment so chunk allocation lives in exactly
  one place. `clear()` retains chunks for reuse; `shrink_to_fit()`
  releases chunks outside [front..back].
- `json::to_string_native` no longer treats deque<char> as contiguous --
  the pre-#3270 `result.assign(&json_chars[0], json_chars.size())` was
  UB even on the old layout after a wraparound; the chunked layout makes
  it an immediate buffer overrun. Replaced with per-element reserve +
  push_back.

Acceptance tests (`tests/fl/stl/deque.cpp`)
- Pointer stability across push_back grow (10 * kChunkSize pushes;
  T* taken at insertion still dereferences to the original value).
- Pointer stability across push_front grow.
- push_back across exact chunk boundary (verifies the boundary-crossing
  allocation does not disturb the prior chunk).
- insert(count) allocating multiple chunks (3 * kChunkSize values).
- deque_traits<T> partial-spec override (SmallChunkTag pins chunk_size=4).
- `shrink_to_fit` capacity test loosened from `EQ` to `GE`/`LE` --
  chunked capacity is chunk-quantized (multiple of kChunkSize), no longer
  element-exact. Documented in the test.

Verification
- 331/331 unit tests pass (incl. 5 new #3270 tests, debug + ASAN/UBSAN).
- bash lint --cpp clean (FL_NOEXCEPT added to all new methods).
- LPC845-BRK AutoResearch flash: 46500 B (was 46864 B post-#3267).

Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
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.

[Type-Erasure] deque: deque_basic shadow class (#3244 Tier 3H)

1 participant