[swift-users] Extracting arbitrary types (e.g. UInt16) out of Data
Charles Srstka
cocoadev at charlessoft.com
Mon Jun 26 10:48:53 CDT 2017
> On Jun 26, 2017, at 3:55 AM, Daniel Vollmer via swift-users <swift-users at swift.org> wrote:
>
> Hi Rick,
>
>> On 26. Jun 2017, at 02:37, Rick Mann via swift-users <swift-users at swift.org <mailto:swift-users at swift.org>> wrote:
>
> [snip]
>
>> I'd also like to avoid unnecessary copying of the data. All of it is immutable for the purposes of this problem.
>>
>> How can I get the UInt16 that starts at byte X in a Data? Same goes for Double or Int32 or whatever.
>
> I’m not sure what Swift’s stance on this is, but not all platforms allow misaligned memory accesses (such as your attempt to access a UInt16 that lies at an odd memory address).
>
> So at least IMO, copying and assembling the bytes into an instance of the actual destination type seems to be exactly the right thing to do.
>
> Daniel.
While that’s true, the bindMemory() function takes as arguments not only the type you’re binding to, but also the number of objects you plan to read. So if Swift is ever ported to a platform that doesn’t allow unaligned access (I don’t think it is currently, although I could be wrong about that), it wouldn’t be difficult to make the version of bindMemory() for that architecture copy the bytes to a safe address in the case that the underlying memory isn’t properly aligned for that type.
Charles
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-users/attachments/20170626/013ea16a/attachment.html>
More information about the swift-users
mailing list