Skip to content

Commit

Permalink
Simplified raw memory access helpers
Browse files Browse the repository at this point in the history
  • Loading branch information
dimitribouniol committed Feb 24, 2024
1 parent 7f19882 commit 6d46e85
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 14 deletions.
24 changes: 10 additions & 14 deletions Sources/Bytes/Colletion+Casting.swift
Original file line number Diff line number Diff line change
Expand Up @@ -39,21 +39,17 @@ extension BidirectionalCollection where Element == Byte {
public func casting<R>() throws -> R {
try canBeCasted(to: R.self)

guard
let result = self.withContiguousStorageIfAvailable({
$0.withUnsafeBytes {
$0.baseAddress!.assumingMemoryBound(to: R.self).pointee
}
})
else {
guard self.count <= 4*1024 else { // If bytes is less than 4KB, then perform a copy first
throw BytesError.contiguousMemoryUnavailable(type: "\(Self.self)")
}
return Bytes(self).withUnsafeBytes {
$0.baseAddress!.assumingMemoryBound(to: R.self).pointee
}
if let result = self.withContiguousStorageIfAvailable({
$0.withUnsafeBytes { $0.loadUnaligned(as: R.self) }
}) {
return result
}
return result

/// If bytes is less than 4KB, then perform a copy first
guard self.count <= 4*1024
else { throw BytesError.contiguousMemoryUnavailable(type: "\(Self.self)") }

return Bytes(self).withUnsafeBytes { $0.loadUnaligned(as: R.self) }
}

/// Create a new Bytes sequence from the memory occupied by the passed in value.
Expand Down
6 changes: 6 additions & 0 deletions Tests/BytesTests/IntegerTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,12 @@ final class IntegerTests: XCTestCase {
XCTAssertEqual(try Int64(littleEndianBytes: [0x11, 0x32, 0x54, 0x76, 0x98, 0xba, 0xdc, 0xfe]), Int64(-0x0123456789abcdef))
}

func testUnalignedMemoryAccess() throws {
let bytes: Bytes = [0x0, 0x0, 0x0, 0x01, 0x23, 0x45, 0x67, 0x0]

XCTAssertEqual(try UInt32(bigEndianBytes: bytes.dropFirst(3).dropLast()), UInt32(0x01234567))
}

func testInvalidBytes() throws {
XCTAssertThrowsError(try UInt8(bigEndianBytes: [])) {
BytesError.testInvalidMemorySize($0, targetSize: 1, targetType: "UInt8", actualSize: 0)
Expand Down

0 comments on commit 6d46e85

Please sign in to comment.