nearest 0.4.5

Self-relative pointer library for region-based allocation
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
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
use core::{fmt, mem, ops::Deref};

use crate::{
  Emit, Flat,
  buf::Buf,
  emitter::{Emitter, Pos},
  session::{Brand, Session},
};

/// An owning, contiguous byte buffer whose root value `T` starts at byte 0.
///
/// All [`Near`](crate::Near) and [`NearList`](crate::NearList) pointers
/// inside the region are self-relative offsets, so `Clone` is a plain memcpy
/// — no fixup needed.
///
/// # Memory layout
///
/// ```text
/// ┌──────────────────────────────────────────────┐
/// │ Root T (starts at byte 0)                    │
/// │  ├── scalar fields (inline)                  │
/// │  ├── Near<U> → i32 offset ───────┐           │
/// │  └── NearList<V> → i32 + u32 ──┐ │           │
/// │                                │ │           │
/// │ [padding]                      │ │           │
/// │ U value ◄──────────────────────│─┘           │
/// │ [padding]                      │             │
/// │ Segment<V> header ◄────────────┘             │
/// │ V values...                                  │
/// └──────────────────────────────────────────────┘
/// ```
///
/// # Soundness
///
/// **Ownership**: A `Region` exclusively owns its buffer. There is no
/// shared mutable state. `Clone` performs a byte-for-byte copy of the buffer;
/// all self-relative offsets remain valid because they are position-independent.
///
/// **Alignment**: The buffer base is aligned to `max(align_of::<T>(), 8)`.
/// Every sub-allocation is padded to the target type's alignment. A
/// compile-time assertion ensures no type exceeds the buffer's base alignment.
///
/// **Mutation safety**: All mutations go through [`Session`](crate::Session),
/// which holds `&mut Region`. The branded `'id` lifetime on [`Ref`](crate::Ref)
/// prevents refs from escaping or crossing sessions.
///
/// **`Send`/`Sync`**: Implemented with `T: Send + Sync` bounds as
/// defense-in-depth. All `Flat` types are `Send + Sync` by construction
/// (no heap pointers, no interior mutability), but the bounds let the
/// compiler verify this.
#[cfg(feature = "alloc")]
#[must_use]
pub struct Region<T: Flat, B: Buf = crate::buf::AlignedBuf<T>> {
  buf: B,
  _type: core::marker::PhantomData<T>,
}

/// See the `#[cfg(feature = "alloc")]` variant above for full documentation.
#[cfg(not(feature = "alloc"))]
#[must_use]
pub struct Region<T: Flat, B: Buf> {
  buf: B,
  _type: core::marker::PhantomData<T>,
}

#[cfg(feature = "alloc")]
impl<T: Flat> Region<T> {
  /// Construct a region from a builder using the default [`AlignedBuf`](crate::AlignedBuf).
  ///
  /// The builder emits the root `T` (and any nested data) into a fresh
  /// emitter, producing an immutable `Region`.
  ///
  /// # Examples
  ///
  /// ```
  /// use nearest::{Flat, NearList, Region, empty, list};
  ///
  /// #[derive(Flat, Debug)]
  /// struct Node {
  ///   id: u32,
  ///   children: NearList<u32>,
  /// }
  ///
  /// // Build with the derive-generated `Node::make(id, children)` builder.
  /// let region = Region::new(Node::make(1, list([10u32, 20, 30])));
  /// assert_eq!(region.id, 1);
  /// assert_eq!(region.children.len(), 3);
  ///
  /// // Build with an empty list.
  /// let region = Region::new(Node::make(2, empty()));
  /// assert_eq!(region.children.len(), 0);
  /// ```
  pub fn new(builder: impl Emit<T>) -> Self {
    Self::new_in(builder)
  }

