[go: up one dir, main page]

funty 3.0.0-rc1

Trait generalization over the primitive types
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
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
#![doc = include_str!("../doc/ptr.md")]

use core::{
	any,
	cmp,
	fmt,
	hash::{
		Hash,
		Hasher,
	},
	marker::PhantomData,
	mem,
	ptr::{
		self,
		NonNull,
	},
};

#[doc = include_str!("../doc/permission.md")]
pub trait Permission {
	/// The raw pointer type that drives memory accesses for this `Permission`.
	/// This is necessary because `*const T` and `*mut T` are different types,
	/// and tools such as Miri track how `*mut` pointers are created, and
	/// by using an associated type we can avoid improperly using a `*mut T`
	/// pointer inside a `Pointer<T, Shared>` that never had unique access
	/// permissions.
	type Ptr<T: ?Sized>: RawPtr<T>;

	/// The corresponding reference type.
	type Ref<'a, T: 'a + ?Sized>: RawRef<'a, T>;

	/// Either `"*const"` or `"*mut"`; used for debug printing.
	const DEBUG_PREFIX: &'static str;

	// These are utility functions that should not be called directly by public
	// consumers. They exist to provide specific behaviors that the `Pointer`
	// type needs, but cannot directly express.

	/// Casts the referent type of the pointer.
	///
	/// This can be used to cast a pointer-to-unsized to pointer-to-sized, but
	/// cannot be used to cast any pointer to pointer-to-unsized. Pointers to
	/// unsized types (currently only slices and trait objects) must be created
	/// through dedicated APIs which are not yet stabilized on the raw pointer
	/// types.
	#[doc(hidden)]
	fn cast<T: ?Sized, U>(ptr: Self::Ptr<T>) -> Self::Ptr<U>;

	/// Creates a raw `*const T` primitive.
	#[doc(hidden)]
	fn into_const<T: ?Sized>(ptr: Self::Ptr<T>) -> *const T;

	/// Attempts to create a raw `*mut T` primitive.
	///
	/// This is only allowed to succeed where `Self::Ptr<T>` is `*mut T`.
	#[doc(hidden)]
	fn try_into_mut<T: ?Sized>(ptr: Self::Ptr<T>) -> Option<*mut T>;

	/// Wraps a raw `*const T` primitive as the `Raw` associated type.
	#[doc(hidden)]
	fn from_const<T: ?Sized>(ptr: *const T) -> Self::Ptr<T>;

	/// Dereferences a pointer and produces a reference to the pointed-to value.
	///
	/// ## Safety
	///
	/// The pointer must be non-null and well-aligned for `T`, and the
	/// pointed-to location must outlive the conjured `'a` lifetime and not have
	/// any other outstanding references which violate the Rust
	/// many-shared-xor-one-mutable reference rule.
	#[doc(hidden)]
	unsafe fn ptr_to_ref<'a, T: 'a + ?Sized>(
		ptr: Self::Ptr<T>,
	) -> Self::Ref<'a, T>;

	/// Combines a base pointer and a length into a slice pointer.
	///
	/// ## Safety
	///
	/// The region `ptr[.. len]` must be within a single provenance region.
	#[doc(hidden)]
	unsafe fn ptr_to_slice<T: Sized>(
		ptr: Self::Ptr<T>,
		len: usize,
	) -> Self::Ptr<[T]>;

	/// Gets the raw address of a pointer.
	#[doc(hidden)]
	fn addr<T: ?Sized>(ptr: Self::Ptr<T>) -> usize;
}

/// Equivalent to `*const` pointers or `&` references.
#[derive(Clone, Copy, Debug, Default, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct Shared;

/// Equivalent to `*mut` pointers or `&mut` references.
#[derive(Clone, Copy, Debug, Default, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct Unique;

impl Permission for Shared {
	type Ptr<T: ?Sized> = *const T;
	type Ref<'a, T: 'a + ?Sized> = &'a T;

	const DEBUG_PREFIX: &'static str = "*const";

	fn cast<T: ?Sized, U>(ptr: *const T) -> *const U {
		ptr.cast::<U>()
	}

	fn into_const<T: ?Sized>(ptr: *const T) -> *const T {
		ptr
	}

	fn try_into_mut<T: ?Sized>(_: *const T) -> Option<*mut T> {
		None
	}

