"ToOwnedBox": possible solutions?

#1

I’m currently working on an API that would benefit from having a Borrow alternative that uses boxed slices as the owned target rather than vectors. (So &[T] => Box<[T]>, &str => Box<str>, AlreadyOwned => AlreadyOwned, with the possibility of probably into_boxed_sliceing String and Vec.)

Basically, I want to make a mapping that stores immutable values, so I don’t need to pay for the grow ability of String/Vec. Is there a way to do this that doesn’t provide special wrappers or entry points for these types? (Ideally, it’d work for any 'static data and its borrowed format, not just those defined in std.)

#2

Why can you do slice.to_vec().into_boxed_slice() or string.to_string().into_boxed_str()? When you use to_vec or to_string it only allocates as much memory as needed to store the slice or str

You could create a trait to do this

trait ToBoxed {
    fn to_boxed(&self) -> Box<Self>;
}

impl<T: Clone> ToBoxed for [T] {
    fn to_boxed(&self) -> Box<Self> {
       self.to_vec().into_boxed_slice()
    }
}

impl ToBoxed for str {
    fn to_boxed(&self) -> Box<Self> {
       self.to_string().into_boxed_str()
    }
}

https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=9a8eeea6253eee96f0fdcaf109b58350

2 Likes
#3

I… expected it to be more complicated than that.

Just add a type Boxed and a impl<T: Clone> { type Boxed=T; }, and you’ve got the perfect ToOwned variant (modulo other people’s ToOwned implementations, but that’s a reasonable limitation, I guess).

https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=86758b78682404732bfb09cf8d3f0a5f