gep 0.1.0

`gep`, a better pointer arithmetic library.
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
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
//! Nullable raw pointer type.

use core::fmt;
use core::mem;
use core::mem::MaybeUninit;
use core::ptr;

use crate::offset;
use crate::offset::Offset;
use crate::NonNull;

/// A nullable raw pointer.
///
/// This type is intended as an improved version of `*mut T`, which provides
/// clearer methods for common operations on raw pointers.
///
/// Unlike Rust's raw pointers, this pointer type does not track mutability
/// (which is not deeply useful book-keeping on raw pointers).
///
/// ```
/// # use gep::*;
/// # #[derive(Default, PartialEq, Debug, Clone)]
/// struct Foo {
///   first: i32,
///   second: u64,
/// }
///
/// let data = vec![Foo::default(); 100];
/// let ptr = Ptr::from(data.as_ptr());
/// assert!(!ptr.is_null() && ptr.is_aligned());
///
/// unsafe {
///   ptr.at(42).write_at(gep::field!(Foo.first), -1);
///   ptr.at(42).write_at(gep::field!(Foo.second), 42);
/// }
///
/// assert_eq!(data[42], Foo { first: -1, second: 42 });
/// ```
///
/// # Unsized Types
///
/// Currently, `T: !Sized` is poorly supported (due to lack of good support on
/// `*mut T` itself). In particular, `Ptr<[T]>` should be separated into a
/// `Ptr<T>` and a `usize`, since there is no supported way to get the length
/// out.
#[repr(transparent)]
pub struct Ptr<T: ?Sized> {
  p: *mut T,
}

impl<T: ?Sized> PartialEq<Ptr<T>> for Ptr<T> {
  fn eq(&self, other: &Ptr<T>) -> bool {
    self.p == other.p
  }
}

impl<T: ?Sized> PartialEq<NonNull<T>> for Ptr<T> {
  fn eq(&self, other: &NonNull<T>) -> bool {
    self.p == other.to_raw()
  }
}

impl<T: ?Sized> Eq for Ptr<T> {}

impl<T: ?Sized> Clone for Ptr<T> {
  fn clone(&self) -> Self {
    *self
  }
}

impl<T: ?Sized> Copy for Ptr<T> {}

impl<T: ?Sized> fmt::Debug for Ptr<T> {
  fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
    fmt::Debug::fmt(&self.p, f)
  }
}

impl<T: ?Sized> fmt::Pointer for Ptr<T> {
  fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
    fmt::Pointer::fmt(&self.p, f)
  }
}

impl<T: ?Sized> From<&T> for Ptr<T> {
  fn from(value: &T) -> Self {
    Self::new(value as *const T as *mut T)
  }
}

impl<T: ?Sized> From<&mut T> for Ptr<T> {
  fn from(value: &mut T) -> Self {
    Self::new(value)
  }
}

impl<T: ?Sized> From<*const T> for Ptr<T> {
  fn from(value: *const T) -> Self {
    Self::new(value as *mut T)
  }
}

impl<T: ?Sized> From<*mut T> for Ptr<T> {
  fn from(value: *mut T) -> Self {
    Self::new(value)
  }
}

impl<T: ?Sized> From<ptr::NonNull<T>> for Ptr<T> {
  fn from(value: ptr::NonNull<T>) -> Self {
    Self::new(value.as_ptr())
  }
}

impl<T: ?Sized> From<NonNull<T>> for Ptr<T> {
  fn from(value: NonNull<T>) -> Self {
    Self::new(value.to_raw())
  }
}

impl<T: ?Sized> From<Ptr<T>> for *const T {
  fn from(value: Ptr<T>) -> Self {
    value.to_raw()
  }
}

impl<T: ?Sized> From<Ptr<T>> for *mut T {
  fn from(value: Ptr<T>) -> Self {
    value.to_raw()
  }
}

impl<T: ?Sized> Ptr<T> {
  /// Constructs a new `Ptr` from a raw pointer or reference.
  pub const fn new(ptr: *mut T) -> Self {
    Ptr { p: ptr }
  }

