-
Notifications
You must be signed in to change notification settings - Fork 787
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
refactor: use ptr_from_ref
and ptr .cast()
#4240
Conversation
6cdbc75
to
d6ea3c1
Compare
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Thanks, I much prefer this as well.
Also, we can use https://doc.rust-lang.org/std/primitive.pointer.html#method.cast_mut when we bump msrv next time :)
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Very nice, I like this a lot!
Yes, as well as |
…tr_from_ref` added in PR PyO3#4240. Updated `PyRefMut::as_super` to use this method instead of `as *mut _`.
* Added `PyRef::as_super` and `PyRefMut::as_super` methods, including docstrings and tests. The implementation of these methods also required adding `#[repr(transparent)]` to the `PyRef` and `PyRefMut` structs. * Added newsfragment entry. * Changed the `AsRef<U>`/`AsMut<U>` impls for `PyRef` and `PyRefMut` to use the new `as_super` methods. Added the `PyRefMut::downgrade` associated function for converting `&PyRefMut` to `&PyRef`. Updated tests and docstrings to better demonstrate the new functionality. * Fixed newsfragment filename. * Removed unnecessary re-borrows flagged by clippy. * retrigger checks * Updated `PyRef::as_super`, `PyRefMut::as_super`, and `PyRefMut::downgrade` to use `.cast()` instead of `as _` pointer casts. Fixed typo. * Updated `PyRef::as_super` and `PyRefMut::downgrade` to use `ptr_from_ref` for the initial cast to `*const _` instead of `as _` casts. * Added `pyo3::internal_tricks::ptr_from_mut` function alongside the `ptr_from_ref` added in PR #4240. Updated `PyRefMut::as_super` to use this method instead of `as *mut _`. * Updated the user guide to recommend `as_super` for accessing the base class instead of `as_ref`, and updated the subsequent example/doctest to demonstrate this functionality. * Improved tests for the `as_super` methods. * Updated newsfragment to include additional changes. * Fixed formatting. --------- Co-authored-by: jrudolph <jrudolph@anl.gov>
Typically these days I like to use
x.cast::<Y>()
instead ofx as *const Y
to perform pointer casting (and in many contexts it's also convenient to let type inference work on justx.cast()
, which reads a lot nicer thanx as *const _
). It also avoids const <-> mut casting by accident.I just discovered
ptr::from_ref
and am now similarly excited to replace&x as *const X
withptr_from_ref(&x)
.... so this PR is just a few tidy-ups across the codebase!