Or is there any more conscise way? (edit: I mean with a single type alias, for example. Of course I could use Vec<u8> instead of <Content as ToOwned>::Owned) And how do I name these? Content/OwnedContent? Or Content/ContentBuf?
I thought on this too, but in my case, the OwnedContent will usually not serve to build (buffer) the content, but more to serve as keeping the content allocated . This makes me wonder if semantically, I have more something like this:
The trade-off of Box<[u8]> vs Vec<u8> — in settings where you'll never (or at least rarely) need to further grow or shrink the value — should generally be that creatingBox<[u8]> (usually from a Vec<u8>) will involve another reallocation, unless the Vec had exactly the right capacity to begin with, while in the other hand, the fact that excess capacity is removed can be seen as a way to limit wasted memory. If using shrink_to_fit seemed like a reasonable (memory usage) optimization in your use case, then a boxed slice could also be reasonable.
I don't really think using Box is worth it in my case. But out of curiosity, wouldn't it be possible to create a Box<[u8]> from a Vec<u8> without reallocation by "wasting" the excess memory, yet saving the memory for the capacity information? (assuming that the memory allocator doesn't need to know the length, as free in C also doesn't need to know the length)
The thing I'm "annoyed" with is that (disregarding memory storage) I have to use two types to describe the exact same thing (similar to Path/PathBuf, str/String, etc). But I think that's the way to go in Rust.
Perhaps I'm missing some syntax like this:
pub type Id = u64;
pub type Content = [u8];
macro_rules! owned {
($type:tt) => { <$type as ::std::borrow::ToOwned>::Owned };
}
pub fn foo(_content: &Content) -> owned!(Id) {
todo!()
}
pub fn bar(_id: &Id) -> owned!(Content) {
todo!()
}
This assumption doesn't hold in Rust. Whenever you call dealloc(), you need to pass a pointer and the Layout of your allocation (i.e. alignment and size). Passing in the incorrect length (the overall allocation would be a Vec's capacity, but Box<[u8]> only has access to the len) will probably cause the allocator implementation to have a bad time.