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
extern crate core;
/// Returns the address of an inner element without creating unneeded
/// intermediate references.
///
/// The general syntax is
// don't doctest this.
/// ```
/// element_ptr!(base_ptr => /* element accesses */ )
/// ````
/// where `base_ptr` may be any expression that evaluates to a value of the following types:
/// * [`*const T`]
/// * [`*mut T`]
/// * [`NonNull<T>`]
///
/// All accesses (besides a dereference) will maintain that pointer type of the input pointer.
/// This is especially nice with [`NonNull<T>`] because it makes everything involving it much
/// more ergonomic.
///
/// ### Element accesses
///
/// The following a table describes each of the possible accesses that can be inside the macro.
/// These can all be chained by simply putting one after another.
///
/// | Access Kind | Syntax | | Equivalent Pointer Expression |
/// |-----------------|---------------|-----------|------------------------------------------------|
/// | Field | `.field` | | <code>[addr_of!]\((*ptr).field)</code> |
/// | Index | `[index]` | | <code>ptr.[cast::\<T>]\().[add]\(index)</code> |
/// | Add Offset | `+ count` | [1](#sl1) | <code>ptr.[add]\(count)</code> |
/// | Sub Offset | `- count` | [1](#sl1) | <code>ptr.[sub]\(count)</code> |
/// | Byte Add Offset | `u8+ bytes` | [1](#sl1) | <code>ptr.[byte_add]\(bytes)</code> |
/// | Byte Sub Offset | `u8- bytes` | [1](#sl1) | <code>ptr.[byte_sub]\(bytes)</code> |
/// | Cast | `as T =>` | [2](#sl2) | <code>ptr.[cast::\<T>]\()</code> |
/// | Dereference | `.*` | [3](#sl3) | <code>ptr.[read]\()</code> |
/// | Grouping | `( ... )` | | Just groups the inner accesses for clarity. |
///
/// 1. <span id="sl1">
/// `count`/`bytes` may either be an integer literal or an expression wrapped in parentheses.
/// </span>
/// 2. <span id="sl2">
/// The `=>` may be omitted if the cast is the last access in a group.
/// </span>
/// 3. <span id="sl3">
/// A dereference may return a value that is not a pointer only if it is the final access in the macro.
/// In general it is encouraged to not do this and only use deferencing for inner pointers.
/// </span>
///
/// # Safety
/// * All of the [requirements][offsetreq] for [`offset()`] must be upheld. This is relevant for every
/// access except for dereferencing, grouping, and casting.
/// * The derefence access (`.*`) unconditionally reads from the pointer, and must not violate
/// any [requirements][readreq] related to that.
///
/// # Examples
///
/// The following example should give you a general sense of what the macro is capable of,
/// as well as a pretty good reference for how to use it.
///
/// ```
/// use element_ptr::element_ptr;
///
/// use std::{
/// alloc::{alloc, dealloc, Layout, handle_alloc_error},
/// ptr,
/// };
///
/// struct Example {
/// field_one: u32,
/// uninit: u32,
/// child_struct: ChildStruct,
/// another: *mut Example,
/// }
///
/// struct ChildStruct {
/// data: [&'static str; 6],
/// }
///
/// let example = unsafe {
/// // allocate two `Example`s on the heap, and then initialize them part by part.
/// let layout = Layout::new::<Example>();
///
/// let example = alloc(layout).cast::<Example>();
/// if example.is_null() { handle_alloc_error(layout) };
///
/// let other_example = alloc(layout).cast::<Example>();
/// if other_example.is_null() { handle_alloc_error(layout) };
///
/// // Get the pointer to `field_one` and initialize it.
/// element_ptr!(example => .field_one).write(100u32);
/// // But the `uninit` field isn't initialized.
/// // We can't take a reference to the struct without causing UB!
///
/// // Now initialize the child struct.
/// let string = "It is normally such a pain to manipulate raw pointers, isn't it?";
///
/// // Get each word from the sentence
/// for (index, word) in string.split(' ').enumerate() {
/// // and push alternating words to each child struct.
/// if index % 2 == 0 {
/// // The index can be any arbitrary expression that evaluates to an usize.
/// element_ptr!(example => .child_struct.data[index / 2]).write(word);
/// } else {
/// element_ptr!(other_example => .child_struct.data[index / 2]).write(word);
/// }
/// }
///
/// element_ptr!(example => .another).write(other_example);
///
/// example
/// };
///
///
/// // Now that the data is initialized, we can read data from the structs.
///
/// unsafe {
/// // The `element_ptr!` macro will get a raw pointer to the data.
/// let field_one_ptr: *mut u32 = element_ptr!(example => .field_one);
///
/// // This means you can even get a pointer to a field that is not initialized.
/// let uninit_field_ptr: *mut u32 = element_ptr!(example => .uninit);
///
/// assert_eq!(*field_one_ptr, 100);
///
/// let seventh_word = element_ptr!(example => .child_struct.data[3]);
///
/// assert_eq!(*seventh_word, "to");
///
/// // The `.*` access is used here to go into the pointer to `other_example`.
/// // Note that this requires the field `another` to be initialized, but not any
/// // of the other fields in `example`.
/// // As long as you don't use `.*`, you can be confident that no data will ever
/// // be dereferenced.
///
/// let second_word = element_ptr!(
/// example => .another.*.child_struct.data[0]
/// );
///
/// assert_eq!(*second_word, "is");
///
/// // Now lets deallocate everything so MIRI doesn't yell at me for leaking memory.
/// let layout = Layout::new::<Example>();
///
/// // Here as a convenience, we can cast the pointer to another type using `as T`.
/// dealloc(element_ptr!(example => .another.* as u8), layout);
/// // Of course this is simply the same as using `as *mut T`
/// dealloc(example as *mut u8, layout);
/// }
/// ```
///
// the following links need to be explicitly put because rustdoc cannot refer to pointer methods.
/// [addr_of!]: core::ptr::addr_of!
/// [read]: https://doc.rust-lang.org/core/primitive.pointer.html#method.read
/// [add]: https://doc.rust-lang.org/core/primitive.pointer.html#method.add
/// [sub]: https://doc.rust-lang.org/core/primitive.pointer.html#method.sub
/// [byte_add]: https://doc.rust-lang.org/core/primitive.pointer.html#method.byte_add
/// [byte_sub]: https://doc.rust-lang.org/core/primitive.pointer.html#method.byte_sub
/// [`offset()`]: https://doc.rust-lang.org/core/primitive.pointer.html#method.offset
/// [offsetreq]: https://doc.rust-lang.org/core/primitive.pointer.html#safety-2
/// [readreq]: https://doc.rust-lang.org/core/ptr/fn.read.html#safety
/// [cast::\<T>]: https://doc.rust-lang.org/core/primitive.pointer.html#method.cast
/// [`*const T`]: https://doc.rust-lang.org/core/primitive.pointer.html
/// [`*mut T`]: https://doc.rust-lang.org/core/primitive.pointer.html
/// [`NonNull<T>`]: core::ptr::NonNull
// #[cfg(not(doctest))] // just don't doctest any of these. Macros are way too hard to do.
pub use element_ptr;