	fn from_const<T: ?Sized>(ptr: *const T) -> *const T {
		ptr
	}

	unsafe fn ptr_to_ref<'a, T: 'a + ?Sized>(ptr: *const T) -> &'a T {
		&*ptr
	}

	unsafe fn ptr_to_slice<T: Sized>(ptr: *const T, len: usize) -> *const [T] {
		ptr::slice_from_raw_parts(ptr, len)
	}

	fn addr<T: ?Sized>(ptr: *const T) -> usize {
		ptr.cast::<()>() as usize
	}
}

impl Permission for Unique {
	type Ptr<T: ?Sized> = *mut T;
	type Ref<'a, T: 'a + ?Sized> = &'a mut T;

	const DEBUG_PREFIX: &'static str = "*mut";

	fn cast<T: ?Sized, U>(ptr: *mut T) -> *mut U {
		ptr.cast::<U>()
	}

	fn into_const<T: ?Sized>(ptr: *mut T) -> *const T {
		ptr.cast_const()
	}

	fn try_into_mut<T: ?Sized>(ptr: *mut T) -> Option<*mut T> {
		Some(ptr)
	}

	fn from_const<T: ?Sized>(ptr: *const T) -> *mut T {
		ptr.cast_mut()
	}

	unsafe fn ptr_to_ref<'a, T: 'a + ?Sized>(ptr: *mut T) -> &'a mut T {
		&mut *ptr
	}

	unsafe fn ptr_to_slice<T: Sized>(ptr: *mut T, len: usize) -> *mut [T] {
		ptr::slice_from_raw_parts_mut(ptr, len)
	}

	fn addr<T: ?Sized>(ptr: *mut T) -> usize {
		ptr.cast::<()>() as usize
	}
}

impl<P> Permission for (Shared, P)
where P: Permission
{
	type Ptr<T: ?Sized> = *const T;
	type Ref<'a, T: 'a + ?Sized> = &'a T;

	const DEBUG_PREFIX: &'static str = Shared::DEBUG_PREFIX;

	fn cast<T: ?Sized, U>(ptr: *const T) -> *const U {
		ptr.cast::<U>()
	}

	fn into_const<T: ?Sized>(ptr: *const T) -> *const T {
		ptr
	}

	fn try_into_mut<T: ?Sized>(_: *const T) -> Option<*mut T> {
		None
	}

	fn from_const<T: ?Sized>(ptr: *const T) -> *const T {
		ptr
	}

	unsafe fn ptr_to_ref<'a, T: 'a + ?Sized>(ptr: *const T) -> &'a T {
		&*ptr
	}

	unsafe fn ptr_to_slice<T: Sized>(ptr: *const T, len: usize) -> *const [T] {
		ptr::slice_from_raw_parts(ptr, len)
	}

	fn addr<T: ?Sized>(ptr: *const T) -> usize {
		ptr.cast::<()>() as usize
	}
}

#[repr(transparent)]
#[doc = include_str!("../doc/pointers.md")]
pub struct Pointer<T, P>
where
	T: ?Sized,
	P: Permission,
{
	ptr: P::Ptr<T>,
}

impl<T> Pointer<T, Shared>
where T: ?Sized
{
	/// Produces a new `Pointer` from a raw `const` pointer.
	pub const fn new(ptr: *const T) -> Self {
		Self { ptr }
	}

	/// Produces the enclosed raw pointer.
	pub const fn into_inner(self) -> *const T {
		self.ptr
	}
}

impl<T> Pointer<T, Unique>
where T: ?Sized
{
	/// Produces a new `Pointer` from a raw `mut` pointer.
	pub const fn new(ptr: *mut T) -> Self {
		Self { ptr }
	}

	/// Produces the enclosed raw pointer.
	pub const fn into_inner(self) -> *mut T {
		self.ptr
	}

	/// Produces a unique reference to the pointed-to value.
	///
	/// ## Safety
	///
	/// This function requires the following:
	///
	/// - the `Pointer` is well-aligned for `T`.
	/// - the pointed-to location contains an initialized `T` value.
	/// - no other reference or `Reference` pointing to the location exists for
	///   the duration of the produced reference’s existence.
	/// - the pointed-to location exists for the full duration of the conjured
	///   `'a` lifetime.
	pub unsafe fn as_mut<'a>(self) -> Option<&'a mut T> {
		if self.is_null() {
			return None;
		}
		Some(&mut *self.ptr)
	}

	/// Runs the destructor on the pointed-to location.
	///
	/// ## Safety
	///
	/// The value at the pointed-to location must be currently initialized.
	pub unsafe fn drop_in_place(self) {
		self.ptr.drop_in_place();
	}
}

