Once https://github.com/rust-lang/rfcs/pull/2349 hits stable, it'd be very useful to be able to declare various C types as immovable, especially self referential types.
I'd be happy to work on this once the feature lands!
This would be really useful, indeed. I'm happy to mentor something like this :)
Notice that pinning does not declare a type itself immovable, but it lets methods declare that they may only be called on instances of the type that will not be moved again. That's a subtle difference. I do not know what bindgen needs though :)
That's what Unpin is for. Assuming I'm reading the RFC correctly, the generated code would look like
pub struct ImmovableType {...}
impl !Unpin for ImmovableType {}
Without the Unpin marker trait, an ImmovableType wouldn't be able to be moved. You'd then use PinBox to place the struct onto the heap.
Not quite, Unpin actually declares that you are allowed to move that type even when it's been passed via Pin, it being implemented or not doesn't affect you when you have an instance of the type directly.
If anyone could link to a small example of some C header that uses self-referential types or in some other way should be immovable I would be interested in seeing if there is some way to encode this using Pin. I have some experience with using Pin for embedded development now so I feel I could probably come up with something.
In my example
impl !Unpin for ImmovableType {}
the !Unpin represents a negative trait impl which should opt ImmovableType out of the automatic Unpin implementation. This will make it immovable.
impl !Unpin does not mean unmovable. The trait is called Unpin and not Move for a reason.
So, the following is legal code:
pub struct ImmovableType {...}
impl !Unpin for ImmovableType {}
fn foo(x: ImmovableType) {
let y = Box::new(x); // move x into a box
}
The guarantee provided by Pin is that if you have a Pin<ImmovableType> (which is a reference), then you know the target of that reference will not be moved, ever.
That makes sense. Thank you for the clarification.
Good article @RalfJung
https://www.ralfj.de/blog/2018/04/05/a-formal-look-at-pinning.html
Most helpful comment
This would be really useful, indeed. I'm happy to mentor something like this :)