Search code examples
swiftswift3unsafe-pointers

Trouble converting extension on Data to Swift 3.1 and UnsafeRawPointer


I am updating a swift 2.3 project to 3.1 and I am running into an issue converting this function, specifically on one line.

This is in an extension on Data.

public func read<T: BinaryReadable>(offset f_offset: inout Int,
                                    byteOrder: ByteOrder = .HostByteOrder) -> T? {
    // Validate the specified offset boundary.
    guard self.count >= (f_offset + MemoryLayout<T>.size) else {
        return nil
    }

    //let dataPtr = Unsas
    // Get data pointer at offset location.

    // TROUBLE CONVERTING THIS LINE
    let dataPtr = UnsafePointer<UInt8>(bytes).advancedBy(f_offset)

    // Increment the offset position.
    f_offset += MemoryLayout<T>.size

    // Read data from offset location and return in specified endianess.
    let retVal = UnsafeRawPointer(dataPtr).load(as: T.self)
    return (byteOrder == .littleEndian) ? retVal.littleEndian : retVal.bigEndian
}

I can't seem to get the line

let dataPtr = UnsafePointer<UInt8>(bytes).advancedBy(f_offset)

to convert to using an UnsafeRawPointer. I have tried too many to list here with no success (compile errors).

What would be the proper syntax?


Solution

  • The withUnsafeBytes() method of Data gives access to the bytes, and the load() method of UnsafeRawPointer takes an optional byte offset argument:

    let retVal = self.withUnsafeBytes {
        UnsafeRawPointer($0).load(fromByteOffset: f_offset, as: T.self)
    }
    

    But note that this assumes (as does your original code) that the memory address is properly aligned for the type T.