Skip to content

Instantly share code, notes, and snippets.

@sandersaares
Created November 6, 2024 08:25
Show Gist options
  • Save sandersaares/22732af43d140c967f09016c13284882 to your computer and use it in GitHub Desktop.
Save sandersaares/22732af43d140c967f09016c13284882 to your computer and use it in GitHub Desktop.
pins-in-rust-01
// BAD CODE: This example is intentionally wrong.
pub struct BagOfApples {
count: usize,
// In the example code, this self-reference is mostly useless.
// This is just to keep the example code simple - the emphasis is
// on the effects of pinning, not why a type may be designed to need it.
self_reference: *mut BagOfApples,
}
impl BagOfApples {
pub fn new() -> Self {
BagOfApples {
count: 0,
// We cannot set this here because we have not yet
// created the BagOfApples - there is nothing to reference.
self_reference: ptr::null_mut(),
}
}
/// Call this after creating a BagOfApples to initialize the instance.
pub fn initialize(&mut self) {
self.self_reference = self;
}
pub fn count(&self) -> usize {
assert!(
!self.self_reference.is_null(),
"BagOfApples is not initialized"
);
// SAFETY: Simple read-only access to the count field, which
// is safe. We do it via the pointer for example purposes.
unsafe { (*self.self_reference).count }
}
}
// BAD CODE: This example is intentionally wrong.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment