[swift-users] Avoiding an extra copy withUnsafeBytes

Ray Fix rayfix at gmail.com
Thu Jan 26 09:03:17 CST 2017


To compute a hash, I want to loop through bytes of a trivial type.  To get the bytes, I use withUnsafeBytes hands me a rawBufferPointer collection type.  Great!

However this call also requires that the "of arg" be declared as a “var" instead of “let” because it is inout.  So to do it generically, it forces me to make a copy to some var storage.  

Since I am using withUnsafeBytes and not withUnsafeMutableBytes, though, it doesn’t seem like this copy should be necessary.  Is there some way to avoid it?  Is it something the compiler should be able to reason about and therefore elide? Possibly a future evolution (and something for that list)?

On a side note, wouldn’t it be cool if there where a way to enforce that a type was trivial?

Then one could write code like:

func consume<T: Trivial>(value: T) {
  var copy = value
  withUnsafeMutableBytes(of: &copy) { rawBufferPointer in
    // something interesting
  }
}

Always appreciate the great insights I get here.
Thanks as always. Best wishes,
Ray
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-users/attachments/20170126/86c5d525/attachment.html>


More information about the swift-users mailing list