Skip to content

perf(flat_map): type-erase lower_bound / upper_bound binary search (#3235 Tier 2D) - #3239

Merged
zackees merged 1 commit into
masterfrom
feat/flat-map-basic-3235-tier2d
Jun 18, 2026
Merged

zackees merged 1 commit into
masterfrom
feat/flat-map-basic-3235-tier2d

Conversation

@zackees

@zackees zackees commented Jun 18, 2026 •

Copy link
Copy Markdown
Member

Closes #3235 Tier 2D.

Lands / as non-template shared cores under fl/stl/flat_map_basic.h. Comparator dispatch through a function-pointer-with-context tuple to support stateful comparators uniformly with stateless ones.

FL_NO_INLINE on the implementations is load-bearing — without it LTO inlines the bodies back at each call site, defeating dedup.

Measurement honesty

On AutoResearch (1-2 flat_map instances) the per-call thunk overhead matches or slightly exceeds the per-instance savings, so the immediate flash delta is neutral-to-negative. The win materializes on builds with more instantiations — the audit predicted ~6-9 KB on kitchen-sink builds with ~30 flat_map types. Landing the infrastructure now so future additions amortize against the shared core (the fl::vector_basic precedent.)

Sketch flat_map instances Net flash change
LPC845 / AutoResearch 1 +72 B
Teensy 4 / AutoResearch 2 ±0 B

Test plan

  • LPC845 / AutoResearch build → succeeded
  • Teensy 4 / AutoResearch build → succeeded (separately verified earlier in session)
  • CI matrix

Refs #3235 (Tier 2D)

Summary by CodeRabbit

  • Refactor
    • Reorganized internal flat_map implementation to reduce code duplication and improve maintainability.

…3235 Tier 2D)

Extracts the binary-search inner loop from `fl::flat_map<K, V, Less>`
into a non-template `fl::detail::flat_map_lower_bound_idx` /
`flat_map_upper_bound_idx` pair under `fl/stl/flat_map_basic.h`.
Comparator dispatch goes through a `(less_fn, less_ctx)` function-
pointer-with-context tuple so stateful comparators (e.g.
StringFastLess if it ever needs intern-table state) work the same as
stateless ones. The element layout assumes `pair<K,V>::first` at
offset 0 (standard layout).

## Why noinline matters here

`FL_NO_INLINE` on the implementation functions is load-bearing. With
LTO enabled (default on every embedded target), the compiler would
otherwise fold the body back into each call site, defeating the dedup
goal. The runtime cost (one indirect `call` + return) is negligible
against the lookup work the caller is doing anyway.

## Per-instantiation budget

| Sketch | flat_map instances | Net change |
|---|---:|---:|
| LPC845 / AutoResearch | 1 | +72 B (per-call thunk overhead > 1-instance savings) |
| Teensy 4 / AutoResearch | 2 | ±0 B |

The win materializes on larger builds — `fl::vector_basic`'s precedent
shows that type-erasure pays back once a handful of instantiations
exist. AutoResearch is below that threshold for flat_map; bigger
sketches (WASM compiler runtime, kitchen-sink CI matrix builds) will
demonstrate the audit's predicted ~6-9 KB savings once the codebase
grows. Landing the infrastructure now so future flat_map additions
amortize against the shared core.

Refs #3235 Tier 2D
@coderabbitai

coderabbitai Bot commented Jun 18, 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: bdc02f86-8bae-4597-a66f-4e3e73004e00

📥 Commits

Reviewing files that changed from the base of the PR and between 3d15703 and 9cdc995.

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

📝 Walkthrough

Walkthrough

Introduces a type-erased binary-search core for fl::flat_map to reduce per-template-instantiation code size. A new flat_map_basic.h declares comparator thunk types and an flat_map_ops parameter block; flat_map_basic.cpp.hpp implements the FL_NO_INLINE lower_bound/upper_bound index helpers. flat_map.h is refactored to delegate its bounds methods to these helpers via a less_thunk and make_ops(). The unity build header is updated to include the new implementation file.

Changes

Type-erased flat_map binary-search core

Layer / File(s) Summary
Type-erased ops contract and binary-search implementation
src/fl/stl/flat_map_basic.h, src/fl/stl/flat_map_basic.cpp.hpp
flat_map_basic.h declares flat_map_less_thunk_t, flat_map_ops (thunk + context + element stride), and FL_NO_INLINE declarations for flat_map_lower_bound_idx / flat_map_upper_bound_idx. flat_map_basic.cpp.hpp implements both binary-search helpers over a raw byte buffer, using ops.less_fn with pointer arithmetic to locate the mid-element key.
flat_map delegation and unity build registration
src/fl/stl/flat_map.h, src/fl/stl/_build.cpp.hpp
flat_map.h adds #include "fl/stl/flat_map_basic.h", introduces a less_thunk static comparator and make_ops() builder, and replaces the previous inline binary-search loops in lower_bound/upper_bound (and their const overloads) with calls to detail::flat_map_lower_bound_idx / detail::flat_map_upper_bound_idx. _build.cpp.hpp adds the include for flat_map_basic.cpp.hpp in the unity build list.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Poem

🐇 Hop, hop — one binary search to rule them all,
No more typed copies piling down the hall!
A thunk, a stride, a raw-byte mid-point found,
The flash map shrinks without a wasted round.
Less code, more hops — the rabbit stamps the ground! 🗺️

✨ 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/flat-map-basic-3235-tier2d

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.

@zackees
zackees merged commit be2fbd5 into master Jun 18, 2026
10 checks passed
@fastled-project-sync fastled-project-sync Bot moved this to Triage in FastLED Tracker Jun 18, 2026
@fastled-project-sync fastled-project-sync Bot moved this from Triage to Done in FastLED Tracker Jun 18, 2026
zackees added a commit that referenced this pull request Jun 19, 2026
…3244 Tier 3H) (#3267)

* perf(deque): deque_basic ring-buffer + grow-policy helpers (#3250 / #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]>

* fix(deque): guard deque_grow_capacity against wraparound (#3267 review)

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

* fix(deque): guard ensure_capacity byte-size against overflow (#3267 review)

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

---------

Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
@zackees
zackees deleted the feat/flat-map-basic-3235-tier2d 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.

META: type-erasure burn-down -- collapse template-instantiation taxes across containers / RPC / visitors / fl::function / chipset controllers

1 participant