dsa_rust/util/memory_management.rs
1#![allow(unused_imports)]
2
3#[test]
4/// Illustrates the various ways to get pointers, allocate memory,
5/// and initialize values.
6fn nonnull_test() {
7 use std::boxed::Box;
8 use std::ptr::NonNull;
9
10 // Creating a NonNull pointer
11
12 // 1) From a binding
13 // 1.1) usize -> *mut usize -> Option<NonNull<usize>>
14 // Valid for non-owning pointers
15 let mut a: usize = 64;
16 let b: *mut usize = &mut a;
17 let c: Option<NonNull<usize>> = NonNull::new(b);
18 assert_eq!(unsafe { *c.unwrap().as_ptr() }, 64usize);
19 unsafe { *c.unwrap().as_ptr() = 34usize };
20 assert_eq!(unsafe { *c.unwrap().as_ptr() }, 34usize);
21 // 1.2) usize -> Option<NonNull<usize>>
22 // Avoid outside specialized use cases
23 // This creates a pointer from the numerical value of a,
24 // it does not create a pointer to the value
25 let a: usize = 64;
26 #[allow(unknown_lints)]
27 let _b: Option<NonNull<usize>> = NonNull::new(a as *mut usize);
28 //assert_eq!(unsafe { *b.unwrap().as_ptr() }, 64usize); // Segfault!
29
30 // 2) From Box
31 //////////////
32
33 // 2.1) Box<usize> -> *mut usize -> NonNull<usize>
34 // NOTE: *mut T and NonNull<T> are non-owning pointer types.
35 // They do not enforce aliasing or ownership rules.
36 // The programmer must uphold Rust's aliasing guarantees manually.
37 // - Box::new allocates and binds
38 // - Box::into_raw converts binding to raw pointer
39 // - NonNull::new<T> -> Option<NonNull<T>>
40 // - NonNull::new_unchecked<T> -> NonNull<T>
41 // - Box::from_raw reclaims ownership
42 //
43 let a: Box<usize> = Box::new(64);
44 let b: *mut usize = Box::into_raw(a);
45 // SAFETY: Creating NonNull may actually be Null, so
46 // NonNull::new returns Option by default.
47 // If you can GUARANTEE that T is non-null, use
48 // the unsafe new_unchecked function instead of
49 // unwrapping the value.
50 //let c: NonNull<usize> = NonNull::new(b).unwrap();
51 let c: NonNull<usize> = unsafe { NonNull::new_unchecked(b) };
52 let d = c;
53 let e = d.as_ptr(); // Copy!
54 unsafe { *e = 24 };
55 assert_eq!(unsafe { *e }, 24);
56 assert_eq!(unsafe { *c.as_ref() }, unsafe { *b });
57 // Wraps ptr in Box for Drop cleanup to avoid leak
58 let _ = unsafe { Box::from_raw(c.as_ptr()) };
59
60 // 2.2) Inlines the raw pointer creation step
61 let a: *mut usize = Box::into_raw(Box::new(64));
62 let c: NonNull<usize> = unsafe { NonNull::new_unchecked(a) };
63 assert_eq!(unsafe { *c.as_ref() }, unsafe { *a });
64 // Wraps ptr in Box for Drop cleanup to avoid leak
65 //let _ = Box::new(c); // Leaks
66 let _ = unsafe { Box::from_raw(c.as_ptr()) };
67
68 // 2.3) Uses new for an Option<NonNull> just in case
69 let a = NonNull::new(Box::into_raw(Box::new(64)));
70 assert_eq!(unsafe { *a.unwrap().as_ptr() }, 64usize);
71 // Wraps ptr in Box for Drop cleanup to avoid leak
72 //let _ = Box::new(a); // Leaks
73 let _ = unsafe { Box::from_raw(a.unwrap().as_ptr()) };
74
75 // 2.4) Inlines NonNull::new_unchecked for brevity
76 // SAFETY: Pointer is guaranteed to be valid given
77 // composition chain from Boxed value
78 let a = unsafe { NonNull::new_unchecked(Box::into_raw(Box::new(64))) };
79 assert_eq!(unsafe { *a.as_ptr() }, 64usize);
80 // Wraps ptr in Box for Drop cleanup to avoid leak
81 //let _ = Box::new(a); // Leaks
82 let _ = unsafe { Box::from_raw(a.as_ptr()) };
83}
84
85#[test]
86fn size_of() {
87 use std::mem::size_of;
88 use std::ptr::NonNull;
89
90 // Option<NonNull> is optimized whereas Option<*mut T> is not!
91 // size_of() returns the byte offset of the argument which
92 // provides the effective size of a type
93 assert_eq!(size_of::<Option<NonNull<String>>>(), 8_usize);
94 assert_eq!(size_of::<*mut String>(), 8_usize);
95 assert_eq!(size_of::<Option<*mut String>>(), 16_usize);
96 assert_eq!(size_of::<usize>(), 8_usize);
97
98 assert_eq!(
99 size_of::<Option<NonNull<String>>>(),
100 size_of::<*mut String>()
101 );
102 assert_ne!(
103 size_of::<Option<NonNull<String>>>(),
104 size_of::<Option<*mut String>>()
105 );
106}
107
108// Using NonNull optimizations saves 24 bytes per AVLNode
109#[allow(unused)]
110mod opt {
111 use std::ptr::NonNull;
112 // Size: T + 4 * 8 bytes = T + 32 bytes
113 struct AVLNode<T> {
114 value: T,
115 parent: Option<NonNull<AVLNode<T>>>,
116 left: Option<NonNull<AVLNode<T>>>,
117 right: Option<NonNull<AVLNode<T>>>,
118 height: usize,
119 }
120
121 #[test]
122 fn one() {
123 let avl_node = AVLNode {
124 value: "Hello".to_string(),
125 parent: None,
126 left: None,
127 right: None,
128 height: 1,
129 };
130 // String is 24 bytes + 32 bytes base = 56 bytes
131 assert_eq!(size_of::<AVLNode<String>>(), 56_usize);
132 }
133}
134
135#[allow(unused)]
136mod nonopt {
137 // Size: T + 3 * 16 bytes + 8 bytes = T + 56 bytes
138 struct AVLNode<T> {
139 value: T,
140 parent: Option<*mut AVLNode<T>>,
141 left: Option<*mut AVLNode<T>>,
142 right: Option<*mut AVLNode<T>>,
143 height: usize,
144 }
145
146 #[test]
147 fn one() {
148 let avl_node = AVLNode {
149 value: "Hello".to_string(),
150 parent: None,
151 left: None,
152 right: None,
153 height: 1,
154 };
155 // String is 24 bytes + 56 bytes base = 80 bytes
156 assert_eq!(size_of::<AVLNode<String>>(), 80_usize);
157 }
158}
159
160#[test]
161#[allow(unused)]
162fn two() {
163 // Recursive, infinitely-sized types are illegal!
164 //struct Recursive<T>{
165 // data: Recursive<T>,
166 //}
167
168 // Recursive types must include:
169 // - Indirection (Box, Arc, Rc, raw pointers, etc.)
170 // on inner type reference to make the size finite
171 // - Non-recursive use of generic parameters, if present.
172 // For example, without data: T or PhantomData<T> this this
173 // type contains only recursive use of T. All type parameters
174 // must be used in a non-recursive way to constrain variance.
175 struct Recursive<T> {
176 next: Box<Recursive<T>>,
177 data: T, //marker: std::marker::PhantomData<T>
178 }
179
180 // Useless but legal because Rust only requires finite,
181 // computable sizing, not necessarily that any recursion terminate
182 struct RecursiveSized {
183 next: Box<RecursiveSized>,
184 }
185}
186
187use std::alloc;
188use std::mem;
189use std::ptr;
190
191#[test]
192#[allow(unused)]
193fn dangle() {
194 // Useful for representing empty collections
195 let a: *const u32 = ptr::dangling_mut();
196 // This dereference represents UB (and probable segfault) because
197 // b is not allocated or initialized
198 //let b = unsafe { *a }; // UB!!
199}
200
201#[test]
202#[allow(arithmetic_overflow)]
203fn overflow() {
204 //Panics on overflow with compiler checks enabled
205 //assert_eq!(u8::MAX + 1, 255);
206 //use std::ops::Add;
207 //assert_eq!(<u8 as Add>::add(255, 1), 3);
208
209 //Unchecked addition overflow causes UB!
210 //unsafe { assert_eq!(u8::MAX.unchecked_add(1), 255) };
211
212 //Explicitly defined overflow semantics
213 assert_eq!(u8::MAX.saturating_add(1), 255);
214 assert_eq!(u8::MAX.wrapping_add(1), 0);
215}