Bridging Swift Protobuf message.serializedData to ByteBuffer on Linux

I have a class that is used on both macOS/iOS and Linux that uses SwiftNIO to send/receive protobuf objects. On Apple platforms, its simple enough with

let buf = ByteBuffer(data: try protobufMessage.serializedData())

For Linux, this init doesn't exist because Data doesn't exist on Linux IIUC.

error: incorrect argument label in call (have 'data:', expected 'bytes:')
        let buf = ByteBuffer(data: try protobufMessage.serializedData())

Is the only solution here to delve into the Unsafe API to bridge the ByteBuffer?:

try protobufMessage.serializedData().withUnsafeBytes { ptr in
          let buf = ByteBuffer(bytes: ptr)
          // ship the buffer
        }

Add NIOFoundationCompat as a dependency. This will give you the missing initialiser on Linux:
https://swiftpackageindex.com/apple/swift-nio/2.61.1/documentation/niofoundationcompat/niocore/bytebuffer/init(data:)

3 Likes

To add to this, Data is most certainly available on Linux under Foundation

1 Like

I must have been reading an older search result saying it was a thin bridge to NSData which is not available.