impl<T> Pointer<T, Unique>
where T: Sized
{
	/// Copies objects pointed to by `src` into the region pointed to by
	/// `self`.
	///
	/// ## Safety
	///
	/// - the memory region of `src[.. count]` must contain contiguous
	///   fully-initialized `T` values.
	/// - the memory region of `self[.. count]` must be within a single
	///   allocation.
	/// - the values stored in `src[.. count]` must not have their destructors
	///   run, as they are now alive in `self[.. count]`.
	pub unsafe fn copy_from<P: Permission>(
		self,
		src: Pointer<T, P>,
		count: usize,
	) {
		self.ptr.copy_from(
			<(Shared, P)>::into_const::<T>(src.cast_const().ptr),
			count,
		);
	}

	/// Same as `copy_from`, except that you guarantee that the memory regions
	/// `self[.. count]` and `src[.. count]` are fully disjoint.
	///
	/// ## Safety
	///
	/// The copying behavior from the source region to the self region is not
	/// specified. As such, the two regions **must not** overlap at all in the
	/// memory space.
	pub unsafe fn copy_from_nonoverlapping<P: Permission>(
		self,
		src: Pointer<T, P>,
		count: usize,
	) {
		self.ptr.copy_from_nonoverlapping(
			<(Shared, P)>::into_const::<T>(src.cast_const().ptr),
			count,
		);
	}

	/// Writes a new value into the pointed-to location.
	///
	/// The pointed-to value does not have its destructor run.
	///
	/// ## Safety
	///
	/// You must ensure that the pointed-to value is properly destroyed before
	/// overwriting it.
	pub unsafe fn write(self, value: T) {
		self.ptr.write(value);
	}

	/// Fills the memory region with a byte pattern for `count` *elements* (not
	/// bytes).
	///
	/// ## Safety
	///
	/// You must ensure that the values stored in `self[.. count]` are properly
	/// destroyed before calling this function, and that the byte pattern
	/// `[byte; mem::size_of::<T>()]` is a valid object representation for `T`
	/// values.
	pub unsafe fn write_bytes(self, byte: u8, count: usize) {
		self.ptr.write_bytes(byte, count);
	}

	/// Equivalent to `write`, with the additional guarantee that the *compiler*
	/// will not omit this store.
	///
	/// This store does not synchronize across threads, nor does it create a
	/// causal dependency with any other memory accesses in the current thread.
	/// Its only guarantee is that the compiler will emit a store instruction.
	///
	/// ## Safety
	///
	/// See `write`.
	pub unsafe fn write_volatile(self, value: T) {
		self.ptr.write_volatile(value);
	}

	/// Equivalent to `write`, except that it is tolerant of the address not
	/// being well-aligned for `T`.
	///
	/// ## Safety
	///
	/// See `write`.
	pub unsafe fn write_unaligned(self, value: T) {
		self.ptr.write_unaligned(value);
	}

	/// Exchanges the argument with the pointed-to value.
	///
	/// ## Safety
	///
	/// The pointed-to value must be properly initialized, and no other
	/// reference to it may exist when this function is called.
	pub unsafe fn replace(self, value: T) -> T {
		self.ptr.replace(value)
	}

	/// Exchanges the pointed-to values between this and another `Pointer`.
	///
	/// ## Safety
	///
	/// The pointed-to values must be properly initialized, and no other
	/// references to them may exist when this function is called.
	pub unsafe fn swap(self, with: Self) {
		self.ptr.swap(with.ptr);
	}
}

impl<T, P> Pointer<T, (Shared, P)>
where
	T: ?Sized,
	P: Permission,
{
	/// Removes the leading `Shared` from the permission stack.
	pub fn cast_unshared(self) -> Pointer<T, P> {
		Pointer {
			ptr: <P>::from_const(self.into_const_ptr()),
		}
	}
}

