sefer-region 0.2.0

Typed, generational handle-addressed store over slotmap — zero own unsafe, no C/C++, no_std + alloc capable.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
//! [`Region`] — a handle-addressed store of `T` backed by `slotmap`.

use crate::Handle;
use core::num::NonZeroUsize;
use core::sync::atomic::AtomicUsize;

/// Process-wide counter for minting unique `region_id` values.
///
/// This counter starts at 1 and is incremented once per `Region::new`/`with_capacity`
/// call. The value 0 is reserved as a permanent "exhausted" sentinel — once the counter
/// wraps to 0, all future `Region` constructions panic forever, ensuring no region_id
/// is ever reused.
static NEXT_REGION_ID: AtomicUsize = AtomicUsize::new(1);

/// Domain limits for slotmap backing store.
///
/// `slotmap` reserves one slot as a sentinel; `try_with_capacity` therefore
/// rejects `capacity > 2^32 - 3` while `try_reserve` rejects `len() + additional > 2^32 - 2`
/// (the extra slot can be filled after construction via `insert`).
const SLOTMAP_MAX_RESERVE: usize = ((1u64 << 32) - 3) as usize;
const SLOTMAP_MAX_LIVE: usize = ((1u64 << 32) - 2) as usize;

/// Error type returned when the process-wide `region_id` counter is exhausted.
///
/// This error is returned by the internal ID-issuance helper when the counter
/// has reached `usize::MAX` and transitioned to the exhausted sentinel (0).
/// After this point, all future `Region::new`/`with_capacity` calls will fail.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct RegionIdExhaustedError;

impl core::fmt::Display for RegionIdExhaustedError {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        f.write_str("process-wide region_id counter exhausted")
    }
}

impl core::error::Error for RegionIdExhaustedError {}

/// Error returned by fallible `Region<T>` constructors and capacity operations.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TryReserveError {
    /// The requested capacity/length exceeds slotmap's maximum live-entry domain.
    CapacityExceeded {
        /// The capacity or length that was requested
        requested: usize,
        /// Slotmap's maximum live-entry limit (`2^32 - 2` for reserve operations,
        /// `2^32 - 3` for `with_capacity` since one slot is reserved as a sentinel)
        limit: usize,
    },
    /// An internal capacity computation overflowed `usize`.
    Overflow,
    /// The process-wide `region_id` counter has been exhausted. Only ever
    /// returned by `Region::try_new`/`try_with_capacity` (constructors mint a
    /// new region_id); `Region::try_reserve` on an existing `Region` never
    /// produces this variant, since it does not mint a new region_id.
    RegionIdExhausted(RegionIdExhaustedError),
}

impl core::fmt::Display for TryReserveError {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        match self {
            // Deliberately method-agnostic: this variant is returned by both
            // `try_with_capacity` and `try_reserve`. Their infallible wrappers
            // (`with_capacity`/`reserve`) prefix the method name themselves
            // when panicking, so this text must not bake in either name.
            Self::CapacityExceeded { requested, limit } => {
                write!(f, "capacity {} exceeds slotmap limit {}", requested, limit)
            }
            Self::Overflow => f.write_str("capacity overflow"),
            Self::RegionIdExhausted(inner) => inner.fmt(f),
        }
    }
}

impl core::error::Error for TryReserveError {
    fn source(&self) -> Option<&(dyn core::error::Error + 'static)> {
        match self {
            Self::RegionIdExhausted(inner) => Some(inner),
            _ => None,
        }
    }
}

impl From<RegionIdExhaustedError> for TryReserveError {
    fn from(err: RegionIdExhaustedError) -> Self {
        Self::RegionIdExhausted(err)
    }
}

/// Attempts to mint a unique `region_id` from the given atomic counter.
///
/// # Returns
///
/// - `Ok(NonZeroUsize)` — the newly minted region_id
/// - `Err(RegionIdExhaustedError)` — the counter has been exhausted (transitioned
///   to the permanent sentinel 0)
///
/// # Exhaustion semantics
///
/// This function uses `fetch_update` to ensure atomic exhaustion semantics:
/// - If the current value is 0: immediately returns an error (already exhausted)
/// - If the current value is `usize::MAX`: returns `MAX` (the last valid ID) and
///   transitions the counter to 0 (permanent exhausted sentinel)
/// - Otherwise: returns the current value and increments by 1
///
/// Once the counter transitions to 0, it will never transition back to a positive
/// value — all future calls will fail with `RegionIdExhaustedError`. This ensures
/// that no region_id is ever reused, even after exhaustion.
#[inline]
fn try_mint_region_id(counter: &AtomicUsize) -> Result<NonZeroUsize, RegionIdExhaustedError> {
    use core::sync::atomic::Ordering;

    match counter.fetch_update(Ordering::Relaxed, Ordering::Relaxed, |current| {
        if current == 0 {
            // Already exhausted: stay at 0 forever
            None
        } else if current == usize::MAX {
            // Last valid ID is MAX; transition to exhausted sentinel
            Some(0)
        } else {
            // Normal case: increment
            Some(current + 1)
        }
    }) {
        // Unreachable in practice: the closure above only ever returns
        // `Some(0)` when the *previous* value was `usize::MAX` (never 0
        // itself), so `fetch_update`'s `Ok(previous)` can never be `Ok(0)`.
        // Kept as a defensive match arm, not a reachable path.
        Ok(0) => Err(RegionIdExhaustedError),
        Ok(value) => match NonZeroUsize::new(value) {
            Some(nz) => Ok(nz),
            None => Err(RegionIdExhaustedError),
        },
        Err(_) => Err(RegionIdExhaustedError),
    }
}

/// Test-only forwarder exposing [`try_mint_region_id`] to integration tests
/// under `tests/`, which — unlike unit tests inside this module — can only
/// see items re-exported from the crate root. Not part of the public API;
/// `#[doc(hidden)]` keeps it out of rendered docs (see the "doc-hidden
/// test-only forwarders" convention in this repo's `CLAUDE.md`). Takes an
/// explicit `&AtomicUsize` rather than reaching for the real
/// `NEXT_REGION_ID` static so boundary/exhaustion tests can drive a local
/// counter without mutating process-wide state shared with other tests.
#[doc(hidden)]
pub fn dbg_try_mint_region_id(
    counter: &AtomicUsize,
) -> Result<NonZeroUsize, RegionIdExhaustedError> {
    try_mint_region_id(counter)
}