  /// Construct a region with a pre-allocated buffer of at least `capacity` bytes.
  ///
  /// Avoids repeated reallocations when the final size is approximately known.
  pub fn with_capacity(capacity: u32, builder: impl Emit<T>) -> Self {
    Self::with_capacity_in(capacity, builder)
  }
}

impl<T: Flat, B: Buf> Region<T, B> {
  /// Construct a region from a builder using an explicit buffer type `B`.
  ///
  /// For the default heap-backed buffer, use [`Region::new`] instead.
  pub fn new_in(builder: impl Emit<T>) -> Self {
    let mut em = Emitter::<T, B>::new();
    builder.emit(&mut em);
    em.finish()
  }

  /// Construct a region with a pre-allocated buffer of at least `capacity` bytes.
  pub fn with_capacity_in(capacity: u32, builder: impl Emit<T>) -> Self {
    let mut em = Emitter::<T, B>::with_capacity(capacity);
    builder.emit(&mut em);
    em.finish()
  }

  /// Create a region from a buffer.
  ///
  /// # Safety
  ///
  /// The buffer must contain a valid representation of `T` at byte 0 and
  /// all transitively reachable data must be valid. Constructing a region
  /// from an invalid buffer causes UB on `Deref`.
  pub(crate) unsafe fn from_buf(buf: B) -> Self {
    debug_assert!(buf.len() as usize >= mem::size_of::<T>(), "buffer too small for root type");
    Self { buf, _type: core::marker::PhantomData }
  }

  /// Open a branded session. [`Ref`](crate::Ref)s created inside the closure
  /// cannot escape or be used with a different session — **compile-time safety,
  /// zero runtime cost**.
  ///
  /// # Examples
  ///
  /// ```
  /// use nearest::{Flat, NearList, Region, empty, list};
  ///
  /// #[derive(Flat, Debug)]
  /// struct Node {
  ///   id: u32,
  ///   children: NearList<u32>,
  /// }
  ///
  /// let mut region = Region::new(Node::make(1, list([10u32, 20])));
  ///
  /// // Read and mutate inside a session.
  /// region.session(|s| {
  ///   let root = s.root();
  ///   assert_eq!(s.at(root).id, 1);
  ///
  ///   let children = s.nav(root, |n| &n.children);
  ///   s.splice_list(children, [99u32]);
  /// });
  ///
  /// assert_eq!(region.children.len(), 1);
  /// assert_eq!(region.children[0], 99);
  /// ```
  pub fn session<R>(&mut self, f: impl for<'id> FnOnce(&mut Session<'id, '_, T, B>) -> R) -> R {
    self.buf.expose_provenance();
    let brand = Brand::new();
    let mut session = Session::new(self, brand);
    f(&mut session)
  }

  /// Bulk-copy another region's bytes into this region, returning the position
  /// of the grafted root.
  ///
  /// All self-relative pointers within the grafted data remain valid because
  /// the entire source is copied as a contiguous block. The graft position is
  /// aligned to the source region's maximum internal alignment so that all
  /// transitively referenced data maintains correct alignment.
  pub(crate) fn graft_internal<U: Flat, B2: Buf>(&mut self, src: &Region<U, B2>) -> Pos {
    // All types within `src` have alignment ≤ BUF_ALIGN (enforced by
    // Buf::alloc). Both regions share alignment ≥ 8, so aligning the graft
    // offset to B2::ALIGN preserves alignment for all data.
    self.buf.align_to(B2::ALIGN);
    let pos = Pos(self.buf.len());
    self.buf.extend_from_slice(src.buf.as_bytes());
    pos
  }

  /// Returns the total byte length of the region.
  ///
  /// # Examples
  ///
  /// ```
  /// use nearest::{Flat, NearList, Region, empty};
  ///
  /// #[derive(Flat)]
  /// struct Node { id: u32, items: NearList<u32> }
  ///
  /// let region = Region::new(Node::make(1, empty()));
  /// assert!(region.byte_len() >= core::mem::size_of::<Node>());
  /// ```
  #[must_use]
  pub fn byte_len(&self) -> usize {
    self.buf.len() as usize
  }

