[swift-evolution] Proposal: Add Initializers For Converting UnsafePointers to Int and Unit

Michael Buckley michael at buckleyisms.com
Tue Dec 8 21:54:48 CST 2015


UnsafePointer and UnsafeMutablePointer both contain initializers to convert
from Int and Uint, but Int and UInt lack initializers to convert from
UnsafePointer and UnsafeMutablePointer. Over in swift-dev, Dimitri Gribenko
proposed adding something like the following initializers to stdlib.

extension UInt {
  init<T>(bitPattern: UnsafePointer<T>) {
    self = UInt(Builtin.ptrtoint_Word(bitPattern._rawValue))
  }

  init<T>(bitPattern: UnsafeMutablePointer<T>) {
    self = UInt(Builtin.ptrtoint_Word(bitPattern._rawValue))
  }
}

extension Int {
  init<T>(bitPattern: UnsafePointer<T>) {
    self = Int(Builtin.ptrtoint_Word(bitPattern._rawValue))
  }

  init<T>(bitPattern: UnsafeMutablePointer<T>) {
    self = Int(Builtin.ptrtoint_Word(bitPattern._rawValue))
  }
}

https://bugs.swift.org/browse/SR-131

There are two motivations behind this proposal. First, it would allow more
complicated pointer arithmetic, such as checking pointer alignment. Second,
some C functions take intptr_t and uintptr_t parameters, which are not
compatible with UnsafePointer.

As noted in UnsafePointer.swift.gyb the conversions from UInt and Int are
fundamentally unsafe, and these proposed conversions would also be unsafe.
They would also allow for more unsafe pointer arithmetic operations. For
example, it would allow users to convert two UnsafePointers to UInt8s in
order to find the distance between them, which would be a problem if the
user subtracted the larger pointer from the smaller pointer.

Because of this, and because it's part of the Swift evolution process, it's
worth considering alternatives. Pointer arithmetic could be taken care of
by adding functions to UnsafePointer, and these may be worth proposing
separately. I'm thinking something like this.

func distanceToBoundary(_ boundary: Int) -> Int {
    return Int(Builtin.ptrtoint_Word(self._rawValue)) % boundary
}

func isAlignedToBoundary(_ boundary: Int) -> Bool {
    return distanceToBoundary(boundary) == 0
}

As for intptr_t parameters, the only alternative I can think of is to
require users to write adaptor functions in C. Requiring users to write C
code also works for pointer alignment and other pointer arithmetic, but it
doesn't feel like a great solution to the problem.

Any feedback, additional motivations, or additional alternatives welcome.
Thanks.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20151208/6eedf0e7/attachment.html>


More information about the swift-evolution mailing list