[swift-users] Getting at the bytes of Data

Philippe Hausler phausler at apple.com
Fri Dec 9 10:44:06 CST 2016

So letting the bytes escape from the closure could potentially be in that territory of “bad things may happen”. If you know for certain that the Data will not be mutated and it’s underlying storage will last for the duration of the usage then you should be able to get away with it.

The bytes pointer is an inner pointer return from the encapsulating object backing the struct Data. Since that backing object can potentially be deallocated via mutation or the buffer may be reallocated (which very often can cause the base address of the pointer to change) we decided it would be safer to use a closure to ensure the lifespan of the bytes over the access to the bytes.

Perhaps it might be best to understand more of what you are trying to do to offer a better solution.

> On Dec 9, 2016, at 8:39 AM, Ray Fix via swift-users <swift-users at swift.org> wrote:
> I am writing a tutorial and creating a wrapper on streaming compression.  In the code, I setup the stream source pointer: (input is of type Data)
>   // set up the stream with the input source
>   input.withUnsafeBytes { (bytes: UnsafePointer<UInt8>) in
>     stream.src_ptr = bytes
>   }
>   stream.src_size = input.count
> Input is guaranteed to be alive for the entire lifetime of the stream.  Everything seems to work fine but I thought I remember reading somewhere that it is bad form to let the bytes escape out of the withUnsafeBytes closure.  Anyone know if I'm I dipping into undefined behavior here?
> Thanks in advanced,
> Ray
> _______________________________________________
> swift-users mailing list
> swift-users at swift.org
> https://lists.swift.org/mailman/listinfo/swift-users

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-users/attachments/20161209/b40a86c4/attachment.html>

More information about the swift-users mailing list