rust-lang / wg-allocators

Home of the Allocators working group: Paving a path for a standard set of allocator traits to be used in collections!
http://bit.ly/hello-wg-allocators
203 stars 9 forks source link

Can one Borrow Vec<T, A> as [T]? #96

Closed yanchith closed 1 year ago

yanchith commented 2 years ago

Hello, my favorite Rust WG :))

At least as of nightly-2022-02-20, Vec<T, A> does not borrow as [T], only Vec<T, Global> does.

From src/alloc/slice.rs:

#[stable(feature = "rust1", since = "1.0.0")]
impl<T> Borrow<[T]> for Vec<T> {
    fn borrow(&self) -> &[T] {
        &self[..]
    }
}

Which I guess could be:

#[stable(feature = "rust1", since = "1.0.0")]
impl<T, A: Allocator> Borrow<[T]> for Vec<T, A> {
    fn borrow(&self) -> &[T] {
        &self[..]
    }
}

Is this just a missing feature, or is there something fundamental afoot here?

(Need this for querying a hashmap with keys that are ~String<A>~ Vec<u8, A>... btw anything I can do to make String<A> happen?)

Lokathor commented 2 years ago

At the language level, yes this is absolutely possible. A slice has nothing to do with the allocator its memory might have come from, so Borrow can be generic over all allocators.

The fact that it isn't written this way yet is just that the standard library hasn't developed enough.

SimonSapin commented 2 years ago

The implementation is based on Index<RangeFull>, which is implemented for all allocator types:

https://doc.rust-lang.org/1.59.0/src/alloc/vec/mod.rs.html#2515-2522

impl<T, I: SliceIndex<[T]>, A: Allocator> Index<I> for Vec<T, A> {

So I would expect no issue with your proposed changed. Feel free to send a PR.

yanchith commented 2 years ago

Thanks! I haven't done any PRs to rust-lang/rust yet, but I'll try and make it happen in the near future :)

yanchith commented 1 year ago

This got merged a few hours ago, closing