• Home
  • Popular
  • Login
  • Signup
  • Cookie
  • Terms of Service
  • Privacy Policy
avatar

Posted by John Dev


08 Jan, 2025

Updated at 20 Jan, 2025

Runtime speed when converting .as_bytes() or .as_ref() to be &mut

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() {
    /*1st implementation*/
    let r = {
        let n = N::default();
        &mut { *n.as_ref() }
    };
    /*unsafe implementation*/
    let u = &mut unsafe { *(N::default().as_ref() as *const [u8; 3] as *mut [u8; 3]) };
}~~~
There are safe and unsafe implementation, do they have the same runtime speed?

7 posts - 3 participants

Read full topic