  /// Constructs a new `Ptr` from a reference.
  ///
  /// # Safety
  ///
  /// This function is safe, but `Ptr`s created with it cannot be written
  /// through.
  pub const fn new_from_ref(ptr: &T) -> Self {
    Ptr {
      p: ptr as *const T as *mut T,
    }
  }

  /// Checks whether this pointer is null.
  ///
  /// ```
  /// # use gep::*;
  /// let x = 1997;
  /// assert!(!Ptr::from(&x).is_null());
  /// assert!(Ptr::<i32>::null().is_null());
  /// ```
  pub const fn is_null(self) -> bool {
    // <*const T>::is_null is not const yet for weird corner-case reasons. Miri
    // accepts this as a valid way to check for null, so at the very least
    // Hyrum's law is on our side. :D
    unsafe { mem::transmute::<*mut T, Option<NonNull<T>>>(self.p) }.is_none()
  }

  /// Extracts the underlying raw pointer.
  ///
  /// ```
  /// # use gep::*;
  /// # use std::ptr;
  /// let x = 1997;
  /// let p = Ptr::from(&x);
  /// assert!(ptr::eq(p.to_raw(), &x));
  /// ```
  pub const fn to_raw(self) -> *mut T {
    self.p
  }

  /// Returns this pointer's address.
  ///
  /// This operation discards provenance information, and any pointer created
  /// from this address value will be invalid.
  ///
  /// Compare [`<*mut T>::addr()`](https://doc.rust-lang.org/std/primitive.pointer.html#method.addr-1).
  pub fn addr(self) -> usize {
    self.p as *mut u8 as usize
  }

  /// Exposes this pointer's address.
  ///
  /// This operation discards provenance information, but allows a pointer to be
  /// reconstituted later with [`Ptr::from_exposed_addr()`].
  ///
  /// Compare [`<*mut T>::expose_addr()`](https://doc.rust-lang.org/std/primitive.pointer.html#method.expose_addr-1).
  pub fn expose_addr(self) -> usize {
    self.p as *mut u8 as usize
  }

  /// Converts this pointer into a [`NonNull`] pointer; returns `None` if this
  /// pointer is null.
  ///
  /// ```
  /// # use gep::*;
  /// let x = 1997;
  /// assert_eq!(
  ///   Ptr::from(&x).to_non_null(),
  ///   Some(NonNull::from(&x)),
  /// );
  ///
  /// assert!(Ptr::<i32>::null().to_non_null().is_none());
  /// ```
  pub const fn to_non_null(self) -> Option<NonNull<T>> {
    if self.is_null() {
      return None;
    }
    unsafe { Some(self.to_non_null_unchecked()) }
  }

  /// Converts this non-null pointer into a [`NonNull`] pointer without
  /// checking.
  ///
  /// ```
  /// # use gep::*;
  /// let x = 1997;
  /// let p = Ptr::from(&x);
  ///
  /// assert!(!p.is_null());
  /// assert_eq!(
  ///   unsafe { Ptr::from(&x).to_non_null_unchecked() },
  ///   NonNull::from(&x),
  /// );
  /// ```
  ///
  /// # Safety
  ///
  /// [`Ptr::is_null()`] must return false for this pointer.
  pub const unsafe fn to_non_null_unchecked(self) -> NonNull<T> {
    debug_assert!(
      !self.is_null(),
      "attempted to convert a null pointer to NonNull<T>"
    );
    NonNull::new(ptr::NonNull::new_unchecked(self.p))
  }

  /// Casts this pointer to another type.
  ///
  /// Note that `U: Sized`, because creating a pointer to an unsized type
  /// requires extra metadata (and no stable API exists to do so yet).
  ///
  /// ```
  /// # use gep::*;
  /// let x = -1;
  /// let y = unsafe {
  ///   Ptr::from(&x).cast::<u32>().read()
  /// };
  ///
  /// assert_eq!(y, !0);
  /// ```
  pub const fn cast<U>(self) -> Ptr<U> {
    Ptr {
      p: self.p as *mut U,
    }
  }

