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
//! The `stackpin` crate exposes a [`StackPinned`] type that allows to represent [`!Unpin`] data that should be [pinned](https://doc.rust-lang.org/std/pin/index.html) to the stack
//! at the point of declaration.
//! The crate exposes a trait, [`FromUnpinned`], as well as a [`stack_let`] macro that makes safely creating [`StackPinned`] instances easier.
//! The crate also exposes the [`PinStack`] type alias for `Pin<StackPinned<T>>`.
//!
//! This crate was inspired from the [pin-utils] crate, the main differences being:
//! * [pin-utils] provides a macro to return a `Pin<&mut T>` instance,
//! with a "mutable reference" semantics that includes reborrow. The `stackpin` crate promotes a
//! "root handle" semantics that guarantees that a function consuming a [`PinStack<T>`] consumes
//! the *only* handle to `T`, and not a reborrowed reference.
//! * The syntax for the `stack_let!(mut id : ty = expr)` macro attempts to mimic a regular `let mut id : ty = expr` statement.
//! * The provided [`FromUnpinned`] trait and [`Unpinned`] struct aim at separating unmovable types
//! from the data that can be used to construct them. `stackpin` aims at promoting a model where
//! all unmovable types are only accessible once pinned.
//! * The [`StackPinned<T>`] type expresses strong guarantee about the fact that the destructor for
//! `T` will be run.
//! * The `stackpin` crate solely focuses on stack pinning. The [pin-utils] crate also provides
//! other utilities such as pin projection.
//!
//! # Stack pinnable types
//!
//! A type T that wants to benefit from the guarantees provided by [`StackPinned`] should be
//! [`!Unpin`]. This is necessary to enforce the "drop will be run" guarantee.
//!
//! Additionally, the `stackpin` crate promotes an idiom where "unmovable" types are strictly
//! separated from movable types, and are preferably only accessible through `PinStack`.
//!
//! For example, let's consider the following `Unmovable` struct (from the [documentation for the
//! `pin` module](https://doc.rust-lang.org/std/pin/index.html)):
//! ```
//! use std::marker::PhantomPinned;
//! use std::ptr::NonNull;
//! struct Unmovable {
//! // Owned data
//! s: String,
//! // Self referential pointer meant to point to `s`
//! slice: NonNull<String>,
//! // Obligatory marker that makes this struct `!Unpin`.
//! // Without this, implementing `FromUnpinned` for `Unmovable` would not be safe.
//! _pinned: PhantomPinned,
//! }
//! ```
//!
//! It is important to note that this struct is **not** unmovable by itself, as there are no such types in Rust.
//! Instead, we are going to enforce this through privacy: since the fields of the struct are private, no instance can be created
//! from outside the module.
//! Similarly, no public "constructor" function `pub fn new() -> Unmovable` should be provided.
//!
//! So, how will clients consume `Unmovable` instances?
//!
//! The recommended solution using `stackpin` is to implement `FromUnpinned<Data>` for `Unmovable`, where `Data` is the
//! type that would normally serve as parameters in a "constructor" function.
//! ```
//! # use std::marker::PhantomPinned;
//! # use std::ptr::NonNull;
//! # struct Unmovable {
//! # s: String,
//! # slice: NonNull<String>,
//! # _pinned: PhantomPinned,
//! # }
//! use stackpin::FromUnpinned;
//! // An `Unmovable` can be created from a `String`
//! unsafe impl FromUnpinned<String> for Unmovable {
//! // This associated type can be used to retain information between the creation of the instance and its pinning.
//! // This allows for some sort of "two-steps initialization" without having to store the initialization part in the
//! // type itself.
//! // Here, we don't need it, so we just set it to `()`.
//! type PinData = ();
//!
//! // Simply builds the Unmovable from the String.
//! // The implementation of this function is not allowed to consider that the type won't ever move **yet**.
//! // (in particular, the `Self` instance is returned by this function)
//! // Note, however, that safe users of FromUnpinned will:
//! // * Not do anything to with the returned `Self` instance between the call to
//! // `from_unpinned` and the call to `on_pin`.
//! // * Not panic between calling the two functions
//! // * Always call the second function if the first has been called.
//! unsafe fn from_unpinned(s: String) -> (Self, ()) {
//! (
//! Self {
//! s,
//! // We will "fix" this dangling pointer once the data will be pinned
//! // and guaranteed not to move anymore.
//! slice: NonNull::dangling(),
//! _pinned: PhantomPinned,
//! },
//! (),
//! )
//! }
//!
//! // Performs a second initialization step on an instance that is already guaranteed to never move again.
//! // This allows to e.g. set self borrow with the guarantee that they will remain valid.
//! unsafe fn on_pin(&mut self, _data: ()) {
//! // Data will never move again, set the pointer to our own internal String whose address
//! // will never change anymore
//! self.slice = NonNull::from(&self.s);
//! }
//! }
//! ```
//! With `FromUnpinned<Data>` implemented for `T`, one can now add a "constructor method" that would return an
//! `Unpinned<Data, T>`. The `Unpinned<U, T>` struct is a simple helper struct around `U` that maintains the destination
//! type `T`. This is used by the [`stack_let`] macro to infer the type of `T` that the user may want to produce.
//!
//! ```
//! # use std::marker::PhantomPinned;
//! # use std::ptr::NonNull;
//! # struct Unmovable {
//! # s: String,
//! # slice: NonNull<String>,
//! # _pinned: PhantomPinned,
//! # }
//! # use stackpin::Unpinned;
//! # use stackpin::FromUnpinned;
//! # unsafe impl FromUnpinned<String> for Unmovable {
//! # type PinData = ();
//! # unsafe fn from_unpinned(s: String) -> (Self, ()) {
//! # (
//! # Self {
//! # s,
//! # slice: NonNull::dangling(),
//! # _pinned: PhantomPinned,
//! # },
//! # (),
//! # )
//! # }
//! # unsafe fn on_pin(&mut self, _data: ()) {
//! # self.slice = NonNull::from(&self.s);
//! # }
//! # }
//! impl Unmovable {
//! fn new_unpinned<T: Into<String>>(s: T) -> Unpinned<String, Unmovable> {
//! Unpinned::new(s.into())
//! }
//! }
//! ```
//!
//! Then, a user of the `Unmovable` struct can simply build an instance by using the [`stack_let`] macro:
//! ```
//! # use std::marker::PhantomPinned;
//! # use std::ptr::NonNull;
//! # struct Unmovable {
//! # s: String,
//! # slice: NonNull<String>,
//! # _pinned: PhantomPinned,
//! # }
//! # use stackpin::Unpinned;
//! # use stackpin::FromUnpinned;
//! # unsafe impl FromUnpinned<String> for Unmovable {
//! # type PinData = ();
//! # unsafe fn from_unpinned(s: String) -> (Self, ()) {
//! # (
//! # Self {
//! # s,
//! # slice: NonNull::dangling(),
//! # _pinned: PhantomPinned,
//! # },
//! # (),
//! # )
//! # }
//! # unsafe fn on_pin(&mut self, _data: ()) {
//! # self.slice = NonNull::from(&self.s);
//! # }
//! # }
//! # impl Unmovable {
//! # fn new_unpinned<T: Into<String>>(s: T) -> Unpinned<String, Unmovable> {
//! # Unpinned::new(s.into())
//! # }
//! # }
//! use stackpin::stack_let;
//! // ...
//! stack_let!(unmovable = Unmovable::new_unpinned("Intel the Beagle")); // this creates the unmovable instance on the stack and binds `unmovable` with a `PinStack<Unmovable>`
//! // ...
//! ```
//!
//! [pin-utils]: https://docs.rs/pin-utils
//! [`StackPinned`]: struct.StackPinned.html
//! [`StackPinned<T>`]: struct.StackPinned.html
//! [`FromUnpinned`]: trait.FromUnpinned.html
//! [`stack_let`]: macro.stack_let.html
//! [`PinStack`]: type.PinStack.html
//! [`PinStack<T>`]: type.PinStack.html
//! [`Unpinned`]: struct.Unpinned.html
//! [`!Unpin`]: https://doc.rust-lang.org/std/pin/index.html#unpin
use PhantomData;
use Deref;
use DerefMut;
use Pin;
/// Struct that represents data that is pinned to the stack, at the point of declaration.
///
/// Because this property cannot be guaranteed by safe rust, constructing an instance of a
/// [`StackPinned`] directly is `unsafe`.
/// Rather, one should use the [`stack_let`] macro that returns a [`PinStack`] instance.
///
/// In particular, one should note the following about [`StackPinned`] instance:
/// * It is impossible to safely pass a [`StackPinned`] instance to a function
/// * It is impossible to safely return a [`StackPinned`] instance from a function
/// * It is impossible to safely store a [`StackPinned`] instance inside of a struct
///
/// Instead, one should replace [`StackPinned<T>`] with [`PinStack<T>`] in each of these situations.
///
/// A [`PinStack<T>`] instance does have its benefits:
/// * The underlying `T` instance is guaranteed to never move for `T: !Unpin` once pinned.
/// This is useful for `T` types whose instances should never move.
/// * For `T: !Unpin`, the destructor of `T` is guaranteed to run when the T leaves the stack frame it was allocated on,
/// even if one uses [`std::mem::forget`](https://doc.rust-lang.org/std/mem/fn.forget.html) on
/// the [`PinStack<T>`] instance.
///
/// [`StackPinned`]: struct.StackPinned.html
/// [`StackPinned<T>`]: struct.StackPinned.html
/// [`PinStack`]: type.PinStack.html
/// [`PinStack<T>`]: type.PinStack.html
/// [`stack_let`]: macro.stack_let.html
;
/// Trait to build [`StackPinned`] values from unpinned types.
///
/// Implementers of `FromUnpinned<Source>` indicate that they can be built from a `Source` instance,
/// to the condition that they will be pinned afterwards.
///
/// # Safety
///
/// This trait both exposes unsafe functions **and** is unsafe to implement.
/// * Unsafe functions are exposed because the functions have the preconditions of having to be
/// called from the [`stack_let`] macro.
/// * The trait itself is unsafe to implement because implementers must provide implementations of
/// the functions that must uphold invariants that cannot be checked by the compiler. See the
/// documentation of each function for information on the invariants.
///
/// [`stack_let`]: macro.stack_let.html
/// [`StackPinned`]: struct.StackPinned.html
pub unsafe
/// A helper struct around `U` that remembers the `T` destination type.
///
/// This struct is typically used to build [`PinStack`] values using the [`stack_let`] macro
/// without having to specify the destination type.
///
/// # Example
///
/// ```
/// # use std::marker::PhantomPinned;
/// # use std::ptr::NonNull;
/// # struct Unmovable {
/// # s: String,
/// # slice: NonNull<String>,
/// # _pinned: PhantomPinned,
/// # }
/// # use stackpin::Unpinned;
/// # use stackpin::FromUnpinned;
/// # unsafe impl FromUnpinned<String> for Unmovable {
/// # type PinData = ();
/// # unsafe fn from_unpinned(s: String) -> (Self, ()) {
/// # (
/// # Self {
/// # s,
/// # slice: NonNull::dangling(),
/// # _pinned: PhantomPinned,
/// # },
/// # (),
/// # )
/// # }
/// # unsafe fn on_pin(&mut self, _data: ()) {
/// # self.slice = NonNull::from(&self.s);
/// # }
/// # }
/// use stackpin::stack_let;
/// // Without `Unpinned`
/// fn new_string(s : impl Into<String>) -> String { s.into() }
/// stack_let!(unmovable : Unmovable = new_string("toto"));
/// // With `Unpinned`
/// fn new_unpinned(s : impl Into<String>) -> Unpinned<String, Unmovable> { Unpinned::new(s.into()) }
/// stack_let!(unmovable = new_unpinned("toto"));
/// ```
///
/// [`stack_let`]: macro.stack_let.html
/// [`PinStack`]: type.PinStack.html
unsafe
pub unsafe
pub unsafe
pub unsafe
pub unsafe
/// `stack_let!(id = expr)` binds a [`PinStack<T>`] to `id` if `expr` is an expression of type `U` where [`T: FromUnpinned<U>`].
///
/// If `expr` is of type [`Unpinned<U, T>`] for some `U`, then no type annotation is necessary.
/// If `expr` is of type `U` where [`T: FromUnpinned<U>`], use `stack_let!(id : T = expr)`.
///
/// To bind `id` mutably, use `stack_let!(mut id = expr)`.
///
/// [`PinStack<T>`]: type.PinStack.html
/// [`T: FromUnpinned<U>`]: trait.FromUnpinned.html
/// [`Unpinned<U, T>`]: struct.Unpinned.html
/// Short-hand for `Pin<StackPinned<T>>`
pub type PinStack<'a, T> = ;