rust-lang / rust

Empowering everyone to build reliable and efficient software.
https://www.rust-lang.org
Other
96.63k stars 12.48k forks source link

Implementing `Alloc` for mutable references to `Alloc` #51509

Open kovaxis opened 6 years ago

kovaxis commented 6 years ago

I don't see why this shouldn't be implemented. It certainly proves useful when working with generic allocators, without requiring a Copy bound on them. For example:

struct AllocWithInternalMutability {
  ...
}

impl<'a> Alloc for &'a AllocWithInternalMutability { ... }

impl AllocWithInternalMutability {
  fn use_self(&self) {
    //Ugly code
    let mut ref_to_self=self;
    use_alloc(&mut ref_to_self);
  }
}

fn use_alloc<A: Alloc>(a: &mut A) {
  //Multiple usages of `A` in here
  a.alloc(...);
  a.dealloc(...);
}

While having an impl<A: Alloc> Alloc for &mut A generic implementation would allow for this instead:

impl AllocWithInternalMutability {
  fn use_self(&self) {
    //Much cleaner
    use_alloc(self);
  }
}

fn use_alloc<A: Alloc>(mut a: A) {
  //Multiple usages of `A` in here, thanks to `&mut A` also implementing `Alloc`
  a.alloc(...);
  a.dealloc(...);
}

The other current option is to require Copy on A, allowing for multiple uses of A without losing ownership.

sfackler commented 6 years ago

Adding an impl for &mut A seems reasonable to me!