[swift-evolution] [Pitch] Normalize Slice Types for Unsafe Buffers

Andrew Trick atrick at apple.com
Fri Dec 9 13:00:59 CST 2016


> On Dec 9, 2016, at 10:22 AM, Dave Abrahams <dabrahams at apple.com> wrote:
> 
> 
> on Thu Dec 08 2016, Jordan Rose <jordan_rose-AT-apple.com> wrote:
> 
>>> On Dec 8, 2016, at 16:22, Andrew Trick via swift-evolution <swift-evolution at swift.org> wrote:
>>> In practice, it needs to be able to interoperate with [UInt8] and be interchangeable in the same
>> generic context.
>>> e.g. `byteBuffer += rawBuffer[payloadIndex..<endIndex]` is typical.
>>> I think Sequence is sufficient for that purpose.
>> 
>> Um, Sequence doesn’t have a subscript (or indexes). Sequences are single-pass. So if this is
>> important, it needs to stay a Collection.
> 
> Yes.  But I don't see why the raw buffer should be a collection in the first place.  Why not
> 
> byteBuffer += rawBuffer.bytes[payloadIndex..<endIndex]
> 
> ?
> 
> -- 
> -Dave

`RawBytes : Collection` could be a view over the raw buffer with `SubSequence : RandomAccessSlice<RawBytes>` if that's what you mean.

I hadn’t considered that just because it’s yet another type that needs to be introduced. Now interface authors need to decide whether they want to take a collection of bytes or a buffer. (In a non-generic context, the correct answer is to pass the buffer, not the collection--the collection would be just a convenient temporary view).

We still need an initializer or extension to handle the expected use case of nested buffers:

extension RandomAccessSlice where Base == RawBytes {
    var rebased: UnsafeRawBufferPointer {
        return UnsafeRawBufferPointer(start: base.baseAddress, count: count)
    }
}

I would even be willing to eliminate raw buffer subscripting altogether, which I think is what you're getting at, since this isn't too awful:

`buffer.bytes[i]`

Pro: More explicit division between raw memory semantics and Collection semantics.

Con: Raw buffer users need to juggle two different types and know how convert between them.

-Andy


More information about the swift-evolution mailing list