Skip to content

Commit

Permalink
Add UnsafePointer extension (#139)
Browse files Browse the repository at this point in the history
  • Loading branch information
Kyle-Ye authored Oct 7, 2024
1 parent 1129537 commit 70fe2d9
Show file tree
Hide file tree
Showing 2 changed files with 66 additions and 0 deletions.
49 changes: 49 additions & 0 deletions Sources/OpenSwiftUICore/Util/UnsafePointer+Extension.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
//
// UnsafePointer+Extension.swift
// OpenSwiftUICore
//
// Audited for RELEASE_2024
// Status: Complete

extension UnsafePointer {
package subscript() -> Pointee {
@_transparent
unsafeAddress {
self
}
}

@_transparent
package static var null: UnsafePointer<Pointee> {
UnsafePointer(bitPattern: Int(bitPattern: 0xffff_ffff_ffff_ff00) | (-MemoryLayout<Pointee>.alignment))!
}
}

extension UnsafeMutablePointer {
package subscript() -> Pointee {
@_transparent
unsafeAddress { UnsafePointer(self) }
@_transparent
nonmutating unsafeMutableAddress { self }
}

@_transparent
package static var null: UnsafeMutablePointer<Pointee> {
UnsafeMutablePointer(bitPattern: Int(bitPattern: 0xffff_ffff_ffff_ff00) | (-MemoryLayout<Pointee>.alignment))!
}
}

extension UnsafeBufferPointer {
@_transparent
package var startAddress: UnsafePointer<Element> {
baseAddress ?? .null
}
}


extension UnsafeMutableBufferPointer {
@_transparent
package var startAddress: UnsafeMutablePointer<Element> {
baseAddress ?? .null
}
}
17 changes: 17 additions & 0 deletions Tests/OpenSwiftUICoreTests/Util/UnsafePointer+ExtensionTests.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
//
// UnsafePointer+ExtensionTests.swift
// OpenSwiftUICoreTests

import Testing
import OpenSwiftUICore

struct UnsafePointer_ExtensionTests {
@Test
func nullPointer() {
#expect(UnsafePointer<Int64>.null == UnsafePointer(bitPattern: Int(bitPattern: 0xffff_ffff_ffff_fff8)))
#expect(UnsafePointer<Int32>.null == UnsafePointer(bitPattern: Int(bitPattern: 0xffff_ffff_ffff_fffc)))
#expect(UnsafePointer<Int16>.null == UnsafePointer(bitPattern: Int(bitPattern: 0xffff_ffff_ffff_fffe)))
#expect(UnsafePointer<Int8>.null == UnsafePointer(bitPattern: Int(bitPattern: 0xffff_ffff_ffff_ffff)))
#expect(UnsafePointer<Bool>.null == UnsafePointer(bitPattern: Int(bitPattern: 0xffff_ffff_ffff_ffff)))
}
}

0 comments on commit 70fe2d9

Please sign in to comment.