/// A handle-addressed store of `T`.
///
/// A thin typed membrane over `slotmap::SlotMap<slotmap::DefaultKey, T>`.
/// `SlotMap` keeps values in a contiguous slot array resolved by a single
/// indirection (the lookup/churn axis it was benchmarked to win; see
/// <https://github.com/PHPCraftdream/sefer-alloc/blob/main/docs/BENCHMARKS.md>), but it leaves tombstone holes after removals — it is
/// NOT always-compact, and iteration walks the slot array skipping holes
/// (~30 % slower than a `DenseSlotMap`, which packs live values for dense
/// iteration). Every operation delegates to `slotmap` while exposing only typed
/// [`Handle<T>`] values (raw `DefaultKey`s never escape as usable values
/// through the API — Debug output renders the underlying key for diagnostics
/// only, it cannot be turned back into a functioning handle through this crate's
/// public surface). Individual lookup and
/// removal are `O(1)`; insertion is amortized `O(1)` (may reallocate the slot
/// array on growth); iteration and [`clear`](Self::clear) are linear in the
/// slot-array length; [`reserve`](Self::reserve) may reallocate.
///
/// ## Invariants upheld
///
#[doc = include_str!("invariants.md")]
///
/// `region_id` is minted from a process-wide counter (`NEXT_REGION_ID`,
/// `AtomicUsize`) that is incremented once per `Region::new`/`with_capacity`
/// call and never reused. Once the counter is exhausted -- at the
/// `2^{pointer_width}`-th `Region` construction attempt (when it would wrap
/// from `usize::MAX` to 0), it transitions to a permanent exhausted state (0)
/// and all future `Region` constructions panic. No region_id is ever reused,
/// even after exhaustion — the value 0 is reserved as a sentinel that never
/// transitions back to a positive value. See the `# Panics` sections on
/// [`new`](Self::new) and [`with_capacity`](Self::with_capacity). On a
/// 64-bit host this is a theoretical guard only. On a **32-bit host**
/// (e.g. `thumbv7em-none-eabi`, `i686-*`) the bound is `2^32` (about 4.29
/// billion), which is *reachable*, not just theoretical, for a long-lived
/// 32-bit server or embedded process that mints a fresh `Region` per
/// request/session over its lifetime rather than reusing one — the same
/// honest register as the I2/I3 generation-wrap disclosure below, just a
/// much larger and process-lifetime-scoped count rather than a per-slot
/// reuse count.
///
/// ## Generation saturation
///
/// `slotmap::DefaultKey` uses a 32-bit generation counter stored alongside each
/// slot. The exact encoding (odd = occupied, even = vacant), the LIFO freelist
/// behavior, and the measured "~12 seconds" bound for `2^31 - 1` insert/remove
/// cycles on a hot slot are **implementation details of the resolved
/// slotmap 1.1.1 snapshot** — slotmap 1.x reserves the right to change these.
///
/// In the current version: `SlotMap::insert` sets the low bit on reuse
/// (`version | 1`); `SlotMap::remove` advances it past that with
/// `version.wrapping_add(1)` (odd -> even). So one full occupy/free cycle of a
/// slot advances its generation by 2, and after approximately `2^31` such cycles
/// the generation wraps around to its starting value, and a sufficiently stale
/// handle may then resolve to (or remove) a different live value that now
/// occupies the same slot.
///
/// This is a **logic/aliasing issue, not memory unsafety** — `slotmap` guarantees
/// that its internal data structure never becomes corrupt, even when a handle wraps.
/// The worst case for reaching wrap quickly is a hot single-slot churn pattern
/// (repeatedly inserting and removing at the same slot index while nothing else
/// is live). This was empirically confirmed on slotmap 1.1.1: a tight insert/remove
/// loop on one slot for `2^31 - 1` cycles took ~12 seconds on one development
/// machine in release mode; treat this as an order-of-magnitude sense for that
/// version, not a guaranteed bound for all slotmap 1.x.
///
/// Applications that need a stronger guarantee (e.g. to reuse handles without
/// ever risking alias) must add their own wrapper layer that tracks generation
/// wrap on a hot slot; cross-instance confusion is already handled by I7 and
/// needs no wrapper.
pub struct Region<T> {
    region_id: NonZeroUsize,
    inner: slotmap::SlotMap<slotmap::DefaultKey, T>,
}

impl<T> Region<T> {
    /// Checks if a handle belongs to this region (I7). Returns `Some(key)` if it does,
    /// `None` otherwise.
    #[inline]
    fn owned_key(&self, handle: Handle<T>) -> Option<slotmap::DefaultKey> {
        (handle.region_id == self.region_id).then_some(handle.key)
    }

    /// Creates an empty region that allocates nothing until first use.
    ///
    /// # Errors
    ///
    /// Returns `Err(TryReserveError::RegionIdExhausted(...))` if the process-wide
    /// `region_id` counter has been exhausted — i.e. this would be the
    /// `2^{pointer_width}`-th `Region` construction attempt (via `try_new`/`try_with_capacity`)
    /// in this process. Once the counter is exhausted, **all** future `Region`
    /// constructions in this process will fail, and no region_id is ever reused.
    /// See the I7 doc block above for the exhaustion bound and why it is reachable,
    /// not just theoretical, on a 32-bit host.
    pub fn try_new() -> Result<Self, TryReserveError> {
        let region_id = try_mint_region_id(&NEXT_REGION_ID)?;
        Ok(Self {
            region_id,
            inner: slotmap::SlotMap::new(),
        })
    }

