4

The question pretty much says it: can I create a boxed tuple (or any struct) that directly contains a slice as one of its fields?

The Vec::into_boxed_slice method works to create Box<[U]>, but I would like to add on some additional data directly in the box alongside the slice.

For example, here is the kind of struct I would like to box up without using Vec into something like Box<(i32,[u8])>:

struct ConsolidateMe {
    data: i32,
    arr: Vec<u8>,
}

impl ConsolidateMe {
    fn new(n: usize) -> Self {
        let mut arr = Vec::with_capacity(n);
        arr.resize(n, 42);
        ConsolidateMe {
            data: 15,
            arr,
        }
    }
}

(In my application, I am creating many structs on the heap, each of which contains a small array and a few other values. The arrays have different sizes, but the size doesn't change after the struct is created. I'd like these to be compactly stored and to avoid extra indirection to the extent possible.)

2
  • 1
    Note that you can't create ([u8], i32) in any way at all, since the dynamically-sized field must be the last - play.rust-lang.org/…. What you seem to want, however, is a way to build (i32, [u8]).
    – Cerberus
    Jan 9, 2021 at 12:55
  • @Cerberus thanks! I didn't know that restriction but it makes sense when I think about the underlying layout. I updated my example accordingly.
    – Dan R
    Jan 9, 2021 at 15:20

1 Answer 1

1

The slice-dst crate looks like a perfect fit.

Example:

use slice_dst::SliceWithHeader;

#[derive(Debug, Clone)]
struct MyType {
    inner: Box<SliceWithHeader<String, i32>>,
}

impl MyType {
    fn new(value: &str) -> Self {
        let values: Vec<i32> = value.split(" ").map(|s| s.trim().parse().unwrap()).collect();
        Self {
            inner: SliceWithHeader::new(value.into(), values.into_iter()),
        }
    }
}

fn main() {
    println!("{:?}", MyType::new("1 2 3"));
}
3
  • Great suggestion. Basically it looks like this crate author did the unsafe work so I don't have to; hooray! My only concern is that the crate doesn't seem that popular and so I'm hesitant about making it a dependency for my project.
    – Dan R
    Jan 9, 2021 at 15:17
  • 1
    The crate author, CAD97, is famous for insightful comments in the official forums, so I personally trust them.
    – pandaman
    Jan 10, 2021 at 16:16
  • And according to slice-dst, which is also made by CAD97 and powers Rust analyzer, slice-dst is the successor. Thus I think it's the safest bet, though it's not "battle-tested" yet.
    – pandaman
    Jan 10, 2021 at 16:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.