How to write function that takes Array or ArraySlice and access withUnsafeBufferPointer

I am trying to write a function that takes an Array<UInt8> or ArraySlice<UInt8> as an argument.

My function needs to call withUnsafeBufferPointer. Both Array and ArraySlice implements this function but I cannot find if they both conform to a protocol that implements this.


The function would look something like this:

func someFunction<T: RandomAccessCollection>(bytes: T) -> UInt8 where T.Element == UInt8 {
  bytes.withUnsafeBufferPointer({
    return $0.count
  })
}


In this case I am using RandomAccesCollection since both Array and ArraySlice conforms to it, but it is not the protocol that specifies withUnsafeBufferPointer.


Any idea what I should use instead of RandomAccesCollection, or should I take a completely differnet approacy? One that I thought about was to create a new protocol that specifies withUnsafeBufferPointer and to then have both Array and ArraySlice conform to it, but it feels to be like this should have already been done.


Thanks.

Accepted Reply

As far as I know, there's no protocol declaring `withUnsafeBufferPointer`.


You may need to define it yourself:

protocol UnsafeBuferPointerType {
    associatedtype Element
   
    func withUnsafeBufferPointer(_ body: (UnsafeBufferPointer) throws -> R) rethrows -> R
}

extension Array: UnsafeBuferPointerType {}
extension ArraySlice: UnsafeBuferPointerType {}

func someFunction(bytes: T) -> Int where T.Element == UInt8 {
    return bytes.withUnsafeBufferPointer {
        return $0.count
    }
}


If your main intention is to say it feels to be like this should have already been done in the Swift Standard Library, better visit swift.org .

Replies

As far as I know, there's no protocol declaring `withUnsafeBufferPointer`.


You may need to define it yourself:

protocol UnsafeBuferPointerType {
    associatedtype Element
   
    func withUnsafeBufferPointer(_ body: (UnsafeBufferPointer) throws -> R) rethrows -> R
}

extension Array: UnsafeBuferPointerType {}
extension ArraySlice: UnsafeBuferPointerType {}

func someFunction(bytes: T) -> Int where T.Element == UInt8 {
    return bytes.withUnsafeBufferPointer {
        return $0.count
    }
}


If your main intention is to say it feels to be like this should have already been done in the Swift Standard Library, better visit swift.org .

Thanks, that is what I did but I was hoping that there were already a Protocol that I was overlooking.


For correctness, the code above missed the generic return type:


protocol UnsafeBuferPointerType {
  associatedtype Element
  
  func withUnsafeBufferPointer<R>(_ body: (UnsafeBufferPointer<Element>) throws -> R) rethrows -> R
}

Thanks for correction. It's lost because I pasted the code before using `<>`. Anyway if you think this sort of feature is needed, you can start a discussion in swift.org. Please visit forums.swift.org .