    /// Creates an empty region that allocates nothing until first use.
    ///
    /// # Panics
    ///
    /// Panics if the process-wide `region_id` counter has been exhausted —
    /// i.e. this would be the `2^{pointer_width}`-th `Region` construction attempt
    /// (via `new`/`with_capacity`/`Default`) in this process. Once the counter
    /// is exhausted, **all** future `Region` constructions in this process will
    /// panic, and no region_id is ever reused. See the I7 doc block above for
    /// the exhaustion bound and why it is reachable, not just theoretical, on
    /// a 32-bit host.
    #[must_use]
    pub fn new() -> Self {
        Self::try_new().unwrap_or_else(|e| panic!("Region::new: {e}"))
    }

    /// Creates an empty region with space pre-reserved for `capacity` entries.
    ///
    /// # Errors
    ///
    /// - Returns `Err(TryReserveError::CapacityExceeded { .. })` if `capacity > 2^32 - 3`
    ///   (slotmap's maximum live-entry limit is `2^32 - 2`; reserving for sentinel gives `2^32 - 3`)
    ///   — this is the guard that fires for any out-of-domain `capacity`, on both 32-bit
    ///   and 64-bit hosts; on 64-bit this is a theoretical guard only (realistic workloads
    ///   never approach this limit), but on a 32-bit host it is reachable.
    /// - Returns `Err(TryReserveError::Overflow)` if an internal capacity computation
    ///   overflowed `usize` (defense-in-depth, not currently reachable in practice).
    /// - Returns `Err(TryReserveError::RegionIdExhausted(...))` if the process-wide
    ///   `region_id` counter has been exhausted — see [`try_new`](Self::try_new)'s
    ///   `# Errors` section and the I7 doc block above. Once the counter is exhausted,
    ///   **all** future `Region` constructions in this process will fail, and no region_id
    ///   is ever reused.
    ///
    /// # Note on allocation failure
    ///
    /// As with any `Vec`-backed container, allocation failure for a capacity whose slot array
    /// would exceed `isize::MAX` bytes (roughly `usize::MAX / size_of::<Slot<T>>()`) aborts
    /// rather than returning an error — this is not a recoverable error in standard Rust's
    /// memory model.
    pub fn try_with_capacity(capacity: usize) -> Result<Self, TryReserveError> {
        // Reject capacity that would overflow slotmap's limit: max live entries is 2^32 - 2.
        // With one sentinel slot, the maximum reserve is 2^32 - 3.
        if capacity > SLOTMAP_MAX_RESERVE {
            return Err(TryReserveError::CapacityExceeded {
                requested: capacity,
                limit: SLOTMAP_MAX_RESERVE,
            });
        }
        // Tripwire: confirmed unreachable on both 32- and 64-bit targets
        // (see `tests/coverage_gaps.rs`). Stays so a future slotmap change can't
        // silently reintroduce overflow.
        debug_assert!(capacity.checked_add(1).is_some());
        let region_id = try_mint_region_id(&NEXT_REGION_ID)?;
        Ok(Self {
            region_id,
            inner: slotmap::SlotMap::with_capacity(capacity),
        })
    }

    /// Creates an empty region with space pre-reserved for `capacity` entries.
    ///
    /// # Panics
    ///
    /// Panics if `capacity > 2^32 - 3` (slotmap's maximum live-entry limit is
    /// `2^32 - 2`; reserving for sentinel gives `2^32 - 3`) — this is the
    /// guard that actually fires for any out-of-domain `capacity`, on both
    /// 32-bit and 64-bit hosts; on 64-bit this is a theoretical guard only
    /// (realistic workloads never approach this limit), but on a 32-bit host
    /// it is reachable. Also panics (as any `Vec`-backed container does) for
    /// any `capacity` whose slot array would exceed `isize::MAX` bytes —
    /// roughly `usize::MAX / size_of::<Slot<T>>()`; allocation failure beyond
    /// that aborts rather than panicking. Also panics if the process-wide
    /// `region_id` counter has been exhausted — see [`new`](Self::new)'s
    /// `# Panics` section and the I7 doc block above. Once the counter is
    /// exhausted, **all** future `Region` constructions in this process will
    /// panic, and no region_id is ever reused.
    #[must_use]
    pub fn with_capacity(capacity: usize) -> Self {
        Self::try_with_capacity(capacity).unwrap_or_else(|e| panic!("Region::with_capacity: {e}"))
    }