  /// Dereferences this pointer, producing a reference.
  ///
  /// This function takes `&self`, to avoid creating an unbound lifetime in the
  /// common case.
  ///
  /// ```
  /// # use gep::*;
  /// let x = -1;
  /// let p = Ptr::from(&x).cast::<u32>();
  ///
  /// assert_eq!(unsafe { p.deref() }, &!0);
  /// ```
  ///
  /// # Safety
  ///
  /// This operation is equivalent to dereferencing a raw pointer. The following
  /// is an incomplete list of requirements:
  ///
  /// `self` must be non-null, well-aligned, and refer to memory appropriately
  /// initialized for `T`; also, it must not create a reference that aliases any
  /// active `&mut U`.
  pub const unsafe fn deref(&self) -> &T {
    self.deref_unbound()
  }

  /// Dereferences this pointer, producing a reference.
  ///
  /// Unlike [`Ptr::deref()`], this function can produce unbound references.
  ///
  /// # Safety
  ///
  /// This operation is equivalent to dereferencing a raw pointer. The following
  /// is an incomplete list of requirements:
  ///
  /// `self` must be non-null, well-aligned, and refer to memory appropriately
  /// initialized for `T`; also, it must not create a reference that aliases any
  /// active `&mut U`.
  pub const unsafe fn deref_unbound<'a>(self) -> &'a T {
    if cfg!(debug_assertions) {
      // <*mut T>::is_null is not const-stable yet, so we cheat with a little
      // transmute.
      match mem::transmute::<*mut T, Option<&T>>(self.p) {
        Some(r) => return r,
        None => panic!("attempted to deref null pointer"),
      }
    }

    &*(self.p as *const T)
  }

  /// Dereferences this pointer, producing a mutable reference.
  ///
  /// This function takes `&mut self`, to avoid creating an unbound lifetime in
  /// the common case.
  ///
  /// ```
  /// # use gep::*;
  /// let mut x = 0;
  /// let p = Ptr::from(&mut x).cast::<u32>();
  /// *unsafe { p.deref_mut() } = !0;
  ///
  /// assert_eq!(x, -1);
  /// ```
  ///
  /// # Safety
  ///
  /// This operation is equivalent to dereferencing a raw pointer. The following
  /// is an incomplete list of requirements:
  ///
  /// `self` must be non-null, well-aligned, and refer to memory appropriately
  /// initialized for `T`; also, it must not create a reference that aliases any
  /// active `&mut U`.
  #[allow(clippy::mut_from_ref)]
  pub unsafe fn deref_mut(&self) -> &mut T {
    self.deref_mut_unbound()
  }

  /// Dereferences this pointer, producing a reference.
  ///
  /// Unlike [`Ptr::deref_mut()`], this function can produce unbound references.
  ///
  /// # Safety
  ///
  /// This operation is equivalent to dereferencing a raw pointer. The following
  /// is an incomplete list of requirements:
  ///
  /// `self` must be non-null, well-aligned, and refer to memory appropriately
  /// initialized for `T`; also, it must not create a reference that aliases any
  /// active `&mut U`.
  pub unsafe fn deref_mut_unbound<'a>(self) -> &'a mut T {
    debug_assert!(!self.is_null(), "attempted to deref null pointer");
    &mut *self.p
  }

  /// Destroys the pointed-to value; equivalent to [`std::ptr::drop_in_place()`].
  ///
  /// ```
  /// # use gep::*;
  /// # use std::cell::Cell;
  /// struct Handle<'a>(&'a Cell<i32>);
  /// impl<'a> Handle<'a> {
  ///   fn new(c: &'a Cell<i32>) -> Self {
  ///     c.set(c.get() + 1);
  ///     Self(c)
  ///   }
  /// }
  ///
  /// impl Drop for Handle<'_> {
  ///   fn drop(&mut self) {
  ///     self.0.set(self.0.get() - 1);
  ///   }
  /// }
  ///
  /// let counter = Cell::new(0);
  /// let mut handle = Handle::new(&counter);
  ///
  /// assert_eq!(counter.get(), 1);
  ///
  /// let p = Ptr::from(&mut handle);
  /// unsafe {
  ///   p.destroy();
  ///   p.write(Handle::new(&counter));
  /// }
  ///
  /// assert_eq!(counter.get(), 1);
  /// ```
  ///
  /// Tip: given a `Ptr<T>`, you can destroy an array of `n` of them with
  /// `ptr.to_slice(n).destroy()`.
  ///
  /// # Safety
  ///
  /// This operation is equivalent to dereferencing a raw pointer. The following
  /// is an incomplete list of requirements:
  ///
  /// `self` must be valid for reading and writing, properly aligned, and properly
  /// initialized. See [`std::ptr::drop_in_place()`] for more information.
  pub unsafe fn destroy(self) {
    debug_assert!(!self.is_null(), "attempted to destroy null pointer");
    self.p.drop_in_place()
  }
}