  /// Raw const pointer to the buffer (for Cursor reads).
  pub(crate) fn deref_raw(&self) -> *const u8 {
    self.buf.expose_provenance();
    self.buf.as_ptr()
  }

  /// Compact this region by re-emitting only reachable data.
  ///
  /// After mutations (e.g. [`splice_list`](Session::splice_list),
  /// [`push_front`](Session::push_front)), old targets of redirected
  /// [`Near`](crate::Near)/[`NearList`](crate::NearList) pointers become
  /// dead bytes. `trim` walks the root `T` and all transitively reachable
  /// data, emitting a fresh compact buffer via `Emit<T> for &T` deep-copy.
  ///
  /// # Examples
  ///
  /// ```
  /// use nearest::{Flat, NearList, Region, list};
  ///
  /// #[derive(Flat, Debug)]
  /// struct Node { items: NearList<u32> }
  ///
  /// let mut region = Region::new(Node::make(list([1u32, 2, 3])));
  /// let before = region.byte_len();
  ///
  /// // Mutation leaves dead bytes (old list data).
  /// region.session(|s| {
  ///   let items = s.nav(s.root(), |n| &n.items);
  ///   s.splice_list(items, [42u32]);
  /// });
  /// assert!(region.byte_len() > before);
  ///
  /// // Trim compacts the region.
  /// region.trim();
  /// assert!(region.byte_len() <= before);
  /// assert_eq!(region.items[0], 42);
  /// ```
  pub fn trim(&mut self) {
    let new_buf = {
      let root: &T = self;
      let mut em = Emitter::<T, B>::with_capacity(self.buf.len());
      Emit::<T>::emit(root, &mut em);
      em.into_buf()
    };
    self.buf = new_buf;
  }

  // --- pub(crate) buffer mutation methods for Session/Patch ---

  /// Ensure at least `additional` bytes of spare capacity.
  pub(crate) fn reserve_internal(&mut self, additional: u32) {
    self.buf.reserve(additional);
  }

  /// Allocate aligned space for one `U`, returning its position.
  pub(crate) fn alloc_internal<U: Flat>(&mut self) -> Pos {
    self.buf.alloc::<U>()
  }

  /// Write a [`Flat`] value at position `at`.
  ///
  /// # Safety
  ///
  /// `at` must have been allocated for `U` via `alloc_internal::<U>()`,
  /// ensuring correct alignment.
  pub(crate) unsafe fn write_flat_internal<U: Flat>(&mut self, at: Pos, val: U) {
    // SAFETY: Caller guarantees `at` was allocated for `U`.
    unsafe { crate::buf::write_flat(&mut self.buf, at, val) };
  }

  /// Patch a [`Near<U>`](crate::Near) at position `at` to point to `target`.
  ///
  /// # Safety
  ///
  /// `at` must point to a `Near<U>` field within a previously allocated
  /// value, and `target` must be a position allocated for `U`.
  pub(crate) unsafe fn patch_near_internal(&mut self, at: Pos, target: Pos) {
    // SAFETY: Caller guarantees `at` points to a `Near<U>` and `target`
    // was allocated for `U`.
    unsafe { crate::buf::patch_near(&mut self.buf, at, target) };
  }

  /// Patch a [`NearList<U>`](crate::NearList) header at position `at`.
  ///
  /// # Safety
  ///
  /// `at` must point to a `NearList<U>` field within a previously allocated
  /// value, and `target` must be a position of a `Segment<U>` (or
  /// `Pos::ZERO` when `len == 0`).
  pub(crate) unsafe fn patch_list_header_internal(&mut self, at: Pos, target: Pos, len: u32) {
    // SAFETY: Caller guarantees `at` points to a `NearList<U>` and `target`
    // is a valid segment position (or `Pos::ZERO` when `len == 0`).
    unsafe { crate::buf::patch_list_header(&mut self.buf, at, target, len) };
  }

  /// Allocate a segment header plus `count` contiguous values of type `U`.
  ///
  /// Returns the position of the segment header. The segment's `len` field
  /// is initialized to `count`; `next` is 0 (end of chain, from zero-fill).
  pub(crate) fn alloc_segment_internal<U: Flat>(&mut self, count: u32) -> Pos {
    crate::buf::alloc_segment::<U>(&mut self.buf, count)
  }

  /// Patch the `next` pointer of a segment at `seg_pos`.
  ///
  /// # Safety
  ///
  /// `seg_pos` must be a position of a previously allocated `Segment<T>`.
  pub(crate) unsafe fn patch_segment_next_internal(&mut self, seg_pos: Pos, next_seg_pos: Pos) {
    // SAFETY: Caller guarantees `seg_pos` is a previously allocated segment.
    unsafe { crate::buf::patch_segment_next(&mut self.buf, seg_pos, next_seg_pos) };
  }

  /// Copy raw bytes to position `at`.
  ///
  /// # Safety
  ///
  /// `src` must be valid for reading `len` bytes. `at` must be a valid
  /// position with at least `len` bytes available.
  pub(crate) unsafe fn write_bytes_internal(&mut self, at: Pos, src: *const u8, len: usize) {
    // SAFETY: Caller guarantees `src` is valid for `len` bytes and `at`
    // has at least `len` bytes available.
    unsafe { crate::buf::write_bytes(&mut self.buf, at, src, len) };
  }

  /// Return the raw byte contents of this region.
  ///
  /// The returned slice can be persisted (e.g. written to a file) and later
  /// restored via [`from_bytes`](Self::from_bytes).
  ///
  /// # Examples
  ///
  /// ```
  /// use nearest::{Flat, NearList, Region, empty, list};
  ///
  /// #[derive(Flat, Debug)]
  /// struct Node {
  ///   id: u32,
  ///   children: NearList<u32>,
  /// }
  ///
  /// let region = Region::new(Node::make(1, list([10u32, 20, 30])));
  /// let bytes = region.as_bytes();
  /// assert!(bytes.len() >= core::mem::size_of::<Node>());
  /// ```
  #[must_use]
  pub fn as_bytes(&self) -> &[u8] {
    self.buf.as_bytes()
  }

  /// Consume the region and return the underlying buffer.
  ///
  /// This is a zero-copy operation — it simply unwraps the inner buffer.
  /// The returned buffer can be passed to [`from_bytes`](Self::from_bytes)
  /// (via [`Buf::as_bytes`]) for reconstruction, or converted to bytes.
  ///
  /// # Examples
  ///
  /// ```
  /// use nearest::{Flat, NearList, Region, empty, list};
  ///
  /// #[derive(Flat, Debug)]
  /// struct Node {
  ///   id: u32,
  ///   children: NearList<u32>,
  /// }
  ///
  /// let region = Region::new(Node::make(1, list([10u32, 20, 30])));
  /// let buf = region.into_buf();
  /// ```
  pub fn into_buf(self) -> B {
    self.buf
  }

  /// Consume the region and return its contents as a `Vec<u8>`.
  ///
  /// The returned vector contains the same bytes as [`as_bytes`](Self::as_bytes).
  /// This is useful for APIs that need an owned byte buffer (e.g. I/O,
  /// network transmission, or storage). The bytes can later be restored
  /// via [`Region::from_bytes`].
  ///
  /// # Examples
  ///
  /// ```
  /// use nearest::{Flat, NearList, Region, list};
  ///
  /// #[derive(Flat, Debug)]
  /// struct Node {
  ///   id: u32,
  ///   children: NearList<u32>,
  /// }
  ///
  /// let region = Region::new(Node::make(1, list([10u32, 20, 30])));
  /// let bytes: Vec<u8> = region.into_vec();
  /// let restored: Region<Node> = Region::from_bytes(&bytes).unwrap();
  /// assert_eq!(restored.id, 1);
  /// assert_eq!(restored.children.len(), 3);
  /// ```
  #[cfg(feature = "alloc")]
  pub fn into_vec(self) -> alloc::vec::Vec<u8> {
    self.buf.as_bytes().to_vec()
  }

  /// Validate and reconstruct a region from raw bytes.
  ///
  /// Copies the bytes into an aligned buffer first, then runs
  /// [`T::validate`](Flat::validate) on the copy. This copy-then-validate
  /// order means the input is read only once (during the copy), and
  /// validation reads the cache-hot aligned buffer instead.
  ///
  /// # Errors
  ///
  /// Returns [`ValidateError`](crate::ValidateError) if the bytes do not
  /// form a valid representation of `T` and its transitively reachable data.
  ///
  /// # Examples
  ///
  /// Round-trip through bytes:
  ///
  /// ```
  /// use nearest::{Flat, NearList, Region, empty, list};
  ///
  /// #[derive(Flat, Debug)]
  /// struct Node {
  ///   id: u32,
  ///   children: NearList<u32>,
  /// }
  ///
  /// let original = Region::new(Node::make(1, list([10u32, 20, 30])));
  /// let bytes = original.as_bytes();
  /// let restored: Region<Node> = Region::from_bytes(bytes).unwrap();
  /// assert_eq!(restored.id, 1);
  /// assert_eq!(restored.children.len(), 3);
  /// ```
  ///
  /// Validation catches invalid data — here a `bool` field with value `2`:
  ///
  /// ```
  /// use nearest::{Flat, Near, Region, ValidateError, near};
  ///
  /// #[derive(Flat, Debug)]
  /// struct Flags {
  ///   active: bool,
  ///   label: Near<u32>,
  /// }
  ///
  /// let region = Region::new(Flags::make(true, near(42u32)));
  /// let mut bytes = region.as_bytes().to_vec();
  /// // Corrupt the bool — its offset is computed from the struct layout.
  /// let bool_offset = core::mem::offset_of!(Flags, active);
  /// bytes[bool_offset] = 2;
  /// assert!(matches!(
  ///   Region::<Flags>::from_bytes(&bytes),
  ///   Err(ValidateError::InvalidBool { .. })
  /// ));
  /// ```
  pub fn from_bytes(bytes: &[u8]) -> Result<Self, crate::ValidateError> {
    let mut buf = B::empty();
    buf.extend_from_slice(bytes);
    T::validate(0, buf.as_bytes())?;
    // SAFETY: `T::validate` just verified the buffer contents are valid.
    Ok(unsafe { Self::from_buf(buf) })
  }

