Repository navigation
Description
Problem
fl::deque<T> (src/fl/stl/deque.h) is structurally a single contiguous ring buffer that doubles its capacity on overflow — i.e. a fl::vector<T> with a mFront index trick on top. PR #3267 (deque_basic Tier 3H) made the grow-arithmetic non-template but did not change the shape.
The grow body today:
// detail::deque_grow_capacity
fl::size next = current_capacity == 0
? kDequeInitialCapacity // = 8
: current_capacity * 2;
while (next < min_required) { next *= 2; }
return next;// fl::deque<T>::ensure_capacity
T* new_data = allocate(new_capacity * sizeof(T)); // one contiguous slab
for (i in [0, mSize)) { new(new_data[i]) T(move(mData[old_idx])); mData[old_idx].~T(); }
deallocate(mData, mCapacity * sizeof(T));That is not the right shape for a deque. std::deque is specified as a sequence container with O(1) push_front / push_back where existing elements are never moved on grow and references / pointers to elements remain stable across insertions at either end. The current implementation violates both: every overflow walks N elements and invalidates every pointer / iterator that wasn't sourced from the new allocation.
Why the shape matters here
In-tree call sites that are demonstrably the wrong shape under doubling-realloc:
| Site | Type | Pattern |
|---|---|---|
src/fl/audio/detector/transient.h:62 |
deque<float> |
Sliding energy-history window |
src/fl/audio/detector/tempo_analyzer.h:69 |
deque<u32> |
Sliding onset-time window |
src/fl/audio/detector/tempo_analyzer.h:84 |
deque<float> |
Sliding BPM-history window |
src/fl/audio/detector/musical_beat_detector.h:157 |
deque<u32> |
Sliding inter-beat-interval window |
src/fl/audio/detector/downbeat.h:127,131 |
deque<float>, deque<u8> |
Sliding beat-accent / meter-candidate windows |
src/fl/audio/detector/backbeat.h:149,150 |
deque<float> × 2 |
Sliding backbeat-accent windows |
src/fl/stl/json.cpp.hpp |
deque<char> |
Streaming-parse working buffer |
src/platforms/esp/32/drivers/parlio/channel_driver_parlio.h |
deque<u8> |
DMA byte queue |
Every audio-detector deque is a fixed-cadence sliding window. Under doubling-realloc, hitting capacity inside the ISR / audio-thread hot path triggers a synchronous O(N) move-and-deallocate, which on an embedded target is a hard real-time stall the audio pipeline cannot absorb. Today it works only because the windows are sized such that the realloc happens once at warm-up and then never again — i.e. the deque is being used as if it were stable-storage, which is exactly the contract a real chunked deque provides cheaply.
Proposed shape
Replace the contiguous-slab + doubling-realloc strategy with the textbook map-of-fixed-size-chunks layout:
T* chunks[]— small map of chunk pointers (itself a small contiguous array; reallocated rarely, only when the chunk-map fills up).- Each chunk is a fixed-size
T[kDequeChunkSize]allocated independently. push_back/push_frontallocate one new chunk when the active end-chunk is full. Existing elements are never moved.- Multi-element insert (
insert,resize(n)) allocatesceil(needed / kDequeChunkSize)new chunks in one go. kDequeChunkSizeis a compile-time constant with an overridable default:- Default:
16for!FL_PLATFORM_HAS_LARGE_MEMORY(LPC845, ESP8266, AVR),64for Large-memory (Teensy, ESP32, host). - Per-type override via partial-spec
fl::deque_traits<T>::chunk_sizeor a compile-time template parameter, so audio detectors that know their window size can pin chunk-size to match.
- Default:
Acceptance criteria
-
fl::deque<T>reimplemented as a map-of-chunks. Element access remains O(1); the map lookup is one indirection followed by intra-chunk indexing. -
push_back/push_frontare O(1) with no element moves. Verified by a unit test that pushes 10 ×kDequeChunkSizeitems and asserts that pointers to previously-inserted elements remain valid (T*taken at insertion time still dereferences to the same value after subsequent pushes). -
kDequeChunkSizedefault fork onFL_PLATFORM_HAS_LARGE_MEMORY(16vs64). - Per-type override mechanism wired (either
deque_traits<T>::chunk_sizepartial-spec or template parameter — author's choice). - All existing deque tests (
tests/fl/stl/deque/*) pass unchanged. New tests cover: pointer stability across grow, chunk-boundary push/pop, multi-element insert allocating multiple chunks, iterator validity across grow. - No regression in the json / parlio / audio-detector call sites.
bash test --cppgreen. - LPC845-BRK / AutoResearch flash impact recorded. Expected: slightly larger (chunk-map + chunk-allocation bookkeeping) but bounded — chunked deques are not a flash-size win, they are a correctness + real-time-safety win.
Migration plan for current call sites
The current deque<T>::operator[], front(), back(), begin(), end(), iterator semantics, and size() / empty() are externally observable. Preserving them is the migration plan: the rewrite is opaque to every existing caller as long as the external API stays byte-identical. The iterator must internally carry (chunk_map_idx, intra_chunk_idx) instead of a single mIndex, but its public operators (++, --, +=, -=, *, ->, comparison) keep the same signatures.
The two intentionally-removed semantics are:
data()— does not exist on a chunked deque (no contiguous storage). Verify no caller uses it. (std::dequealso does not exposedata().)- Pointer / iterator invalidation rules — change from "invalidated on any grow" to "stable across push at either end; invalidated only on element relocation in the middle." This is a strengthening of the contract; no existing caller can depend on the weaker rule being wrong.
Out of scope
fl::queue<T>(which defaults its container tofl::deque<T>) — gets the new shape for free; no changes needed.- The
deque_basicnon-template helper from PR perf(deque): deque_basic ring-buffer + grow-policy helpers (#3250 / #3244 Tier 3H) #3267 — entirely replaced by chunk-arithmetic helpers (deque_chunk_index,deque_grow_chunkmap). Thedeque_grow_capacitybody insrc/fl/stl/deque_basic.cpp.hppis deleted as part of this work. - Allocator customization beyond the existing
memory_resource*— chunk allocation uses the same resource the deque was constructed with. shrink_to_fitaggressive chunk-release — first pass releases empty end-chunks onpop_back/pop_front; further compaction is a follow-up.
Risk
- The audio-detector sliding-window pattern may be deliberately sized to never realloc today. The chunked version will allocate chunks one at a time as the window grows, so heap pressure during warm-up is N small allocations instead of 1 doubling allocation. For platforms with a fragmenting allocator this could be a regression — flag during review.
- Chunk-size tuning is a workload-dependent knob. The default fork on
FL_PLATFORM_HAS_LARGE_MEMORYis a first guess; per-type override is the escape hatch. - The iterator becoming a 2-field struct (chunk-map idx + intra-chunk idx) inflates its size from one
fl::sizeto two. Auditfl::deque<T>::iteratorcallers — most pass by value, but anything copying iterators heavily (e.g.find,find_ifover the entire deque) will see a small per-call cost.
Refs
- Predecessor: PR perf(deque): deque_basic ring-buffer + grow-policy helpers (#3250 / #3244 Tier 3H) #3267 / [Type-Erasure] deque: deque_basic shadow class (#3244 Tier 3H) #3250 / meta META: memory & flash reduction -- Phase 3 burn-down (continues #3235) #3244 Tier 3H — landed the
deque_basicnon-template helpers on the current vector-style shape. That work stays in tree only as far asdeque_physical_indexis reusable; the grow-capacity helper goes away. std::dequereference shape: cppreference / libstdc++stl_deque.h.
Metadata
Metadata
Assignees
Labels
Type
Projects
- StatusShow more project fieldsDone
Activity
refactor(deque): chunked map-of-fixed-size-blocks layout (closes #3270)…
fix(deque): free orphaned chunks in grow_map to stop chunked-deque le…