Skip to content

Instantly share code, notes, and snippets.

@pidb
Created November 23, 2021 15:24
Show Gist options
  • Save pidb/82efde7433b3967e704375c38a11570f to your computer and use it in GitHub Desktop.
Save pidb/82efde7433b3967e704375c38a11570f to your computer and use it in GitHub Desktop.
slice and raw pointer mututal conversions in rust
#![allow(unused)]
fn to_mut_ptr(data: Vec<u8>) -> *mut u8 {
unsafe { data.to_owned().as_mut_ptr() }
}
fn main() {
let s = String::from("hello world");
let mut storage = vec![0; s.len()];
storage.fill(0);
let storage_mut_ptr = to_mut_ptr(storage);
unsafe {
std::ptr::copy_nonoverlapping(s.as_bytes().as_ptr(), storage_mut_ptr, s.len());
}
unsafe {
let storage_mut_slice = std::slice::from_raw_parts_mut(storage_mut_ptr, s.len());
println!("{}", std::str::from_utf8_unchecked(&storage_mut_slice[..]));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment