-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy pathmain.rs
More file actions
2479 lines (2129 loc) · 68.6 KB
/
Copy pathmain.rs
File metadata and controls
2479 lines (2129 loc) · 68.6 KB
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
#![allow(internal_features, dead_code)]
#![feature(core_intrinsics, f16, f128, ptr_internals, ptr_metadata, set_ptr_value, layout_for_ptr)]
use core::mem::MaybeUninit;
fn generic_uninit_slice_data<T>(values: &mut [MaybeUninit<T>]) -> *mut T {
values.as_mut_ptr().cast::<T>()
}
fn boxed_uninit_slice_data<T>(length: usize) -> *mut T {
Box::into_raw(
(0..length)
.map(|_| MaybeUninit::<T>::uninit())
.collect::<Box<[_]>>(),
)
.cast::<T>()
}
fn generic_fat_pointer_casts() {
let mut values = [
MaybeUninit::<u32>::uninit(),
MaybeUninit::<u32>::uninit(),
MaybeUninit::<u32>::uninit(),
];
let data = generic_uninit_slice_data(&mut values);
unsafe {
data.write(11);
data.add(1).write(22);
data.add(2).write(33);
assert_eq!(data.read(), 11);
assert_eq!(data.add(1).read(), 22);
assert_eq!(data.add(2).read(), 33);
}
let boxed_data = boxed_uninit_slice_data::<u32>(3);
unsafe {
boxed_data.write(44);
boxed_data.add(1).write(55);
boxed_data.add(2).write(66);
assert_eq!(boxed_data.add(1).read(), 55);
drop(Box::from_raw(core::ptr::slice_from_raw_parts_mut(
boxed_data.cast::<MaybeUninit<u32>>(),
3,
)));
}
}
fn basic_raw_pointer_round_trip() {
let mut value = 41_i32;
let pointer = &mut value as *mut i32;
unsafe {
assert!(*pointer == 41);
*pointer = 42;
}
assert!(value == 42);
unsafe {
let previous = pointer.read();
pointer.write(previous + 1);
}
assert!(value == 43);
}
fn array_pointer_arithmetic() {
let mut values = [10_i32, 20, 30, 40, 50];
let base = values.as_mut_ptr();
unsafe {
assert!(*base == 10);
assert!(*base.add(2) == 30);
*base.add(1) = 22;
*base.offset(3) = 44;
assert!(*base.add(4).sub(2) == 30);
assert!(base.add(5).offset_from(base) == 5);
}
assert!(values[0] == 10);
assert!(values[1] == 22);
assert!(values[2] == 30);
assert!(values[3] == 44);
assert!(values[4] == 50);
}
fn pointer_identity_and_casts() {
let value = 7_i32;
let first = &value as *const i32;
let alias = first;
let other_value = 7_i32;
let other = &other_value as *const i32;
assert!(first == alias);
assert!(first != other);
let mut mutable = 9_i32;
let mutable_pointer = &mut mutable as *mut i32;
let const_pointer = mutable_pointer as *const i32;
unsafe {
assert!(*const_pointer == 9);
*mutable_pointer = 11;
}
assert!(mutable == 11);
let exposed_address = mutable_pointer as usize;
let restored_pointer = exposed_address as *mut i32;
unsafe {
*restored_pointer = 13;
}
assert!(mutable == 13);
}
struct Pair {
left: i32,
right: i32,
}
impl Pair {
#[inline(never)]
fn choose<'a>(&'a self, other: &'a Self, use_other: bool) -> &'a Self {
if use_other { other } else { self }
}
}
#[repr(C)]
struct PackedWords {
low: u16,
high: u16,
}
#[repr(C)]
struct NestedPackedWords {
prefix: u8,
words: PackedWords,
}
#[repr(u32)]
enum WireState {
First = 0x1122_3344,
Second = 0x5566_7788,
}
#[repr(C, u8)]
enum PayloadState {
First(u32),
Second(u32),
}
#[repr(C)]
struct PointerHolder {
tag: u32,
pointer: *mut i32,
}
#[repr(C)]
struct StringPointerHolder {
text: &'static str,
marker: u32,
}
#[repr(C)]
struct WideAggregate {
value: u128,
marker: u32,
}
#[repr(C)]
union WordBytes {
word: u32,
bytes: [u8; 4],
}
struct ZeroSized;
trait RawDynValue {
fn get(&self) -> i32;
fn set(&mut self, value: i32);
}
struct DynValue {
value: i32,
}
impl RawDynValue for DynValue {
fn get(&self) -> i32 {
self.value
}
fn set(&mut self, value: i32) {
self.value = value;
}
}
fn advance_one_u32(address: usize) -> usize {
address + 4
}
fn add_through_reference(value: &mut i32, amount: i32) {
*value += amount;
}
fn read_through_reference(value: &i32) -> i32 {
*value
}
fn projected_places_and_reborrows() {
let mut pair = Pair {
left: 12,
right: 30,
};
let right = core::ptr::addr_of_mut!(pair.right);
unsafe {
*right += 12;
}
assert!(pair.left == 12);
assert!(pair.right == 42);
let mut value = 5_i32;
let reference = &mut value;
let raw = reference as *mut i32;
let reborrow = unsafe { &mut *raw };
*reborrow += 7;
assert!(value == 12);
}
fn reference_identity() {
let value = 17_i32;
let first = &value;
let second = &value;
let alias = first;
let equal_but_distinct = 17_i32;
assert!(first as *const i32 == second as *const i32);
assert!(first as *const i32 == alias as *const i32);
let first_pair = Pair { left: 1, right: 2 };
let second_pair = Pair { left: 3, right: 4 };
assert!(first_pair.choose(&second_pair, false).right == 2);
assert!(first_pair.choose(&second_pair, true).left == 3);
assert!(first as *const i32 != &equal_but_distinct as *const i32);
let mut across_call = 30_i32;
add_through_reference(&mut across_call, 12);
assert!(read_through_reference(&across_call) == 42);
}
fn nested_and_aggregate_pointers() {
let mut first_value = 10_i32;
let mut second_value = 20_i32;
let mut active = &mut first_value as *mut i32;
let active_pointer = &mut active as *mut *mut i32;
unsafe {
**active_pointer = 11;
*active_pointer = &mut second_value;
**active_pointer = 22;
}
assert!(first_value == 11);
assert!(second_value == 22);
// A pointer value is itself addressable memory: byte-level access must preserve its bits.
let pointer_bytes = (&mut active as *mut *mut i32).cast::<u8>();
unsafe {
let low_byte = pointer_bytes.read();
pointer_bytes.write(low_byte);
**active_pointer = 23;
}
assert!(second_value == 23);
let inners = [&mut first_value as *mut i32, &mut second_value as *mut i32];
let outer = inners.as_ptr();
unsafe {
**outer += 10;
**outer.add(1) += 20;
}
assert!(first_value == 21);
assert!(second_value == 43);
let mut pairs = [
Pair { left: 1, right: 2 },
Pair { left: 3, right: 4 },
Pair { left: 5, right: 6 },
];
let pairs_ptr = pairs.as_mut_ptr();
unsafe {
(*pairs_ptr.add(1)).right = 40;
pairs_ptr.add(2).write(Pair {
left: 20,
right: 22,
});
}
assert!(pairs[0].left == 1);
assert!(pairs[1].right == 40);
assert!(pairs[2].left + pairs[2].right == 42);
}
static STATIC_VALUE: i32 = 21;
static STATIC_SINGLETON_SLICE: &[i32] = &[123];
static mut MUTABLE_STATIC_VALUE: i32 = 40;
static mut DROP_COUNT: u32 = 0;
struct NeedsDrop;
impl Drop for NeedsDrop {
fn drop(&mut self) {
unsafe {
*core::ptr::addr_of_mut!(DROP_COUNT) += 1;
}
}
}
trait DynDropProbe {
fn amount(&self) -> u32;
}
struct DynDropAmount {
amount: u32,
}
impl DynDropProbe for DynDropAmount {
fn amount(&self) -> u32 {
self.amount
}
}
impl Drop for DynDropAmount {
fn drop(&mut self) {
unsafe {
*core::ptr::addr_of_mut!(DROP_COUNT) += self.amount;
}
}
}
struct DynDropContainer {
child: DropAmount,
}
impl DynDropProbe for DynDropContainer {
fn amount(&self) -> u32 {
self.child.amount
}
}
struct PlainDynDropValue {
amount: u32,
}
impl DynDropProbe for PlainDynDropValue {
fn amount(&self) -> u32 {
self.amount
}
}
struct DropAmount {
amount: u32,
}
impl Drop for DropAmount {
fn drop(&mut self) {
unsafe {
*core::ptr::addr_of_mut!(DROP_COUNT) += self.amount;
}
}
}
struct DropContainer {
first: DropAmount,
second: DropAmount,
}
struct DropEnvelope {
own_amount: u32,
child: DropAmount,
}
enum DropChoice {
Empty,
One(DropAmount),
Two(DropAmount, DropAmount),
}
impl Drop for DropEnvelope {
fn drop(&mut self) {
unsafe {
*core::ptr::addr_of_mut!(DROP_COUNT) += self.own_amount;
}
}
}
fn static_addresses() {
let first = core::ptr::addr_of!(STATIC_VALUE);
let second = core::ptr::addr_of!(STATIC_VALUE);
assert!(first == second);
unsafe {
assert!(*first == 21);
}
assert_eq!(STATIC_SINGLETON_SLICE, &[123]);
assert_eq!(STATIC_SINGLETON_SLICE.as_ptr(), STATIC_SINGLETON_SLICE.as_ptr());
assert_eq!(unsafe { *STATIC_SINGLETON_SLICE.as_ptr() }, 123);
let mutable = core::ptr::addr_of_mut!(MUTABLE_STATIC_VALUE);
unsafe {
*mutable += 2;
assert!(*core::ptr::addr_of!(MUTABLE_STATIC_VALUE) == 42);
}
}
fn other_pointer_carriers() {
let mut flags = [false, true, false];
let flag_pointer = flags.as_mut_ptr();
unsafe {
*flag_pointer.add(2) = true;
}
assert!(flags[0] == false);
assert!(flags[1]);
assert!(flags[2]);
let mut values = [1.5_f64, 2.5, 3.5];
let value_pointer = values.as_mut_ptr();
unsafe {
*value_pointer.add(1) = 42.25;
}
assert!(values[0] == 1.5);
assert!(values[1] == 42.25);
assert!(values[2] == 3.5);
}
fn null_and_wrapping_arithmetic() {
let null = 0_usize as *const i32;
assert!(null.is_null());
assert!(null as usize == 0);
let values = [3_i32, 6, 9, 12];
let base = values.as_ptr();
let end = base.wrapping_add(4);
let last = end.wrapping_sub(1);
unsafe {
assert!(*last == 12);
}
}
fn same_width_pointer_reinterpretation() {
let mut float = 1.0_f32;
let bits = &mut float as *mut f32 as *mut i32;
unsafe {
assert!(*bits == 0x3f80_0000_i32);
*bits = 0x4000_0000_i32;
}
assert!(float == 2.0);
let mut double = 1.0_f64;
let bits = &mut double as *mut f64 as *mut i64;
unsafe {
assert!(*bits == 0x3ff0_0000_0000_0000_i64);
*bits = 0x4000_0000_0000_0000_i64;
}
assert!(double == 2.0);
}
fn f16_pointer_storage() {
let mut value = 1.5_f16;
let pointer = &mut value as *mut f16;
unsafe {
assert!(*pointer == 1.5_f16);
let bits = pointer.cast::<u16>();
assert!(*bits == 0x3e00);
*bits = 0x4000;
}
assert!(value == 2.0_f16);
}
fn wide_scalar_pointer_storage() {
let mut value64 = 0x1122_3344_5566_7788_u64;
let bytes64 = (&mut value64 as *mut u64).cast::<u8>();
unsafe {
assert!(*bytes64 == 0x88);
assert!(*bytes64.add(7) == 0x11);
*bytes64.add(7) = 0xaa;
}
assert!(value64 == 0xaa22_3344_5566_7788_u64);
let mut value128 = 0x1122_3344_5566_7788_99aa_bbcc_ddee_ff00_u128;
let bytes128 = (&mut value128 as *mut u128).cast::<u8>();
unsafe {
assert!(*bytes128 == 0x00);
assert!(*bytes128.add(15) == 0x11);
*bytes128.add(1) = 0x42;
*bytes128.add(15) = 0xfe;
}
assert!(value128 == 0xfe22_3344_5566_7788_99aa_bbcc_ddee_4200_u128);
let mut signed = 0_i128;
let signed_bytes = (&mut signed as *mut i128).cast::<u8>();
unsafe {
*signed_bytes.add(15) = 0x80;
}
assert!(signed == i128::MIN);
const TWO_BITS: u128 = 0x4000_0000_0000_0000_0000_0000_0000_0000;
let mut wide_float = 1.0_f128;
let float_bits = (&mut wide_float as *mut f128).cast::<u128>();
unsafe {
assert!(*float_bits == 1.0_f128.to_bits());
*float_bits = TWO_BITS;
}
assert!(wide_float == 2.0_f128);
assert!(wide_float.to_bits() == TWO_BITS);
}
fn byte_addressing_and_integer_addresses() {
let mut words = [0x1122_3344_u32, 0x5566_7788_u32];
let words_ptr = words.as_mut_ptr();
let bytes = words_ptr.cast::<u8>();
unsafe {
assert!(*bytes.add(0) == 0x44);
assert!(*bytes.add(1) == 0x33);
assert!(*bytes.add(2) == 0x22);
assert!(*bytes.add(3) == 0x11);
assert!(*bytes.add(4) == 0x88);
*bytes.add(1) = 0xaa;
}
assert!(words[0] == 0x1122_aa44);
let second_from_bytes = unsafe { bytes.add(core::mem::size_of::<u32>()) }.cast::<u32>();
unsafe {
assert!(*second_from_bytes == 0x5566_7788);
}
let second_address = bytes as usize + core::mem::size_of::<u32>();
let second_from_address = second_address as *const u32;
unsafe {
assert!(*second_from_address == 0x5566_7788);
}
let mut unsigned_bytes = [0_u8, 127, 128, 255];
let unsigned_ptr = unsigned_bytes.as_mut_ptr();
unsafe {
assert!(*unsigned_ptr.add(2) == 128);
*unsigned_ptr.add(1) = 200;
assert!(*unsigned_ptr.add(1) == 200);
}
assert!(unsigned_bytes[1] == 200);
}
fn pointer_ordering() {
let values = [10_i32, 20, 30];
let first = values.as_ptr();
let second = unsafe { first.add(1) };
let end = unsafe { first.add(values.len()) };
assert!(first < second);
assert!(second <= second);
assert!(end > second);
assert!(end >= first);
}
unsafe fn raw_binary_search(values: *const u32, length: usize, target: u32) -> Option<usize> {
let mut low = 0;
let mut high = length;
while low < high {
let middle = low + (high - low) / 2;
let value = unsafe { *values.add(middle) };
if value < target {
low = middle + 1;
} else if value > target {
high = middle;
} else {
return Some(middle);
}
}
None
}
fn raw_pointer_binary_search() {
let values = [1_u32, 3, 5, 8, 13, 21, 34];
unsafe {
assert!(raw_binary_search(values.as_ptr(), values.len(), 1) == Some(0));
assert!(raw_binary_search(values.as_ptr(), values.len(), 13) == Some(4));
assert!(raw_binary_search(values.as_ptr(), values.len(), 34) == Some(6));
assert!(raw_binary_search(values.as_ptr(), values.len(), 4).is_none());
assert!(raw_binary_search(values.as_ptr(), values.len(), 35).is_none());
}
}
fn unaligned_volatile_and_bulk_memory() {
let mut bytes = [0_u8; 12];
let unaligned = unsafe { bytes.as_mut_ptr().add(1) }.cast::<u32>();
unsafe {
unaligned.write_unaligned(0x4433_2211);
assert!(unaligned.read_unaligned() == 0x4433_2211);
}
assert!(bytes[1] == 0x11);
assert!(bytes[2] == 0x22);
assert!(bytes[3] == 0x33);
assert!(bytes[4] == 0x44);
let mut volatile_value = 10_i32;
let volatile_pointer = &mut volatile_value as *mut i32;
unsafe {
volatile_pointer.write_volatile(42);
assert!(volatile_pointer.read_volatile() == 42);
}
assert!(volatile_value == 42);
let source = [1_u8, 2, 3, 4, 5, 6];
let mut destination = [0_u8; 6];
unsafe {
core::ptr::copy_nonoverlapping(source.as_ptr(), destination.as_mut_ptr(), source.len());
}
assert!(destination[0] == 1);
assert!(destination[1] == 2);
assert!(destination[2] == 3);
assert!(destination[3] == 4);
assert!(destination[4] == 5);
assert!(destination[5] == 6);
unsafe {
core::ptr::copy(destination.as_ptr(), destination.as_mut_ptr().add(1), 5);
}
assert!(destination[0] == 1);
assert!(destination[1] == 1);
assert!(destination[2] == 2);
assert!(destination[3] == 3);
assert!(destination[4] == 4);
assert!(destination[5] == 5);
unsafe {
core::ptr::write_bytes(destination.as_mut_ptr(), 0xaa, destination.len());
}
assert!(destination[0] == 0xaa);
assert!(destination[1] == 0xaa);
assert!(destination[2] == 0xaa);
assert!(destination[3] == 0xaa);
assert!(destination[4] == 0xaa);
assert!(destination[5] == 0xaa);
}
fn aggregate_memory_layout() {
let mut words = PackedWords {
low: 0x1122,
high: 0x3344,
};
let words_pointer = &mut words as *mut PackedWords;
let bytes = words_pointer.cast::<u8>();
unsafe {
assert!(*bytes.add(0) == 0x22);
assert!(*bytes.add(1) == 0x11);
assert!(*bytes.add(2) == 0x44);
assert!(*bytes.add(3) == 0x33);
*bytes.add(2) = 0xaa;
*bytes.add(3) = 0xbb;
}
assert!(words.low == 0x1122);
assert!(words.high == 0xbbaa);
let mut array = [
PackedWords { low: 1, high: 2 },
PackedWords { low: 3, high: 4 },
];
let array_bytes = array.as_mut_ptr().cast::<u8>();
let second = unsafe { array_bytes.add(core::mem::size_of::<PackedWords>()) };
unsafe {
*second = 0x34;
*second.add(1) = 0x12;
}
assert!(array[0].low == 1);
assert!(array[1].low == 0x1234);
assert!(array[1].high == 4);
assert!(WireState::Second as u32 == 0x5566_7788);
let mut state = WireState::First;
let replacement = [0x88_u8, 0x77, 0x66, 0x55];
unsafe {
core::ptr::copy_nonoverlapping(
replacement.as_ptr(),
(&mut state as *mut WireState).cast::<u8>(),
replacement.len(),
);
}
assert!(matches!(state, WireState::Second));
let mut payload_state = PayloadState::First(1);
match &payload_state {
PayloadState::First(value) => assert!(*value == 1),
PayloadState::Second(_) => panic!(),
}
let replacement_state = PayloadState::Second(42);
unsafe {
core::ptr::copy_nonoverlapping(
(&replacement_state as *const PayloadState).cast::<u8>(),
(&mut payload_state as *mut PayloadState).cast::<u8>(),
core::mem::size_of::<PayloadState>(),
);
}
match payload_state {
PayloadState::Second(value) => assert!(value == 42),
PayloadState::First(_) => panic!(),
}
let mut first_target = 10_i32;
let mut second_target = 20_i32;
let mut first_holder = PointerHolder {
tag: 1,
pointer: &mut first_target,
};
let second_holder = PointerHolder {
tag: 2,
pointer: &mut second_target,
};
let first_bytes = (&mut first_holder as *mut PointerHolder).cast::<u8>();
let second_bytes = (&second_holder as *const PointerHolder).cast::<u8>();
unsafe {
// repr(C) places the 8-byte-aligned pointer after four bytes of padding.
core::ptr::copy_nonoverlapping(second_bytes.add(8), first_bytes.add(8), 8);
*first_holder.pointer = 42;
}
assert!(first_target == 10);
assert!(second_target == 42);
assert!(first_holder.tag == 1);
let mut wide = WideAggregate {
value: 0x1122_3344_5566_7788_99aa_bbcc_ddee_ff00_u128,
marker: 42,
};
let wide_bytes = (&mut wide as *mut WideAggregate).cast::<u8>();
unsafe {
assert!(*wide_bytes == 0x00);
assert!(*wide_bytes.add(15) == 0x11);
*wide_bytes.add(15) = 0xaa;
}
assert!(wide.value == 0xaa22_3344_5566_7788_99aa_bbcc_ddee_ff00_u128);
assert!(wide.marker == 42);
}
fn managed_reference_fields_have_memory_bits() {
let mut destination = StringPointerHolder {
text: "destination",
marker: 11,
};
let source = StringPointerHolder {
text: "copied reference",
marker: 22,
};
unsafe {
core::ptr::copy_nonoverlapping(
(&source as *const StringPointerHolder).cast::<u8>(),
(&mut destination as *mut StringPointerHolder).cast::<u8>(),
core::mem::size_of::<&'static str>(),
);
}
assert!(destination.text == "copied reference");
assert!(destination.marker == 11);
let field = core::ptr::addr_of_mut!(destination.text);
unsafe {
field.write("field pointer update");
assert!(*field == "field pointer update");
}
assert!(destination.text == "field pointer update");
}
fn projected_field_addresses_share_allocations() {
let mut words = PackedWords {
low: 0x1122,
high: 0x3344,
};
let whole = &mut words as *mut PackedWords;
let low = core::ptr::addr_of_mut!(words.low);
let high = core::ptr::addr_of_mut!(words.high);
assert!(whole.cast::<u16>() == low);
assert!(high.addr() - low.addr() == 2);
unsafe {
*low.add(1) = 0x5566;
}
assert!(words.low == 0x1122);
assert!(words.high == 0x5566);
let restored = whole.expose_provenance() as *mut PackedWords;
unsafe {
(*restored).high = 0x7788;
}
assert!(words.high == 0x7788);
let mut nested = NestedPackedWords {
prefix: 7,
words: PackedWords {
low: 0x1234,
high: 0x5678,
},
};
let nested_base = &mut nested as *mut NestedPackedWords;
let nested_words = core::ptr::addr_of_mut!(nested.words);
let nested_high = core::ptr::addr_of_mut!(nested.words.high);
assert!(nested_words.addr() == nested_base.addr() + 2);
assert!(nested_high.addr() == nested_base.addr() + 4);
assert!(unsafe { nested_high.byte_offset_from(nested_base.cast::<u8>()) } == 4);
unsafe {
*nested_high = 0xabcd;
}
assert!(nested.words.high == 0xabcd);
let restored_nested_high = nested_high.expose_provenance() as *mut u16;
unsafe {
*restored_nested_high = 0xcdef;
}
assert!(nested.words.high == 0xcdef);
let mut overlay = WordBytes { word: 0x1122_3344 };
let word = core::ptr::addr_of_mut!(overlay.word);
let bytes = core::ptr::addr_of_mut!(overlay.bytes).cast::<u8>();
assert!(word.cast::<u8>() == bytes);
unsafe {
*bytes = 0xaa;
assert!(*word == 0x1122_33aa);
}
}
fn byte_methods_alignment_provenance_and_zsts() {
let values = [0x1122_3344_u32, 0x5566_7788_u32];
let first = values.as_ptr();
let second = unsafe { first.add(1) };
unsafe {
assert!(first.byte_add(4) == second);
assert!(second.byte_sub(4) == first);
assert!(first.byte_offset(4) == second);
assert!(second.wrapping_byte_sub(4) == first);
}
assert!(first.align_offset(core::mem::align_of::<u32>()) == 0);
let misaligned = unsafe { first.cast::<u8>().add(1) };
assert!(misaligned.align_offset(4) == 3);
let first_address = first.addr();
let second_from_address = first.with_addr(first_address + 4);
assert!(second_from_address == second);
assert!(first.expose_provenance() == first_address);
assert!(core::ptr::null::<u32>().is_null());
assert!(core::ptr::null_mut::<u32>().is_null());
let mapped = first.map_addr(|address| address + 4);
assert!(mapped == second);
let captured_delta = 4;
let captured_mapped = first.map_addr(|address| address + captured_delta);
assert!(captured_mapped == second);
assert!(first.map_addr(advance_one_u32) == second);
let address_mapper: fn(usize) -> usize = advance_one_u32;
assert!(first.map_addr(address_mapper) == second);
let address_only = core::ptr::without_provenance::<u32>(first_address);
assert!(address_only.addr() == first_address);
assert!(address_only == first);
assert!(address_only.with_addr(second.addr()) == second);
let restored = core::ptr::with_exposed_provenance::<u32>(first.expose_provenance());
unsafe {
assert!(*restored == 0x1122_3344);
}
let (data, metadata) = first.to_raw_parts();
assert!(data.addr() == first.addr());
let rebuilt = core::ptr::from_raw_parts::<u32>(data, metadata);
assert!(rebuilt == first);
let metadata_from = first.cast::<u8>().with_metadata_of(first);
assert!(metadata_from == first);
let slice_metadata = &values[1..] as *const [u32];
let rebuilt_slice = first.cast::<u8>().with_metadata_of(slice_metadata);
assert!(core::ptr::metadata(rebuilt_slice) == 1);
unsafe {
assert!((*rebuilt_slice)[0] == values[0]);
}
let sized_metadata = core::ptr::metadata(first);
assert!(sized_metadata == ());
let zsts = [ZeroSized, ZeroSized, ZeroSized];
let zst_pointer = zsts.as_ptr();
assert!(unsafe { zst_pointer.add(1) } == zst_pointer);
assert!(zst_pointer.wrapping_add(100) == zst_pointer);
}
fn stable_pointer_api_surface() {
let mut values = [10_u32, 20, 30, 40];
let base = values.as_mut_ptr();
let end = unsafe { base.add(values.len()) };
unsafe {
assert!(end.offset_from_unsigned(base) == values.len());
assert!(end.byte_offset_from(base) == 16);
assert!(end.byte_offset_from_unsigned(base) == 16);
}
assert!(base.is_aligned());
let shared = unsafe { base.as_ref() };
assert!(shared.is_some());
match shared {
Some(value) => assert!(*value == 10),
None => panic!(),
}
assert!(unsafe { core::ptr::null::<u32>().as_ref() }.is_none());
match unsafe { base.as_mut() } {
Some(value) => *value = 11,
None => panic!(),
}
assert!(values[0] == 11);
let by_ref = core::ptr::from_ref(&values[1]);
assert!(by_ref == unsafe { base.add(1) });
let by_mut = core::ptr::from_mut(&mut values[2]);
unsafe {
*by_mut = 31;
}
assert!(values[2] == 31);
let mut copied = [0_u32; 4];
unsafe {
base.copy_to_nonoverlapping(copied.as_mut_ptr(), values.len());
}
assert!(copied[0] == values[0]);
assert!(copied[1] == values[1]);
assert!(copied[2] == values[2]);
assert!(copied[3] == values[3]);
let replacement = [1_u32, 2, 3, 4];
unsafe {
copied
.as_mut_ptr()
.copy_from_nonoverlapping(replacement.as_ptr(), replacement.len());
}
assert!(copied[0] == 1);
assert!(copied[1] == 2);
assert!(copied[2] == 3);
assert!(copied[3] == 4);
unsafe {
copied.as_mut_ptr().copy_to(copied.as_mut_ptr().add(1), 3);
}
assert!(copied[0] == 1);
assert!(copied[1] == 1);
assert!(copied[2] == 2);
assert!(copied[3] == 3);
let previous = unsafe { copied.as_mut_ptr().replace(9) };
assert!(previous == 1);
assert!(copied[0] == 9);
unsafe {
copied.as_mut_ptr().swap(copied.as_mut_ptr().add(3));
}
assert!(copied[0] == 3);
assert!(copied[1] == 1);
assert!(copied[2] == 2);
assert!(copied[3] == 9);
unsafe {
core::ptr::swap_nonoverlapping(copied.as_mut_ptr(), copied.as_mut_ptr().add(2), 2);
}
assert!(copied[0] == 2);
assert!(copied[1] == 9);
assert!(copied[2] == 3);
assert!(copied[3] == 1);
let mut strings = ["a", "b", "c", "d"];
strings.swap(1, 3);
assert!(strings == ["a", "d", "c", "b"]);
strings.swap(0, 3);
assert!(strings == ["b", "d", "c", "a"]);
let mut bytes = [0_u16; 3];
unsafe {
bytes.as_mut_ptr().write_bytes(0x5a, bytes.len());
}
assert!(bytes[0] == 0x5a5a);
assert!(bytes[1] == 0x5a5a);
assert!(bytes[2] == 0x5a5a);
assert!(core::ptr::addr_eq(base, base.cast::<u8>()));
assert!(core::ptr::eq(base, base));
assert!(!core::ptr::eq(base, unsafe { base.add(1) }));
let dangling = core::ptr::dangling::<u32>();
let dangling_mut = core::ptr::dangling_mut::<u32>();
assert!(!dangling.is_null());
assert!(dangling.is_aligned());
assert!(dangling.addr() == dangling_mut.addr());
}
fn non_null_tagged_addresses() {
use core::num::NonZero;
use core::ptr::NonNull;
#[repr(transparent)]
struct Tagged<T>(NonNull<T>);
impl<T> Tagged<T> {
const ALIGNMENT: usize = core::mem::align_of::<T>();
const NUM_BITS: u32 = Self::ALIGNMENT.trailing_zeros();
const ADDRESS_MASK: usize = usize::MAX << Self::NUM_BITS;
const DATA_MASK: usize = !Self::ADDRESS_MASK;
fn tag(&self) -> usize {
self.0.addr().get() & Self::DATA_MASK
}
fn set_tag(&mut self, tag: usize) {
assert_eq!(tag & Self::ADDRESS_MASK, 0);
self.0 = self.0.map_addr(|address| unsafe {
NonZero::new_unchecked(
(address.get() & Self::ADDRESS_MASK) | (tag & Self::DATA_MASK),
)
});