rust

Dynamically sized struct in Arc


I want to create a dynamically sized struct within an Arc, but I can't find a way to do that.

Here's what I'm trying to achieve

struct UnknownSized(usize, [u8]);

fn main() {
    let attached_data: usize = 42;
    let data: Vec<u8> = vec![1, 2, 3, 4, 5]; 

    let arc_object = Arc::new(UnknownSized(attached_data, data)); // Did not work
}

I was expecting just a single level of indirection for this object, rather than using something like a box around a [u8] or wrapping another Arc around a [u8]. No referencing a slice either. i want an owned slice in an Arc with usize. And i want no dependencies either, if possible.


Solution

  • Implementing this by hand is incredibly tricky. Instead, we can lean on the slice-dst crate to take care of the unsafe heavy lifting for us:

    use std::sync::Arc;
    
    use slice_dst::SliceWithHeader;
    
    fn example() -> Arc<SliceWithHeader<usize, u8>> {
        let attached_data: usize = 42;
        let data: Vec<u8> = vec![1, 2, 3, 4, 5];
    
        SliceWithHeader::new(attached_data, data)
    }
    

    This stores the usize along with the u8 data inline.

    In this case the additional data stored with the slice is a single usize, but you can replace usize with a tuple or named struct should you need to store multiple values alongside the u8 data.