    /// Number of live values (I4).
    #[must_use]
    pub fn len(&self) -> usize {
        self.inner.len()
    }

    /// Whether the region holds no live values (I4).
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.inner.is_empty()
    }

    /// Current value-storage capacity, in entries.
    ///
    /// Note: the underlying `slotmap` provides no shrink/compact operation of any kind.
    /// Capacity — and therefore per-sweep iteration cost — is permanently bounded BELOW
    /// by the historical high-water mark of live entries. The only way to reclaim that
    /// cost is to build a fresh `Region` and re-insert (which invalidates every
    /// outstanding handle from the old one).
    #[must_use]
    pub fn capacity(&self) -> usize {
        self.inner.capacity()
    }

    /// Reserves capacity for at least `additional` more insertions.
    ///
    /// Does nothing if the backing store already has room. After a churn that
    /// removes entries, the freed slots live on the free list, so re-inserting
    /// reuses existing capacity and does not grow unboundedly (the backing
    /// stays bounded by the high-water mark of live entries). Delegates to
    /// `slotmap`'s `reserve`; may allocate more than asked to avoid frequent
    /// reallocations.
    ///
    /// # Errors
    ///
    /// - Returns `Err(TryReserveError::Overflow)` if `len() + additional` would overflow `usize`.
    /// - Returns `Err(TryReserveError::CapacityExceeded { .. })` if `len() + additional > 2^32 - 2`
    ///   (slotmap's maximum live-entry limit).
    ///
    /// # Note on allocation failure
    ///
    /// As with any `Vec`-backed container, allocation failure for a capacity whose slot array
    /// would exceed `isize::MAX` bytes (roughly `usize::MAX / size_of::<Slot<T>>()`) aborts
    /// rather than returning an error — this is not a recoverable error in standard Rust's
    /// memory model.
    pub fn try_reserve(&mut self, additional: usize) -> Result<(), TryReserveError> {
        let target = self
            .inner
            .len()
            .checked_add(additional)
            .ok_or(TryReserveError::Overflow)?;
        if target > SLOTMAP_MAX_LIVE {
            return Err(TryReserveError::CapacityExceeded {
                requested: target,
                limit: SLOTMAP_MAX_LIVE,
            });
        }
        self.inner.reserve(additional);
        Ok(())
    }

    /// Reserves capacity for at least `additional` more insertions.
    ///
    /// Does nothing if the backing store already has room. After a churn that
    /// removes entries, the freed slots live on the free list, so re-inserting
    /// reuses existing capacity and does not grow unboundedly (the backing
    /// stays bounded by the high-water mark of live entries). Delegates to
    /// `slotmap`'s `reserve`; may allocate more than asked to avoid frequent
    /// reallocations.
    ///
    /// # Panics
    ///
    /// Panics if `len() + additional` overflows `usize`, in both debug and
    /// release builds — checked up front, before delegating to `slotmap`.
    /// Panics if `len() + additional > 2^32 - 2` (slotmap's maximum live-entry limit).
    /// Additionally panics (as any `Vec`-backed container does) for any
    /// `len() + additional` whose slot array would exceed `isize::MAX` bytes
    /// — roughly `usize::MAX / size_of::<Slot<T>>()`; allocation failure
    /// beyond that aborts rather than panicking.
    pub fn reserve(&mut self, additional: usize) {
        if let Err(e) = self.try_reserve(additional) {
            panic!("Region::reserve: {e}");
        }
    }

    /// Inserts `value`, returning a fresh handle that resolves to it (I1).
    ///
    /// # Panics
    ///
    /// Panics if the backing `slotmap` is full (2^32 - 2 live entries).
    #[must_use]
    pub fn insert(&mut self, value: T) -> Handle<T> {
        Handle::from_key_and_region(self.region_id, self.inner.insert(value))
    }

    /// Borrows the value for `handle`, or `None` if the handle is stale or
    /// removed (I1, I2, I3).
    #[must_use]
    pub fn get(&self, handle: Handle<T>) -> Option<&T> {
        self.inner.get(self.owned_key(handle)?)
    }

    /// Mutably borrows the value for `handle`, or `None` if stale/removed.
    #[must_use]
    pub fn get_mut(&mut self, handle: Handle<T>) -> Option<&mut T> {
        self.inner.get_mut(self.owned_key(handle)?)
    }

    /// Whether `handle` currently resolves to a live value.
    #[must_use]
    pub fn contains(&self, handle: Handle<T>) -> bool {
        self.owned_key(handle)
            .map(|key| self.inner.contains_key(key))
            .unwrap_or(false)
    }

    /// Removes and returns the value for `handle`, or `None` if it is already
    /// stale/removed. After this, `handle` resolves to `None` for roughly
    /// `2^31` reuse cycles of that slot (I2 — see the struct-level doc for
    /// the generation-wrap caveat).
    pub fn remove(&mut self, handle: Handle<T>) -> Option<T> {
        self.inner.remove(self.owned_key(handle)?)
    }

    /// Iterates the live values. The order is unspecified and changes as
    /// elements are removed. Walks the underlying `SlotMap`'s slot array,
    /// skipping tombstone holes — so this is NOT cache-dense over live values
    /// (a `DenseSlotMap`-backed store would be); see
    /// <https://github.com/PHPCraftdream/sefer-alloc/blob/main/docs/BENCHMARKS.md>.
    ///
    /// Note: iteration cost is proportional to the slot-array length, not to
    /// the live-value count. Since the underlying `slotmap` provides no shrink
    /// operation, the slot-array length is permanently bounded below by the
    /// historical high-water mark of live entries — a post-churn region with
    /// many holes pays iteration cost proportional to that high-water mark,
    /// even if few values remain live. See `capacity()`'s documentation for
    /// the full permanence semantics.
    ///
    /// The returned iterator implements `ExactSizeIterator`, `FusedIterator`,
    /// and `Clone`.
    #[must_use]
    pub fn iter(&self) -> Iter<'_, T> {
        Iter {
            inner: self.inner.values(),
        }
    }

    /// Mutably iterates the live values (same non-dense order caveat as
    /// [`iter`](Self::iter)).
    ///
    /// The returned iterator implements `ExactSizeIterator` and `FusedIterator`.
    #[must_use]
    pub fn iter_mut(&mut self) -> IterMut<'_, T> {
        IterMut {
            inner: self.inner.values_mut(),
        }
    }

    /// Removes every value, invalidating all outstanding handles, while
    /// retaining allocated capacity. The region is reusable afterwards.
    ///
    /// Note: `clear` does NOT shrink the underlying slot array; the capacity
    /// remains at the historical high-water mark of live entries. See
    /// `capacity()`'s documentation for the full permanence semantics.
    ///
    /// If a value's `Drop` impl panics mid-`clear`, the clear is partial:
    /// the region stays fully consistent and reusable after unwinding, but
    /// the exact set of survivors depends on the underlying `slotmap` version's
    /// unwind cleanup (slotmap 1.x reserves the right to change this). What is
    /// guaranteed is that: (1) no value is dropped twice, (2) no value is leaked
    /// by the region itself (caller-side `mem::forget` of removed values is
    /// outside this guarantee), and (3) the region's internal accounting remains
    /// correct. See `tests/clear_partial_under_panic.rs`, which documents what
    /// the CURRENT slotmap version actually does -- an observation of the
    /// present dependency, not a stable contract this crate promises.
    pub fn clear(&mut self) {
        self.inner.clear();
    }
}