impl<T, P> Pointer<T, P>
where
	T: ?Sized,
	P: Permission,
{
	/// Constructs a `Pointer` from its enclosed associated type.
	///
	/// This takes a raw pointer when `P` is known, but is only the `P::Ptr`
	/// associated type when `P` is generic.
	pub fn from_ptr(ptr: P::Ptr<T>) -> Self {
		Self { ptr }
	}

	/// Converts this `Pointer` to its enclosed associated type.
	///
	/// This is a raw pointer when `P` is known, but remains the `P::Ptr`
	/// associated type when `P` is generic.
	pub fn as_ptr(self) -> P::Ptr<T> {
		self.ptr
	}

	/// Produces a raw immutable pointer.
	pub fn into_const_ptr(self) -> *const T {
		P::into_const::<T>(self.ptr)
	}

	/// Attempts to produce a raw mutable pointer.
	///
	/// Returns `None` when `P` is not `Unique`.
	pub fn try_into_mut_ptr(self) -> Option<*mut T> {
		P::try_into_mut::<T>(self.ptr)
	}

	/// Tests if this points to the null address.
	pub fn is_null(self) -> bool {
		self.ptr.is_null()
	}

	/// Changes the apparent type of the pointed-to value.
	///
	/// Pointer metadata such as region length or trait vtable can only be
	/// discarded, not transformed or conjured, by this function.
	pub fn cast<U: Sized>(self) -> Pointer<U, P> {
		let Self { ptr } = self;
		Pointer {
			ptr: <P as Permission>::cast::<T, U>(ptr),
		}
	}

	/// Creates a shared reference to the pointed-to value.
	///
	/// ## Safety
	///
	/// This function requires the following:
	///
	/// - the `Pointer` is well-aligned for `T`.
	/// - the pointed-to location contains an initialized `T` value.
	/// - no `&mut T` or `Reference<T, Unique>` pointing to the location exists
	///   for the duration of the produced reference’s existence.
	/// - the pointed-to location exists for the full duration of the conjured
	///   `'a` lifetime.
	pub unsafe fn as_ref<'a>(self) -> Option<&'a T> {
		if self.is_null() {
			return None;
		};
		Some(&*P::into_const(self.ptr))
	}

	/// Produces a reference to the pointed-to value.
	///
	/// ## Safety
	///
	/// This function requires the following:
	///
	/// - the `Pointer` is well-aligned for `T`.
	/// - the pointed-to location contains an initialized `T` value.
	/// - if `P` is `Unique`, no other reference to the pointed-to value may
	///   exist for the duration of the produced reference’s existence.
	/// - if `P` is `Shared`, then no `Unique` or `&mut` reference to the
	///   pointed-to value may exist for the duration.
	/// - the pointed-to location exists for the full duration of the conjured
	///   `'a` lifetime.
	pub unsafe fn as_reference<'a>(self) -> Option<Reference<'a, T, P>> {
		if self.is_null() {
			return None;
		}
		Some(P::ptr_to_ref(self.ptr))
	}

	/// Forcibly converts this to a pointer with `Shared` permissions.
	///
	/// This is always safe to do.
	pub fn cast_const(self) -> Pointer<T, Shared> {
		Pointer {
			ptr: self.into_const_ptr(),
		}
	}

	/// Forcibly converts this to a pointer with `Unique` permissions.
	///
	/// ## Safety
	///
	/// You must ensure that this pointer was originally drawn from a region
	/// with `*mut T` permissions. The penalty for violation of this rule on
	/// memory access is currently not specified, but cannot be relied upon to
	/// always work.
	pub unsafe fn cast_mut(self) -> Pointer<T, Unique> {
		Pointer {
			ptr: self.into_const_ptr().cast_mut(),
		}
	}

	/// Degrades the pointer to no longer have `Unique` permissions.
	///
	/// This prepends `Shared` to the `Permission` stack. The resulting pointer
	/// can remove this `Shared` and restore the current permission stack by
	/// calling `.cast_unshared()`.
	///
	/// Only the permission stack `(Shared, Unique)` has the method
	/// `.cast_mut()`, which directly produces a `Pointer<T, Unique>`.
	pub fn cast_shared(self) -> Pointer<T, (Shared, P)> {
		let ptr = P::into_const(self.ptr);
		let ptr = <(Shared, P)>::from_const(ptr);
		Pointer { ptr }
	}

	/// Gets the raw value of the address to which this points.
	pub fn addr(self) -> usize {
		P::addr::<T>(self.ptr)
	}
}

