Implement buffer pointer's `MutableCollection` methods as nonmutating

Currently this code is not compilable.

func median<T: Comparable>(bp: UnsafeMutableBufferPointer<T>) {
    bp.sort() // error: cannot use mutating member on immutable value: 'bp' is a 'let' constant
    return bp[bp.count/2]
}

It is because sort, defined in MutableColelction, is mutating.

UnsafeMutableBufferPointer has two mutability.

  1. Mutability of itself
  2. Mutability of buffer

If we want to mutate UnsafeMutableBufferPointer itself, we need to make it mutable.
But if we want to mutate only buffer, it doesn't have to be mutable.
mutating denotes the method mutates self, so it's not suitable for UnsafeMutableBufferPointer's sort.

In UnsafeMutableBufferPointer, subscript and swapAt, which mutate only buffer, are implemented as nonmutating .
Other methods, partition, reverse, shuffle, and sort, also mutate only buffer.
So it'll be consistent to make them nonmutating likewise.

What do you think?

Other types:

  • UnsafeMutableRawBufferPointer also has this problem.
  • UnsafeMutableAudioBufferListPointer also has this problem(But it's in CoreAudio).
  • EmptyCollection's methods can be nonmutating since they do nothing.
  • CollectionOfOne's methods, except subscript, also do nothing so they can be nonmutating.
2 Likes

Until this is discussed and decided, you can do var bp2 = bp; bp2.sort(); return bp2[bp2.count/2].

I’m not sure this has been discussed as the main topic of a thread, but it was broached during the light discussion of SE-0237. I suggested giving the UnsafeBufferPointer types a nonmutating interface to MutableCollection, and that was turned down. In the core team’s first evaluation of the proposal, they cited a concern over having too many overloads. It does seem probable that such overloads might not pull their weight.

I know it, of course🙂

I didn't find these posts. It seems your PR contains what I'm suggesting.
Before posting this thread, I thought it would be troublesome to overload all methods. But also thought it's worth discussing which we should take, code simplicity or consistency.