[swift-evolution] [RFC] UnsafeBytePointer API for In-Memory Layout

Andrew Trick atrick at apple.com
Thu May 12 20:51:05 CDT 2016


Responding to this on the swift-evolution thread...
https://github.com/atrick/swift-evolution/blob/voidpointer/proposals/XXXX-unsafebytepointer.md <https://github.com/atrick/swift-evolution/blob/voidpointer/proposals/XXXX-unsafebytepointer.md>

> On May 12, 2016, at 9:27 AM, Jordan Rose <jordan_rose at apple.com> wrote:
> 
> Some concerns with UnsafeBytePointer:
> 
> - I was concerned about having a store() to go with load(). It’s just deinitialize + initialize with a count of 1, but that’s easily the common case when you do need to write to something. That said, I’m not sure which people are more likely to mess up: using initialize and forgetting to deinitialize before, or using store when there wasn’t anything there before.

store() is definitely a common case, but it is subtly broken if the user doesn't realize that the overwritten value must be exactly the same type. The problem is that this API is advertised as supporting type punning. The only way to make it safe as advertised is to force users to deinitialize<T>() + initialize<U>. I think this needs to be clearly explained in the API comments.

+  ///
+  /// - Note: The converse of loading a value, storing a value `T` into
+  /// initialized memory requires the user to know the previously initialized
+  /// value's type. Full 'store' semantics can be achieved with:
+  /// `deinitialize(PreviousType)`
+  /// `initialize(NewType, with: value)`
+  /// If the previosly initialized type cannot reference any managed objects,
+  /// then the `deinitialize` call can be skipped.
   public func load<T>(_ : T.Type) -> T {

> - I am concerned about eliminating the distinction between mutable and immutable memory. That is, I think we’ll want the Mutable variant to be a separate type.

Yes. I haven't gotten feedback yet on that, or on importing 'void*' as UnsafeBytePointer. If the feeling on both is positive, then I think it's worth ammending my proposal at this point to include UnsafeMutableBytePointer.

> - Is there a good way to do a mass copy or move from an UnsafeBytePointer?

I didn’t add ‘move’ from UnsafeBytePointer for the same reason that I didn’t add ‘store’.

I could add the following functions to Unsafe[Mutable]Pointer though for completeness:

- initialize(from: UnsafeBytePointer, count)
- assign(from: UnsafeBytePointer, count)

I could also add a mass move from UnsafePointer *to* UnsafeBytePointer.

  func moveInitializeFrom<T>(_ source: UnsafePointer<T>, count: Int) {
  func moveInitializeBackwardFrom<T>(_ source: UnsafePointer<T>, count: Int) {

-Andy
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20160512/8677e065/attachment.html>


More information about the swift-evolution mailing list