I want to be able to use the UnsafeRawBufferPointer.load(fromByteOffset:as:) method to read a number of bytes from a [UInt8] array and their corresponding type as an UnsignedInteger, FixedWidthInteger at each read.
In both approaches that follow, a "Fatal error: load from misaligned raw pointer" exception is raised, since load expects the underlying data to be aligned in memory.
I have tried using a ContiguousArray
Allocating and initialising a UnsafeMutablePointer
Can you please point out where my misunderstanding lies in each and provide a working example?
In both approaches that follow, a "Fatal error: load from misaligned raw pointer" exception is raised, since load expects the underlying data to be aligned in memory.
I have tried using a ContiguousArray
Code Block var words: ContiguousArray<UInt8> = [0x01, 0x00, 0x03, 0x0a, 0x00, 0x01, 0x00, 0xec, 0xfa, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x7c, 0x20, 0x00, 0x00, 0xe0, 0x88, 0x47, 0xa3, 0xd6, 0x6b, 0xd6, 0x01, 0x4c, 0xff, 0x08] var offset = 0 let byte = words.withUnsafeBytes { $0.load(fromByteOffset: offset, as: UInt8.self) } offset += MemoryLayout<UInt8>.size let bytes = words.withUnsafeBytes { $0.load(fromByteOffset: offset, as: UInt16.self) } XCTAssertEqual(byte, UInt8(littleEndian: 0x01)) XCTAssertEqual(bytes, UInt16(littleEndian: 0x0003))
Allocating and initialising a UnsafeMutablePointer
Code Block var words: [UInt8] = [0x01, 0x00, 0x03, 0x0a, 0x00, 0x01, 0x00, 0xec, 0xfa, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x7c, 0x20, 0x00, 0x00, 0xe0, 0x88, 0x47, 0xa3, 0xd6, 0x6b, 0xd6, 0x01, 0x4c, 0xff, 0x08] let uint8Pointer = UnsafeMutablePointer<UInt8>.allocate(capacity: words.count) uint8Pointer.initialize(from: &words, count: words.count) let rawPointer = UnsafeMutableRawPointer(uint8Pointer) var offset = 0 let byte = UInt8(bigEndian: rawPointer.load(fromByteOffset: offset, as: UInt8.self)) offset += MemoryLayout<UInt8>.size let bytes = UInt16(bigEndian: rawPointer.load(fromByteOffset: offset, as: UInt16.self)) rawPointer.deallocate() uint8Pointer.deinitialize(count: words.count) XCTAssertEqual(byte, UInt8(littleEndian: 0x01)) XCTAssertEqual(bytes, UInt16(littleEndian: 0x0003))
Can you please point out where my misunderstanding lies in each and provide a working example?