impl<T> Default for Region<T> {
    /// # Panics
    ///
    /// Panics under the same condition as [`Region::new`] (process-wide
    /// `region_id` counter exhaustion) — this delegates to `new`.
    fn default() -> Self {
        Self::new()
    }
}

/// Note: the `region_id` field shown by this impl is minted from a
/// process-wide counter and is therefore NOT stable across separate runs or
/// processes (its value depends on how many other `Region`/`SyncRegion`
/// instances the process happened to construct first) — do not rely on it in
/// snapshot/golden-output tests.
impl<T> core::fmt::Debug for Region<T> {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        f.debug_struct("Region")
            .field("region_id", &self.region_id)
            .field("len", &self.len())
            .field("capacity", &self.capacity())
            .finish()
    }
}

// Note: consuming `IntoIterator for Region<T>` is not currently implemented.
// This is not a technical impossibility — a wrapper could yield just `T`,
// dropping the key internally — but has not been requested.
// Iteration by reference (`&Region<T>` and `&mut Region<T>`) is provided below.

impl<'a, T> IntoIterator for &'a Region<T> {
    type Item = &'a T;
    type IntoIter = Iter<'a, T>;

    fn into_iter(self) -> Self::IntoIter {
        self.iter()
    }
}

impl<'a, T> IntoIterator for &'a mut Region<T> {
    type Item = &'a mut T;
    type IntoIter = IterMut<'a, T>;

    fn into_iter(self) -> Self::IntoIter {
        self.iter_mut()
    }
}

/// Iterator over the live values in a [`Region<T>`], returned by
/// [`Region::iter`] and `IntoIterator for &Region<T>`.
///
/// A thin wrapper over `slotmap`'s own values iterator — kept as a distinct
/// named type (rather than re-exporting `slotmap`'s type directly) so this
/// crate's public API surface never names a `slotmap` type, matching the
/// rest of this crate's encapsulation of its backing store.
pub struct Iter<'a, T> {
    inner: slotmap::basic::Values<'a, slotmap::DefaultKey, T>,
}

impl<'a, T> Iterator for Iter<'a, T> {
    type Item = &'a T;

    fn next(&mut self) -> Option<Self::Item> {
        self.inner.next()
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        self.inner.size_hint()
    }
}

impl<T> ExactSizeIterator for Iter<'_, T> {
    fn len(&self) -> usize {
        self.inner.len()
    }
}

impl<T> core::iter::FusedIterator for Iter<'_, T> {}

impl<T> Clone for Iter<'_, T> {
    fn clone(&self) -> Self {
        Self {
            inner: self.inner.clone(),
        }
    }
}

impl<T> core::fmt::Debug for Iter<'_, T> {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        f.debug_struct("Iter").field("len", &self.len()).finish()
    }
}

/// Mutable iterator over the live values in a [`Region<T>`], returned by
/// [`Region::iter_mut`] and `IntoIterator for &mut Region<T>`.
///
/// Same encapsulation rationale as [`Iter`] — not `Clone` (a mutable
/// iterator cannot be duplicated without aliasing `&mut` references).
pub struct IterMut<'a, T> {
    inner: slotmap::basic::ValuesMut<'a, slotmap::DefaultKey, T>,
}

impl<'a, T> Iterator for IterMut<'a, T> {
    type Item = &'a mut T;

    fn next(&mut self) -> Option<Self::Item> {
        self.inner.next()
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        self.inner.size_hint()
    }
}

impl<T> ExactSizeIterator for IterMut<'_, T> {
    fn len(&self) -> usize {
        self.inner.len()
    }
}

impl<T> core::iter::FusedIterator for IterMut<'_, T> {}

impl<T> core::fmt::Debug for IterMut<'_, T> {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        f.debug_struct("IterMut").field("len", &self.len()).finish()
    }
}