Skip to content

Conversation

Copy link

Copilot AI commented Dec 15, 2025

The DynamicBuffer example in the PhantomPinned documentation had a TODO noting that Vec::push may reallocate, invalidating the NonNull<u8> cursor pointer.

Changes

  • Calculate cursor offset before push: Store the cursor position as an offset from the data buffer start using offset_from()
  • Update cursor after push: Reconstruct the cursor pointer at the same logical offset in the potentially reallocated buffer using offset()
  • Add explanatory comments: Document why the offset calculation is necessary for correctness
pub fn push(&mut self, byte: u8) {
    // Calculate the cursor offset before the push (which may reallocate)
    let offset = unsafe {
        self.cursor.as_ptr().offset_from(self.data.as_ptr())
    };
    
    self.data.push(byte);

    // Update cursor to point to the same offset in the (potentially new) buffer
    self.cursor = unsafe {
        NonNull::new_unchecked(self.data.as_mut_ptr().offset(offset))
    };
}

This demonstrates the correct pattern for maintaining a pointer into a dynamically-sized container, which is essential context for understanding when pinning is necessary.

Original prompt

Work on TODO: self.data may have reallocated; ensure that th cursorpoints the the correct place (from src/unsafe-deep-dive/pinning/phantompinned.md)

Created from VS Code via the GitHub Pull Request extension.


✨ Let Copilot coding agent set things up for you — coding agent works faster and does higher quality work when set up for your repo.

- Calculate cursor offset before Vec push operation
- Update cursor after potential reallocation to maintain correct pointer
- Add explanatory comments about the reallocation handling

Co-authored-by: timClicks <27889+timClicks@users.noreply.github.com>
Copilot AI changed the title [WIP] Fix cursor positioning after data reallocation Implement cursor reallocation handling in DynamicBuffer pinning example Dec 15, 2025
Copilot AI requested a review from timClicks December 15, 2025 11:31
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants