-
-
Notifications
You must be signed in to change notification settings - Fork 17
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
Avoid pointer casting #8
Conversation
} | ||
|
||
#[inline] | ||
unsafe fn rebuild(mut ptr: NonNull<Self>, capacity: usize) -> String { | ||
unsafe fn owned_from_parts(mut ptr: NonNull<Self>, capacity: NonZeroUsize) -> String { | ||
String::from_utf8_unchecked(Vec::from_raw_parts( | ||
ptr.as_mut().as_mut_ptr(), |
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.
This should probably be ptr.cast::<u8>().as_raw()
to avoid manifesting (and deriving from) a temporary borrow.
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.
Ended up reading about cast
. TIL casting a fat pointer to a thin pointer is ok.
Vec::from_raw_parts(ptr.as_mut().as_mut_ptr(), ptr.as_mut().len(), capacity) | ||
unsafe fn owned_from_parts(mut ptr: NonNull<Self>, capacity: NonZeroUsize) -> Vec<T> { | ||
Vec::from_raw_parts( | ||
ptr.as_mut().as_mut_ptr(), |
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.
This should probably be ptr.cast::<T>().as_raw()
to avoid manifesting (and deriving from) a temporary borrow.
} | ||
|
||
#[inline] | ||
unsafe fn rebuild(mut ptr: NonNull<Self>, capacity: usize) -> String { | ||
unsafe fn owned_from_parts(mut ptr: NonNull<Self>, capacity: NonZeroUsize) -> String { | ||
String::from_utf8_unchecked(Vec::from_raw_parts( | ||
ptr.as_mut().as_mut_ptr(), | ||
ptr.as_mut().len(), |
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.
If I'm being overcautious, I'd bring the len
call up before the as_mut_ptr
, and do it as ptr.as_ref().len()
. If you want to be super correct, you can write fn slice_len<T>(ptr: NonNull<[T]>) -> usize
to just directly extract the length metadata today: https://discordapp.com/channels/273534239310479360/592856094527848449/688117580040241162
&mut T as *mut T
.Beef::owned_ptr
is no longer marked asunsafe
.