impl<T> Ptr<T> {
  /// Creates a new null pointer.
  pub const fn null() -> Self {
    Ptr::invalid(0)
  }

  /// Creates a new, non-null, dangling pointer.
  ///
  /// ```
  /// # use gep::*;
  /// assert_ne!(Ptr::<i32>::null(), Ptr::<i32>::dangling());
  /// ```
  pub const fn dangling() -> Self {
    Ptr::invalid(mem::align_of::<T>())
  }

  /// Creates a pointer with the given address and the "invalid" provenance.
  ///
  /// Compare [`std::ptr::invalid()`].
  pub const fn invalid(addr: usize) -> Self {
    Ptr { p: addr as *mut T }
  }

  /// Reconstitutes a pointer using an address previously constructed with
  /// [`Ptr::expose_addr()`].
  ///
  /// ```
  /// # use gep::*;
  /// const KEY: usize = 0xf0f0f0f0f0f0f0f0;
  ///
  /// let x = 1997;
  /// let p = Ptr::from(&x);
  /// let addr = p.expose_addr() ^ KEY;
  ///
  /// let q = Ptr::<i32>::from_exposed_addr(addr ^ KEY);
  /// assert_eq!(p, q);
  /// ```
  ///
  /// Compare [`std::ptr::from_exposed_addr()`].
  pub const fn from_exposed_addr(addr: usize) -> Self {
    Ptr { p: addr as *mut T }
  }

  /// Creates a new pointer with the given address using the provenance
  /// information from `self`.
  ///
  /// Compare [`<*mut T>::with_addr()`](https://doc.rust-lang.org/std/primitive.pointer.html#method.with_addr-1).
  pub fn with_addr(self, addr: usize) -> Ptr<T> {
    let off = (addr as isize).wrapping_sub(self.addr() as isize);
    unsafe { self.at(offset::NotInBounds(offset::ByteOffset(off))) }
  }

  /// Transforms the address of `self` while preserving its provenance.
  ///
  /// This is a convenience wrapper over [`Ptr::with_addr()`].
  pub fn map_addr(self, f: impl FnOnce(usize) -> usize) -> Self {
    self.with_addr(f(self.addr()))
  }

  /// Returns whether this pointer is appropriately aligned for its type.
  ///
  /// ```
  /// # use gep::*;
  /// # use gep::offset::ByteOffset;
  /// let x = 1997;
  /// let p = Ptr::from(&x);
  /// let q = unsafe { p.at(ByteOffset(1)) };
  ///
  /// assert!(p.is_aligned());
  /// assert!(!q.is_aligned());
  /// ```
  pub fn is_aligned(self) -> bool {
    self.misalignment() == 0
  }

  /// Like `is_aligned`, but usable inside of assertions in `const` code.
  pub(crate) const fn is_aligned_const_for_assertions(self) -> bool {
    crate::is_aligned_const_for_assertions(self.p)
  }

  /// Returns this pointer's "address misalignment"; i.e., its address modulo
  /// the pointee type's alignment.
  ///
  /// ```
  /// # use gep::*;
  /// # use gep::offset::ByteOffset;
  /// let x = 1997;
  /// let p = Ptr::from(&x);
  /// let q = unsafe { p.at(ByteOffset(1)) };
  ///
  /// assert_eq!(p.misalignment(), 0);
  /// assert_eq!(q.misalignment(), 1);
  /// ```
  pub fn misalignment(self) -> usize {
    let mask = mem::align_of::<T>() - 1;
    self.addr() & mask
  }