  /// Reconstruct a region from raw bytes **without validation**.
  ///
  /// This is the unsafe fast path for deserialization. The bytes are copied
  /// into a fresh aligned buffer but **no validation** is performed — no
  /// bounds checks, no pointer validation, no discriminant checks.
  ///
  /// For a safe alternative that validates the buffer, use
  /// [`from_bytes`](Self::from_bytes).
  ///
  /// # Safety
  ///
  /// The caller must guarantee **all** of the following:
  ///
  /// - `bytes` was originally produced by [`as_bytes`](Self::as_bytes) on a
  ///   valid `Region<T>` (or is byte-for-byte identical to such output).
  /// - The buffer contains a valid representation of `T` at byte offset 0,
  ///   with correct size (`bytes.len() >= size_of::<T>()`).
  /// - All [`Near<U>`](crate::Near) self-relative offsets resolve to
  ///   in-bounds, correctly aligned addresses within the buffer, and the
  ///   target bytes form a valid `U`.
  /// - All [`NearList<U>`](crate::NearList) headers have in-bounds segment
  ///   chains with correct lengths, and every element is a valid `U`.
  /// - All enum discriminants are valid for their `#[repr]`.
  /// - All `bool` values are `0` or `1`.
  /// - No `Option<Near<T>>` contains a bit pattern that is neither `None`
  ///   nor a valid `Some(Near<T>)`.
  ///
  /// Violating any of these preconditions causes **undefined behavior** on
  /// subsequent reads through the region.
  ///
  /// # Examples
  ///
  /// ```
  /// use nearest::{Flat, NearList, Region, list};
  ///
  /// #[derive(Flat, Debug)]
  /// struct Node {
  ///   id: u32,
  ///   children: NearList<u32>,
  /// }
  ///
  /// let original = Region::new(Node::make(1, list([10u32, 20, 30])));
  /// let bytes = original.as_bytes();
  ///
  /// // SAFETY: `bytes` was produced by `as_bytes()` on a valid `Region<Node>`.
  /// let restored: Region<Node> = unsafe { Region::from_bytes_unchecked(bytes) };
  /// assert_eq!(restored.id, 1);
  /// assert_eq!(restored.children.len(), 3);
  /// ```
  pub unsafe fn from_bytes_unchecked(bytes: &[u8]) -> Self {
    let mut buf = B::empty();
    buf.extend_from_slice(bytes);
    // SAFETY: Caller guarantees the bytes form a valid region buffer for `T`.
    // The copy into `buf` provides the required alignment (see `Buf` trait).
    unsafe { Self::from_buf(buf) }
  }

  /// Reconstruct a region from a pre-existing buffer **without validation**.
  ///
  /// Unlike [`from_bytes_unchecked`](Self::from_bytes_unchecked), this takes
  /// an already-allocated buffer `B`, avoiding an extra copy when the caller
  /// already has an aligned buffer (e.g. memory-mapped I/O with a
  /// [`FixedBuf`](crate::FixedBuf)).
  ///
  /// # Safety
  ///
  /// The caller must guarantee **all** of the following:
  ///
  /// - `buf` contains a valid representation of `T` at byte offset 0,
  ///   with `buf.len() >= size_of::<T>()`.
  /// - The buffer base is aligned to at least `align_of::<T>()` (guaranteed
  ///   by the [`Buf`](crate::Buf) trait, but the *contents* must also be
  ///   valid).
  /// - All [`Near<U>`](crate::Near) self-relative offsets resolve to
  ///   in-bounds, correctly aligned addresses within the buffer, and the
  ///   target bytes form a valid `U`.
  /// - All [`NearList<U>`](crate::NearList) headers have in-bounds segment
  ///   chains with correct lengths, and every element is a valid `U`.
  /// - All enum discriminants are valid for their `#[repr]`.
  /// - All `bool` values are `0` or `1`.
  /// - No `Option<Near<T>>` contains a bit pattern that is neither `None`
  ///   nor a valid `Some(Near<T>)`.
  ///
  /// Violating any of these preconditions causes **undefined behavior** on
  /// subsequent reads through the region.
  ///
  /// # Examples
  ///
  /// ```
  /// use nearest::{Buf, Flat, NearList, Region, FixedBuf, list};
  ///
  /// #[derive(Flat, Debug)]
  /// struct Node {
  ///   id: u32,
  ///   children: NearList<u32>,
  /// }
  ///
  /// let original: Region<Node, FixedBuf<256>> =
  ///   Region::new_in(Node::make(1, list([10u32, 20, 30])));
  /// let bytes = original.as_bytes();
  ///
  /// let mut buf = FixedBuf::<256>::new();
  /// buf.extend_from_slice(bytes);
  ///
  /// // SAFETY: `buf` contains bytes from a valid `Region<Node>`.
  /// let restored: Region<Node, FixedBuf<256>> =
  ///   unsafe { Region::from_buf_unchecked(buf) };
  /// assert_eq!(restored.id, 1);
  /// assert_eq!(restored.children.len(), 3);
  /// ```
  pub unsafe fn from_buf_unchecked(buf: B) -> Self {
    // SAFETY: Caller guarantees the buffer contains a valid region for `T`.
    unsafe { Self::from_buf(buf) }
  }
}

