tokio-rs / bytes

Utilities for working with bytes
MIT License
1.87k stars 278 forks source link

Unable to try_reclaim(..) a BytesMut allocation #620

Open benschulz opened 1 year ago

benschulz commented 1 year ago

bytes_mut.reserve(..) makes the guarantee that the underlying allocation will be reclaimed when bytes_mut is the only remaining handle to it. However, when it isn't the only remaining handle, new space is allocated and the handle to the old allocation is discarded.

BytesMut should offer a method to request that the underlying allocation be reclaimed without discarding the old allocation when the attempt fails. Something along the lines of the following.

impl BytesMut {
  /// Attempts to reclaim the underlying allocation.
  ///
  /// The attempt will succeed iff this is the last remaining handle
  /// to the allocation.
  ///
  /// When the attempt succeeds, an empty `BytesMut` with the full
  /// capacity of the allocation is returned. Otherwise, the original
  /// handle is returned.
  pub fn try_reclaim(self) -> Result<Self, Self>;
}

I'd be happy to implement this proposal and file a PR for it.

bojo-byte commented 1 year ago

I think this is a pretty decent idea.