  /// Makes this pointer well-aligned by rounding its address down.
  ///
  /// ```
  /// # use gep::*;
  /// # use gep::offset::ByteOffset;
  /// let x = [1997, 42];
  /// let p = Ptr::from(&x).element();
  /// let q = unsafe { p.at(ByteOffset(1)) };
  ///
  /// unsafe {
  ///   assert_eq!(p.align_down().read(), 1997);
  ///   assert_eq!(q.align_down().read(), 1997);
  /// }
  /// ```
  pub fn align_down(self) -> Self {
    let mask = mem::align_of::<T>() - 1;
    self.map_addr(|a| a & !mask)
  }

  /// Makes this pointer well-aligned by rounding its address up.
  ///
  /// ```
  /// # use gep::*;
  /// # use gep::offset::ByteOffset;
  /// let x = [1997, 42];
  /// let p = Ptr::from(&x).element();
  /// let q = unsafe { p.at(ByteOffset(1)) };
  ///
  /// unsafe {
  ///   assert_eq!(p.align_up().read(), 1997);
  ///   assert_eq!(q.align_up().read(), 42);
  /// }
  /// ```
  pub fn align_up(self) -> Self {
    let mask = mem::align_of::<T>() - 1;
    self.map_addr(|a| (a + mask) & !mask)
  }

  /// Performs pointer arithmetic to produce a new pointer.
  ///
  /// If an integer `i` (of any type, possibly signed) is passed in as the
  /// offset, it will compute the address of the `i`th `T` relative to this
  /// pointer. To obtain a pointer to the `i`th byte instead, wrap the integer
  /// in an [`offset::ByteOffset`].
  ///
  /// ```
  /// # use gep::*;
  /// # use gep::offset::ByteOffset;
  /// let x = [1997, 42];
  /// let p = Ptr::from(&x).element();
  ///
  /// unsafe {
  ///   assert_eq!(p.at(1).read(), 42);
  ///   assert_eq!(p.at(ByteOffset(4)).read(), 42);
  /// }
  /// ```
  ///
  /// If an [`offset::Field`] is passed in as the offset, it will compute the
  /// address of that field within the pointer. If it's a negative field
  /// offset, it will treat this as a pointer to a field and compute the address
  /// of the outer struct. Note that such negative field offsets are only valid
  /// if this pointer was created from a reference to the top of the outer
  /// struct originally.
  ///
  /// ```
  /// # use gep::*;
  /// struct Foo {
  ///   a: u8,
  ///   bar: Bar,
  /// }
  ///
  /// struct Bar(i32, i32, i32);
  ///
  /// let x = Foo { a: 5, bar: Bar(-1, -2, -3) };
  /// let p = Ptr::from(&x);
  ///
  /// unsafe {
  ///   assert_eq!(p.at(field!(Foo.bar.2)).read(), -3);
  /// }
  /// ```
  ///
  /// [`offset::NotInBounds`] can be used to disable out-of-bounds undefined
  /// behavior for this function, but the resulting pointer may be invalid for
  /// reads and writes.
  ///
  /// ```
  /// # use gep::*;
  /// # use gep::offset::NotInBounds;
  /// let x = [1997, 42];
  /// let p = Ptr::from(&x).element();
  ///
  /// unsafe {
  ///   let invalid = p.at(NotInBounds(2000));
  ///   // invalid.read()  // UB!
  ///   let valid_again = invalid.at(NotInBounds(-1999));
  ///   assert_eq!(valid_again.read(), 42);
  /// }
  /// ```
  ///
  /// # Safety
  ///
  /// See the safety doc for [`offset::Measurement::apply()`].
  pub unsafe fn at<U>(self, offset: impl Offset<T, U>) -> Ptr<U> {
    self.at_raw(offset.measure()).cast::<U>()
  }

  /// Performs pointer arithmetic to produce a new pointer.
  ///
  /// Unlike [`Ptr::at()`], this function is `const`, but takes an explicit
  /// [`offset::Measurement`] value.
  ///
  ///
  /// ```
  /// # use gep::*;
  /// # use gep::offset::Measurement;
  /// let x = [1997, 42];
  /// let p = Ptr::from(&x).element();
  ///
  /// let m = Measurement::by_bytes(4);
  /// unsafe {
  ///   assert_eq!(p.at_raw(m).read(), 42);
  /// }
  /// ```
  ///
  /// # Safety
  ///
  /// See the safety doc for [`offset::Measurement::apply()`].
  pub const unsafe fn at_raw(self, offset: offset::Measurement) -> Ptr<T> {
    Ptr {
      p: offset.apply(self.p),
    }
  }

  /// Casts this pointer to a `Ptr<[T]>`, with the given length.
  pub fn to_slice(self, len: usize) -> Ptr<[T]> {
    Ptr {
      p: ptr::slice_from_raw_parts_mut(self.p, len),
    }
  }

  /// Casts this pointer to a `Ptr<MaybeUninit<T>>`.
  pub const fn to_uninit(self) -> Ptr<MaybeUninit<T>> {
    self.cast()
  }

  /// Reads the value at `self`.
  ///
  /// This does not "move"; it effectively performs a bytewise copy of the value
  /// behind the pointer.
  ///
  /// ```
  /// # use gep::*;
  /// let x = 1997;
  /// let p = Ptr::from(&x);
  ///
  /// assert_eq!(unsafe { p.read() }, 1997);
  /// ```
  ///
  /// # Safety
  ///
  /// This operation is equivalent to dereferencing a raw pointer. The following
  /// is an incomplete list of requirements:
  ///
  /// `self` must be valid for reads, properly aligned, and properly
  /// initialized. See [`std::ptr::read()`] for more information.
  pub unsafe fn read(self) -> T {
    debug_assert!(!self.is_null(), "attempted to read null pointer");
    debug_assert!(
      self.is_aligned_const_for_assertions(),
      "attempted to read misaligned pointer {self:?}"
    );

    self.p.read()
  }

  /// Reads the value at `self.at(idx)`.
  ///
  /// This is a convenience function for reading at a specified offset.
  ///
  /// ```
  /// # use gep::*;
  /// struct Player {
  ///   name: String,
  ///   health: f32,
  /// }
  ///
  /// let x = Player { name: "Gep".into(), health: 20.0 };
  /// let p = Ptr::from(&x);
  ///
  /// unsafe {
  ///   assert_eq!(p.read_at(field!(Player.health)), 20.0);
  /// }
  /// ```
  ///
  /// # Safety
  ///
  /// The requirements of [`Ptr::at()`] must be satisfied, as well as those
  /// for [`Ptr::read()`] (on the result of the pointer arithmetic operation).
  pub unsafe fn read_at<U>(self, idx: impl Offset<T, U>) -> U {
    self.at(idx).read()
  }

  /// Writes to the value at `self`.
  ///
  /// Note: does not run the destructor of `self`'s pointee before overwriting
  /// it.
  ///
  /// ```
  /// # use gep::*;
  /// let mut x = 1997;
  /// let p = Ptr::from(&mut x);
  ///
  /// unsafe { p.write(42); }
  /// assert_eq!(x, 42);
  /// ```
  ///
  /// # Safety
  ///
  /// This operation is equivalent to dereferencing a raw pointer. The following
  /// is an incomplete list of requirements:
  ///
  /// `self` must be valid for writes, properly aligned, and properly
  /// initialized. See [`std::ptr::write()`] for more information.
  pub unsafe fn write(self, val: T) {
    debug_assert!(!self.is_null(), "attempted to write to null pointer");
    debug_assert!(
      self.is_aligned_const_for_assertions(),
      "attempted to write to misaligned pointer {self:?}"
    );

    self.p.write(val)
  }

