A crate on crates.io doesn't provide .as_mut() or . borrow_mut(), since such crate is published by other people, it's not comfortable or necessary to publish a modified crate. E.g, if I implement a type with only AsRef, no implementation returns mutable reference:
struct N([u8; 3]);
impl Default for N {
fn default() -> N {
N([0u8; 3])
}
}
impl AsRef<[u8; 3]> for N {
fn as_ref(&self) -> &[u8; 3] {
&self.0
}
}
Such situation may occur in a crate published on crates.io, it doesn't provide.as_mut() or .borrow_mut() so it's troublesome to publish a modified crate by myself. To forcibly convert the returned reference from a crate published by another person, I considered about such code:
fn main() {
let n = N::default();
/*1st implementation*/
let r = &mut { *n.as_ref() };
/*unsafe implementation*/
let u = &mut unsafe { *(n.as_ref() as *const [u8; 3] as *mut [u8; 3]) };
}
There are safe and unsafe implementation, do they have the same runtime speed?
2 posts - 2 participants