Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Raw Memory #36

Merged
merged 2 commits into from
Feb 24, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ Please check the [releases](https://github.com/mochidev/Bytes/releases) for reco

```swift
dependencies: [
.package(url: "https://github.com/mochidev/Bytes.git", .upToNextMinor(from: "0.2.2")),
.package(url: "https://github.com/mochidev/Bytes.git", .upToNextMinor(from: "0.3.1")),
],
...
targets: [
Expand Down
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
Loading