  /// Writes to the value at `self.at(idx)`.
  ///
  /// This is a convenience function for writing at a specified offset.
  ///
  /// ```
  /// # use gep::*;
  /// struct Player {
  ///   name: String,
  ///   health: f32,
  /// }
  ///
  /// let mut x = Player { name: "Gep".into(), health: 20.0 };
  /// let p = Ptr::from(&mut x);
  ///
  /// unsafe {
  ///   p.write_at(field!(Player.health), 30.0);
  /// }
  /// assert_eq!(x.health, 30.0);
  /// ```
  ///
  /// # Safety
  ///
  /// The requirements of [`Ptr::at()`] must be satisfied, as well as those
  /// for [`Ptr::write()`] (on the result of the pointer arithmetic operation).
  pub unsafe fn write_at<U>(self, idx: impl Offset<T, U>, val: U) {
    self.at(idx).write(val)
  }

  /// Zeroes the value at `self`.
  ///
  /// ```
  /// # use gep::*;
  /// let mut x = 1997;
  /// let p = Ptr::from(&mut x);
  ///
  /// unsafe { p.clear_to_zero(); }
  /// assert_eq!(x, 0);
  /// ```
  ///
  /// # Safety
  ///
  /// The requirements of [`Ptr::write()`] must be met. Also, if the pointee is
  /// not a type for which zero is a valid representation (e.g., a reference),
  /// the pointer will be invalid for reads.
  pub unsafe fn clear_to_zero(self) {
    self.p.write_bytes(0, 1)
  }

  /// Zeroes the value at `self`.
  ///
  /// This is a convenience function for zeroing at a specified offset.
  ///
  /// ```
  /// # use gep::*;
  /// struct Player {
  ///   name: String,
  ///   health: f32,
  /// }
  ///
  /// let mut x = Player { name: "Gep".into(), health: 20.0 };
  /// let p = Ptr::from(&mut x);
  ///
  /// unsafe {
  ///   p.clear_to_zero_at(field!(Player.health));
  /// }
  /// assert_eq!(x.health, 0.0);
  /// ```
  ///
  /// # Safety
  ///
  /// The requirements of [`Ptr::at()`] must be satisfied, as well as those
  /// for [`Ptr::clear_to_zero()`] (on the result of the pointer arithmetic operation).
  pub unsafe fn clear_to_zero_at<U>(self, idx: impl Offset<T, U>) {
    self.at(idx).clear_to_zero()
  }

  /// Destroys the value at `self.at(idx)`.
  ///
  /// This is a convenience function for destroying at a specified offset.
  ///
  /// # Safety
  ///
  /// The requirements of [`Ptr::at()`] must be satisfied, as well as those
  /// for [`Ptr::destroy()`] (on the result of the pointer arithmetic operation).
  pub unsafe fn destroy_at<U>(self, idx: impl Offset<T, U>) {
    self.at(idx).destroy()
  }

  /// Replaces the value at `self`.
  ///
  /// This is like [`Ptr::read()`], but it writes a new value after reading.
  ///
  /// ```
  /// # use gep::*;
  /// let mut x = 1997;
  /// let p = Ptr::from(&mut x);
  ///
  /// unsafe {
  ///   assert_eq!(p.replace(42), 1997);
  /// }
  /// assert_eq!(x, 42);
  /// ```
  ///
  /// # Safety
  ///
  /// The requirements of [`Ptr::read()`] and [`Ptr::write()`] must be satisfied.
  pub unsafe fn replace(self, val: T) -> T {
    let x = self.read();
    self.write(val);
    x
  }

  /// Replaces the value at `self`.
  ///
  /// This is a convenience function for replacing at a specified offset.
  ///
  /// ```
  /// # use gep::*;
  /// struct Player {
  ///   name: String,
  ///   health: f32,
  /// }
  ///
  /// let mut x = Player { name: "Gep".into(), health: 20.0 };
  /// let p = Ptr::from(&mut x);
  ///
  /// unsafe {
  ///   assert_eq!(p.replace_at(field!(Player.health), 30.0), 20.0);
  /// }
  /// assert_eq!(x.health, 30.0);
  /// ```
  ///
  /// # Safety
  ///
  /// The requirements of [`Ptr::at()`] must be satisfied, as well as those
  /// [`Ptr::read()`] and [`Ptr::write()`] (on the result of the pointer
  /// arithmetic operation).
  pub unsafe fn replace_at<U>(self, idx: impl Offset<T, U>, val: U) -> U {
    self.at(idx).replace(val)
  }

