heap - How can you allocate a raw mutable pointer in stable Rust? -


i trying build naive implementation of custom string-like struct small string optimization. unions allowed in stable rust, came following code:

struct large {     capacity: usize,     buffer: *mut u8, }  struct small([u8; 16]);  union container {     large: large,     small: small, }  struct mystring {     len: usize,     container: container, } 

i can't seem find way how allocate *mut u8. possible in stable rust? looks using alloc::heap work, available in nightly.

if you'd allocate collection of u8 instead of single u8, can create vec , convert constituent pieces, such calling as_mut_ptr:

use std::mem;  fn main() {     let mut foo = vec![0; 1024]; // or vec::<u8>::with_capacity(1024);      let ptr = foo.as_mut_ptr();     let cap = foo.capacity();     let len = foo.len();     mem::forget(foo); // avoid calling destructor!      let foo_again = unsafe { vec::from_raw_parts(ptr, len, cap) }; // rebuild drop     // *not* use `ptr` / `cap` / `len` anymore } 

re allocating bit of pain though; you'd have convert vec , whole dance forwards , backwards

that being said, large struct seems missing length, distinct capacity. use vec instead of writing out. see it's bit in hierarchy.

i wonder if having full string wouldn't lot easier, if bit less efficient in length double-counted...

union container {     large: string,     small: small, } 

see also:


Comments

Popular posts from this blog

node.js - Node js - Trying to send POST request, but it is not loading javascript content -

javascript - Replicate keyboard event with html button -

javascript - Web audio api 5.1 surround example not working in firefox -