impl<T: Flat, B: Buf> Deref for Region<T, B> {
  type Target = T;

  fn deref(&self) -> &T {
    self.buf.expose_provenance();
    // SAFETY: The buffer is aligned to `align_of::<T>()` and at least
    // `size_of::<T>()` bytes. The root `T` starts at byte 0.
    unsafe { &*self.buf.as_ptr().cast::<T>() }
  }
}

impl<T: Flat, B: Buf + Clone> Clone for Region<T, B> {
  fn clone(&self) -> Self {
    Self { buf: self.buf.clone(), _type: core::marker::PhantomData }
  }
}

impl<T: Flat + PartialEq, B: Buf> PartialEq for Region<T, B> {
  fn eq(&self, other: &Self) -> bool {
    **self == **other
  }
}

impl<T: Flat + Eq, B: Buf> Eq for Region<T, B> {}

impl<T: Flat + fmt::Debug, B: Buf> fmt::Debug for Region<T, B> {
  fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
    f.debug_struct("Region").field("root", &**self).finish()
  }
}

impl<T: Flat + fmt::Display, B: Buf> fmt::Display for Region<T, B> {
  fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
    fmt::Display::fmt(&**self, f)
  }
}

// SAFETY: Region owns its buffer exclusively via Buf which is Send+Sync.
// The `Send + Sync` bounds on `T` are defense-in-depth: all `Flat` types are
// `Send + Sync` by construction (no heap pointers, no interior mutability),
// but we add the bounds explicitly so the compiler checks this invariant.
unsafe impl<T: Flat + Send + Sync, B: Buf + Send> Send for Region<T, B> {}
// SAFETY: See above — Region owns its buffer exclusively.
unsafe impl<T: Flat + Send + Sync, B: Buf + Sync> Sync for Region<T, B> {}

impl<T: Flat, B: Buf> AsRef<[u8]> for Region<T, B> {
  fn as_ref(&self) -> &[u8] {
    self.as_bytes()
  }
}

#[cfg(feature = "alloc")]
impl<T: Flat, B: Buf> From<Region<T, B>> for alloc::vec::Vec<u8> {
  fn from(region: Region<T, B>) -> Self {
    region.into_vec()
  }
}

// ---------------------------------------------------------------------------
// serde support
// ---------------------------------------------------------------------------

#[cfg(feature = "serde")]
impl<T: Flat, B: Buf> serde::Serialize for Region<T, B> {
  fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
    serializer.serialize_bytes(self.as_bytes())
  }
}

#[cfg(feature = "serde")]
impl<'de, T: Flat, B: Buf> serde::Deserialize<'de> for Region<T, B> {
  fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
    struct RegionVisitor<T, B>(core::marker::PhantomData<(T, B)>);

    impl<'de, T: Flat, B: Buf> serde::de::Visitor<'de> for RegionVisitor<T, B> {
      type Value = Region<T, B>;

      fn expecting(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
        f.write_str("a valid nearest region byte buffer")
      }

      fn visit_bytes<E: serde::de::Error>(self, v: &[u8]) -> Result<Self::Value, E> {
        Region::from_bytes(v).map_err(E::custom)
      }

      fn visit_seq<A: serde::de::SeqAccess<'de>>(
        self,
        mut seq: A,
      ) -> Result<Self::Value, A::Error> {
        let mut bytes = alloc::vec::Vec::with_capacity(seq.size_hint().unwrap_or(0));
        while let Some(b) = seq.next_element::<u8>()? {
          bytes.push(b);
        }
        self.visit_byte_buf(bytes)
      }
    }

    deserializer.deserialize_byte_buf(RegionVisitor(core::marker::PhantomData))
  }
}