impl<T, P> Pointer<T, P>
where
	T: Sized,
	P: Permission,
{
	pub fn dangling() -> Self {
		Self {
			ptr: P::from_const(mem::align_of::<T>() as *const T),
		}
	}

	/// Tests if this points to the canonical “sentinel” address for a type.
	///
	/// Since most targets Rust supports do not permit addressing the zero page,
	/// Rust considers addresses which match the alignment of a type (that is,
	/// the addresses `0x1`, `0x2`, `0x4`, `0x8`, `0x10`, ... probably `0x1000`)
	/// to be “unlikely” to point to validly-initialized or dereferenceable
	/// memory, and uses these values to indicate that some structure which
	/// contains a pointer has been validly initialized, but has not been
	/// granted a region of memory to which it can usefully point.
	///
	/// This is a convenience function to support that use case, but should not
	/// be considered to indicate anything else about the pointed-to location.
	/// This behavior is determined entirely by the user, not by this type.
	pub fn is_dangling(self) -> bool {
		self == Self::dangling()
	}

	/// Adjusts the memory address by some number of `T` elements.
	///
	/// ## Safety
	///
	/// The resulting pointer must be within the same provenance region as the
	/// source pointer.
	pub unsafe fn offset(self, by: isize) -> Self {
		Self {
			ptr: self.ptr.offset(by),
		}
	}

	/// Adjusts the memory address by some number of `T` elements.
	///
	/// Note: the resulting pointer is permitted to be outside the provenance
	/// region of the source pointer. However, it will not be safe to
	/// dereference until it has been brought back within the original
	/// provenance bounds.
	pub fn wrapping_offset(self, by: isize) -> Self {
		Self {
			ptr: self.ptr.wrapping_offset(by),
		}
	}

	/// Produces the number of `T` elements between this pointer and the
	/// provided origin.
	///
	/// This is positive when `self` is higher in the memory space than `origin`
	/// and negative when `self` is lower in the memory space than `origin`.
	///
	/// # Safety
	///
	/// Both pointers must be within the same provenance region. This is most
	/// likely to be the case when `self` has been produced by calling
	/// `origin.offset()`.
	pub unsafe fn offset_from(self, origin: Self) -> isize {
		self.ptr.offset_from(origin.ptr)
	}

	/// Adjusts the memory address upwards in the memory space by some number of
	/// `T` elements.
	///
	/// ## Safety
	///
	/// The resulting pointer must be within the same provenance region as the
	/// source pointer.
	pub unsafe fn add(self, count: usize) -> Self {
		debug_assert!(
			count < (isize::MAX as usize),
			"Addend ({}) exceeds maximum ({})",
			count,
			isize::MAX
		);
		self.offset(count as isize)
	}

	/// Adjusts the memory address downwards in the memory space by some number
	/// of `T` elements.
	///
	/// ## Safety
	///
	/// The resulting pointer must be within the same provenance region as the
	/// source pointer.
	pub unsafe fn sub(self, count: usize) -> Self {
		debug_assert!(
			count < (isize::MAX as usize),
			"Subtrahend ({}) exceeds maximum ({})",
			count,
			isize::MAX
		);
		self.offset(-(count as isize))
	}

	/// Adjusts the memory address upwards in the memory space by some number of
	/// `T` elements.
	///
	/// Note: the resulting pointer is permitted to be outside the provenance
	/// region of the source pointer. However, it will not be safe to
	/// dereference until it has been brought back within the original
	/// provenance bounds.
	pub fn wrapping_add(self, count: usize) -> Self {
		debug_assert!(
			count < (isize::MAX as usize),
			"Addend ({}) exceeds maximum ({})",
			count,
			isize::MAX
		);
		self.wrapping_offset(count as isize)
	}

	/// Adjusts the memory address downwards in the memory space by some number
	/// of `T` elements.
	///
	/// Note: the resulting pointer is permitted to be outside the provenance
	/// region of the source pointer. However, it will not be safe to
	/// dereference until it has been brought back within the original
	/// provenance bounds.
	pub fn wrapping_sub(self, count: usize) -> Self {
		debug_assert!(
			count < (isize::MAX as usize),
			"Subtrahend ({}) exceeds maximum ({})",
			count,
			isize::MAX
		);
		self.wrapping_offset(-(count as isize))
	}

	/// Reads the value out of the pointed-to location.
	///
	/// ## Safety
	///
	/// The pointed-to location is now de-initialized, and must not have its
	/// destructor run unless the location is re-initialized with a new value,
	/// such as through `write`.
	pub unsafe fn read(self) -> T {
		self.ptr.read()
	}

	/// Equivalent to `read`, with the additional guarantee that the *compiler*
	/// will not omit this load.
	///
	/// This load does not synchronize across threads, nor does it create a
	/// causal dependency with any other memory accesses in the current thread.
	/// Its only guarantee is that the compiler will emit a load instruction.
	///
	/// ## Safety
	///
	/// See `read`.
	pub unsafe fn read_volatile(self) -> T {
		self.ptr.read_volatile()
	}

	/// Equivalent to `read`, except that it is tolerant of the address not
	/// being well-aligned for `T`.
	///
	/// ## Safety
	///
	/// See `read`.
	pub unsafe fn read_unaligned(self) -> T {
		self.ptr.read_unaligned()
	}

	/// Copies objects pointed to by `self` into the region pointed to by
	/// `dest`.
	///
	/// ## Safety
	///
	/// - the memory region of `self[.. count]` must contain contiguous
	///   fully-initialized `T` values.
	/// - the memory region of `dest[.. count]` must be within a single
	///   allocation.
	///
	/// ## Non-Effects
	///
	/// This does not run destructors on values stored in `dest[.. count]`, and
	/// any values stored there will become leaked.
	pub unsafe fn copy_to(self, dest: Pointer<T, Unique>, count: usize) {
		self.ptr.copy_to(dest.ptr, count)
	}

	/// Same as `copy_t`, except that you guarantee that the memory regions
	/// `self[.. count]` and `dest[.. count`] are fully disjoint.
	///
	/// ## Safety
	///
	/// The copying behavior from the self region to the destination region is
	/// not specified. As such, the two regions **must not** overlap at all in
	/// the memory space.
	pub unsafe fn copy_to_nonoverlapping(
		self,
		dest: Pointer<T, Unique>,
		count: usize,
	) {
		self.ptr.copy_to_nonoverlapping(dest.ptr, count)
	}

	/// Computes the positive offset, measured in `T` elements, that must be
	/// applied to this pointer in order to bring its address to the requested
	/// alignment.
	///
	/// The requested alignment is measured in bytes, and is most likely to be
	/// produced by calling `mem::align_of::<U>()`.
	pub fn align_offset(self, align: usize) -> usize {
		self.ptr.align_offset(align)
	}

	/// Converts this into a slice pointer, beginning at the pointed-to element
	/// and extending upwards in memory for `len` total elements.
	///
	/// ## Safety
	///
	/// `self[.. len]` must be within a single contiguous provenance region.
	pub unsafe fn make_slice(self, len: usize) -> Pointer<[T], P> {
		Pointer::from_raw_parts(self, len)
	}
}