  /// Dereferences `self.at(idx)`, producing a reference.
  ///
  /// This is a convenience function for deref-ing at a specified offset.
  ///
  /// ```
  /// # use gep::*;
  /// struct Player {
  ///   name: String,
  ///   health: f32,
  /// }
  ///
  /// let mut x = Player { name: "Gep".into(), health: 20.0 };
  /// let p = Ptr::from(&mut x);
  ///
  /// let name = unsafe { p.deref_at(field!(Player.name)) };
  /// assert_eq!(name, "Gep");
  /// ```
  ///
  /// # Safety
  ///
  /// The requirements of [`Ptr::at()`] must be satisfied, as well as those
  /// [`Ptr::deref()`] (on the result of the pointer arithmetic operation).
  pub unsafe fn deref_at<U>(&self, idx: impl Offset<T, U>) -> &U {
    self.at(idx).deref_unbound()
  }

  /// Dereferences `self.at(idx)`, producing a reference.
  ///
  /// This is a convenience function for deref-ing at a specified offset; this
  /// is the unbound version of [`Ptr::deref_at()`].
  ///
  /// # Safety
  ///
  /// The requirements of [`Ptr::at()`] must be satisfied, as well as those
  /// [`Ptr::deref()`] (on the result of the pointer arithmetic operation).
  pub unsafe fn deref_unbound_at<'a, U>(self, idx: impl Offset<T, U>) -> &'a U {
    self.at(idx).deref_unbound()
  }

  /// Dereferences `self.at(idx)`, producing a mutable reference.
  ///
  /// This is a convenience function for deref-ing at a specified offset.
  ///
  /// ```
  /// # use gep::*;
  /// struct Player {
  ///   name: String,
  ///   health: f32,
  /// }
  ///
  /// let mut x = Player { name: "Gep".into(), health: 20.0 };
  /// let p = Ptr::from(&mut x);
  ///
  /// {
  ///   let name = unsafe { p.deref_mut_at(field!(Player.name)) };
  ///   name.clear();
  ///   name.push_str("Jim");
  /// }
  ///
  /// assert_eq!(x.name, "Jim")
  /// ```
  ///
  /// # Safety
  ///
  /// The requirements of [`Ptr::at()`] must be satisfied, as well as those
  /// [`Ptr::deref_mut()`] (on the result of the pointer arithmetic operation).
  #[allow(clippy::mut_from_ref)]
  pub unsafe fn deref_mut_at<U>(&self, idx: impl Offset<T, U>) -> &mut U {
    self.at(idx).deref_mut_unbound()
  }

  /// Dereferences `self.at(idx)`, producing a mutable reference.
  ///
  /// This is a convenience function for deref-ing at a specified offset; this
  /// is the unbound version of [`Ptr::deref_mut_at()`].
  ///
  /// # Safety
  ///
  /// The requirements of [`Ptr::at()`] must be satisfied, as well as those
  /// [`Ptr::deref_mut()`] (on the result of the pointer arithmetic operation).
  pub unsafe fn deref_mut_unbound_at<'a, U>(
    self,
    idx: impl Offset<T, U>,
  ) -> &'a mut U {
    self.at(idx).deref_mut_unbound()
  }
}

impl<T> Ptr<[T]> {
  /// Flattens this pointer into a pointer to the first element.
  ///
  /// ```
  /// # use gep::*;
  /// let x = [1, 2, 3];
  /// let p = Ptr::from(&x[..]);
  ///
  /// assert_eq!(p.element(), Ptr::from(&x[0]));
  /// ```
  pub const fn element(self) -> Ptr<T> {
    self.cast::<T>()
  }
}

impl<T, const N: usize> Ptr<[T; N]> {
  /// Flattens this pointer into a pointer to the first element.
  ///
  /// ```
  /// # use gep::*;
  /// let x = [1, 2, 3];
  /// let p = Ptr::from(&x);
  ///
  /// assert_eq!(p.element(), Ptr::from(&x[0]));
  /// ```
  pub const fn element(self) -> Ptr<T> {
    self.cast::<T>()
  }
}