impl<T, P> Pointer<[T], P>
where
	T: Sized,
	P: Permission,
{
	/// Produces a slice pointer from its raw parts.
	///
	/// ## Safety
	///
	/// The provided element pointer must point to a region of memory that is
	/// within a single allocation for at least `len` contiguous elements of
	/// `T`. The pointed-to region does not need to be initialized.
	pub unsafe fn from_raw_parts(ptr: Pointer<T, P>, len: usize) -> Self {
		Self {
			ptr: P::ptr_to_slice::<T>(ptr.ptr, len),
		}
	}
}

impl<T, P> fmt::Debug for Pointer<T, P>
where
	T: ?Sized,
	P: Permission,
{
	fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
		if fmt.alternate() {
			write!(fmt, "({} {})", P::DEBUG_PREFIX, any::type_name::<T>())?;
		}
		fmt::Debug::fmt(&P::into_const(self.ptr), fmt)
	}
}

impl<T, P> fmt::Pointer for Pointer<T, P>
where
	T: ?Sized,
	P: Permission,
{
	fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
		fmt::Pointer::fmt(&P::into_const(self.ptr), fmt)
	}
}

impl<T, P> Clone for Pointer<T, P>
where
	T: ?Sized,
	P: Permission,
{
	fn clone(&self) -> Self {
		*self
	}
}

impl<T, P> Eq for Pointer<T, P>
where
	T: ?Sized,
	P: Permission,
{
}

impl<T, P> Ord for Pointer<T, P>
where
	T: ?Sized,
	P: Permission,
{
	fn cmp(&self, other: &Self) -> cmp::Ordering {
		let this = P::into_const(self.ptr);
		let that = P::into_const(other.ptr);
		this.cmp(&that)
	}
}

impl<T, P1, P2> PartialEq<Pointer<T, P2>> for Pointer<T, P1>
where
	T: ?Sized,
	P1: Permission,
	P2: Permission,
{
	fn eq(&self, other: &Pointer<T, P2>) -> bool {
		let this = P1::into_const(self.ptr);
		let that = P2::into_const(other.ptr);
		this == that
	}
}

impl<T, P1, P2> PartialOrd<Pointer<T, P2>> for Pointer<T, P1>
where
	T: ?Sized,
	P1: Permission,
	P2: Permission,
{
	fn partial_cmp(&self, other: &Pointer<T, P2>) -> Option<cmp::Ordering> {
		let this = P1::into_const(self.ptr);
		let that = P2::into_const(other.ptr);
		this.partial_cmp(&that)
	}
}

impl<T> From<*const T> for Pointer<T, Shared>
where T: ?Sized
{
	fn from(src: *const T) -> Self {
		Self::new(src)
	}
}

impl<T> From<&T> for Pointer<T, Shared>
where T: ?Sized
{
	fn from(src: &T) -> Self {
		Self::new(src)
	}
}

impl<T> From<*mut T> for Pointer<T, Unique>
where T: ?Sized
{
	fn from(src: *mut T) -> Self {
		Self::new(src)
	}
}

impl<T> From<&mut T> for Pointer<T, Unique>
where T: ?Sized
{
	fn from(src: &mut T) -> Self {
		Self::new(src)
	}
}

impl<T, P> Hash for Pointer<T, P>
where
	T: ?Sized,
	P: Permission,
{
	fn hash<H: Hasher>(&self, hasher: &mut H) {
		P::into_const(self.ptr).hash(hasher);
	}
}

impl<T, P> Copy for Pointer<T, P>
where
	T: ?Sized,
	P: Permission,
{
}

#[repr(transparent)]
#[doc = include_str!("../doc/nonnull.md")]
pub struct NonNullPtr<T, P>
where
	T: ?Sized,
	P: Permission,
{
	/// The enclosed non-null pointer. Only the standard library can guarantee
	/// the presence of niches on types, or this type would just wrap `Pointer`.
	inner: NonNull<T>,
	/// Remember the `Permission`.
	_perm: PhantomData<P>,
}

impl<T> NonNullPtr<T, Shared>
where T: ?Sized
{
	/// Wraps a raw pointer, returning `None` if it is null.
	pub fn new(ptr: *const T) -> Option<Self> {
		NonNull::new(ptr.cast_mut()).map(Self::from_nonnull)
	}

	/// Wraps a raw pointer.
	///
	/// ## Safety
	///
	/// The pointer must not be null.
	pub const unsafe fn new_unchecked(ptr: *const T) -> Self {
		Self::from_nonnull(NonNull::new_unchecked(ptr.cast_mut()))
	}
}

impl<T> NonNullPtr<T, Unique>
where T: ?Sized
{
	/// Wraps a raw pointer, returning `None` if it is null.
	pub fn new(ptr: *mut T) -> Option<Self> {
		NonNull::new(ptr).map(Self::from_nonnull)
	}

	/// Wraps a raw pointer.
	///
	/// ## Safety
	///
	/// The pointer must not be null.
	pub const unsafe fn new_unchecked(ptr: *mut T) -> Self {
		Self::from_nonnull(NonNull::new_unchecked(ptr))
	}
}

impl<T, P> NonNullPtr<T, P>
where
	T: ?Sized,
	P: Permission,
{
	/// Encloses an existing non-null pointer.
	pub const fn from_nonnull(ptr: NonNull<T>) -> Self {
		Self {
			inner: ptr,
			_perm: PhantomData,
		}
	}

	/// Casts this to point to a different type at the same address.
	pub const fn cast<U: Sized>(self) -> NonNullPtr<U, P> {
		let Self { inner, _perm } = self;
		NonNullPtr {
			inner: inner.cast::<U>(),
			_perm,
		}
	}

	/// Discards the non-null guarantee.
	pub fn as_pointer(self) -> Pointer<T, P> {
		Pointer::from_ptr(P::from_const(self.inner.as_ptr().cast_const()))
	}

	/// Unconditionally produces a reference to the pointed-to value.
	///
	/// ## Safety
	///
	/// The pointed-to value must be initialized, must outlive the conjured `'a`
	/// lifetime`, and must have no other references to it that violate Rust’s
	/// rules. If `P` is `Unique`, no other references may exist at all; if `P`
	/// is shared, then no `Unique` reference may exist.
	pub unsafe fn as_reference<'a>(self) -> Reference<'a, T, P> {
		P::ptr_to_ref(self.as_pointer().as_ptr())
	}
}

impl<T, P> NonNullPtr<T, P>
where
	T: Sized,
	P: Permission,
{
	/// Produces the canonical dangling pointer for `T`.
	pub const fn dangling() -> Self {
		Self {
			inner: NonNull::dangling(),
			_perm: PhantomData,
		}
	}
}

#[doc = include_str!("../doc/references.md")]
pub type Reference<'a, T, P> = <P as Permission>::Ref<'a, T>;

/// Unifying bridge over `*const T` and `*mut T`.
#[doc(hidden)]
pub trait RawPtr<T: ?Sized>: Copy {
	fn is_null(self) -> bool;

	unsafe fn offset(self, by: isize) -> Self
	where T: Sized;

	fn wrapping_offset(self, by: isize) -> Self
	where T: Sized;

	unsafe fn offset_from(self, origin: Self) -> isize
	where T: Sized;

	unsafe fn read(self) -> T
	where T: Sized;

	unsafe fn read_volatile(self) -> T
	where T: Sized;

	unsafe fn read_unaligned(self) -> T
	where T: Sized;

	unsafe fn copy_to(self, dest: *mut T, count: usize)
	where T: Sized;

	unsafe fn copy_to_nonoverlapping(self, dest: *mut T, count: usize)
	where T: Sized;

	fn align_offset(self, align: usize) -> usize
	where T: Sized;
}

macro_rules! impl_raw_ptr {
	($($t:ty),+) => { $(
		impl<T: ?Sized> RawPtr<T> for $t {
			fn is_null(self) -> bool {
				self.is_null()
			}

			unsafe fn offset(self, by: isize) -> Self
			where T: Sized {
				self.offset(by)
			}

			fn wrapping_offset(self, by: isize) -> Self
			where T: Sized {
				self.wrapping_offset(by)
			}

			unsafe fn offset_from(self, origin: Self) -> isize
			where T: Sized {
				self.offset_from(origin)
			}

			unsafe fn read(self) -> T
			where T: Sized {
				self.read()
			}

			unsafe fn read_volatile(self) -> T
			where T: Sized {
				self.read_volatile()
			}

			unsafe fn read_unaligned(self) -> T
			where T: Sized {
				self.read_unaligned()
			}

			unsafe fn copy_to(self, dest: *mut T, count: usize)
			where T: Sized {
				self.copy_to(dest, count);
			}

			unsafe fn copy_to_nonoverlapping(self, dest: *mut T, count: usize)
			where T: Sized {
				self.copy_to_nonoverlapping(dest, count);
			}

			fn align_offset(self, align: usize) -> usize
			where T: Sized {
				self.align_offset(align)
			}
		}
	)+ };
}

impl_raw_ptr!(*const T, *mut T);

/// Unifying bridge over `&T` and `&mut T`.
#[doc(hidden)]
pub trait RawRef<'a, T: ?Sized> {}

impl<'a, T: 'a + ?Sized> RawRef<'a, T> for &'a T {
}

impl<'a, T: 'a + ?Sized> RawRef<'a, T> for &'a mut T {
}

#[cfg(test)]
mod tests {
	use super::*;
	use static_assertions::*;

	#[test]
	fn permission_stack() {
		// Ordinary permissions
		assert_impl_all!(Shared: Permission);
		assert_impl_all!(Unique: Permission);

		// Prepend `Shared` to some permission to create a stack
		assert_impl_all!((Shared, Shared): Permission);
		assert_impl_all!((Shared, Unique): Permission);

		// Prepend `Shared` to an existing stack
		assert_impl_all!((Shared, (Shared, Shared)): Permission);
		assert_impl_all!((Shared, (Shared, Unique)): Permission);
	}
}