# Unaligned Load

**URL:** <https://forums.swift.org/t/unaligned-load/22916>\
**Category:** Using Swift\
**Tags:** swift5, memory-safety\
**Created:** [April 10, 2019, 1:32pm UTC](https://forums.swift.org/t/unaligned-load/22916 "2019-04-10T13:32:29Z")\
**Posts on this page:** 6\
**Page:** 1

<div class="post-metadata">

**Author:** ![rlovelett](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/rlovelett/32/753_2.png) [@rlovelett](https://forums.swift.org/u/rlovelett)\
**Post date:** [April 10, 2019, 1:32pm UTC](https://forums.swift.org/t/unaligned-load/22916/1 "2019-04-10T13:32:29Z")

</div>

I've got some code that I am migrating to Swift 5. I had thought this code was relatively safe, or as safe as I could make it considering it was using the `Unsafe*` APIs. It turns out I was wrong and it was actually to be undefined behavior for Swift all along.

I have an extension to `Data` called `getFixedWidthInteger` which gets a `FixedWidthInteger` from a specific index in the `Data`. I used to use the now deprecated `withUnsafeBytes`.

I tried the naïve migration:

```swift
extension Data {
  func getFixedWidthInteger<I: FixedWidthInteger>(at index: Data.Index) -> I {
    return self.withUnsafeBytes { $0.load(fromByteOffset: index, as: I.self) }
  }
}

let data = Data([0x00, 0x00, 0x40, 0xA4, 0x81])
let uut: UInt32 = data.getFixedWidthInteger(at: 1) // Fatal error: load from misaligned raw pointer
XCTAssertEqual(uut, 2_175_025_152)

```

Which traps as expected. I've read multiple threads on here (e.g., [Best practice for parsing heterogeneous types from Data (in Swift 5)](https://forums.swift.org/t/best-practice-for-parsing-heterogeneous-types-from-data-in-swift-5/22528), [Accessing a “misaligned” raw pointer safely](https://forums.swift.org/t/accessing-a-misaligned-raw-pointer-safely/22743), [Built-in unaligned loads](https://forums.swift.org/t/built-in-unaligned-loads/19664)).

## tl;dr: The Actual Question

I've come up with a solution that does not trap.

```swift
extension Data {
  func getFixedWidthInteger<I: FixedWidthInteger>(at index: Data.Index) -> I {
    return self.advanced(by: index).withUnsafeBytes { $0.load(fromByteOffset: 0, as: I.self) }
  }
}

let data = Data([0x00, 0x00, 0x40, 0xA4, 0x81])
let uut: UInt32 = data.getFixedWidthInteger(at: 1)
XCTAssertEqual(uut, 2_175_025_152)

```

My guess is that it is not safe and I've just stumbled into a corner case that is not triggering an assertion. Maybe this is safe and completely defined behavior. However, given that I used to think my old code was safe and defined behavior and I was wrong I figured I'd rather ask and be sure.

How bad is this?

---

<div class="post-metadata">

**Author:** ![rlovelett](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/rlovelett/32/753_2.png) [@rlovelett](https://forums.swift.org/u/rlovelett)\
**Post date:** [April 10, 2019, 2:00pm UTC](https://forums.swift.org/t/unaligned-load/22916/2 "2019-04-10T14:00:50Z")

</div>

I'm starting to think that maybe it is _safe_ but possibly not very performant because it copies the entire block of memory.

> <https://github.com/apple/swift-corelibs-foundation/blob/566e170fbd5052a057d3d65a15cffa6cfaa7e161/Foundation/Data.swift#L2511-L2517>

---

<div class="post-metadata">

**Author:** ![Avi](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/avi/32/2962_2.png) [@Avi](https://forums.swift.org/u/Avi)\
**Post date:** [April 10, 2019, 2:24pm UTC](https://forums.swift.org/t/unaligned-load/22916/3 "2019-04-10T14:24:07Z")

</div>

I switched my code to using the following:

```
fileprivate func read<T: FixedWidthInteger>(_ type: T.Type) throws -> T {
    let byteCount = MemoryLayout<T>.size

    guard cursor + byteCount <= data.endIndex else { throw Errors.prematureEndOfData }

    defer { advance(by: byteCount) }

    return data[cursor ..< cursor + byteCount]
        .reduce(T(0), { $0 << 8 | T($1) })
}

```

Due to the `Data` subscript ensuring that reading a single element (byte) will always succeed.

[edit]

Despite not being an issue in the codebase from which the above method appears, I edited it to be more correct as a standalone method.

---

<div class="post-metadata">

**Author:** ![Nevin](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/nevin/32/617_2.png) [@Nevin](https://forums.swift.org/u/Nevin)\
**Post date:** [April 10, 2019, 2:32pm UTC](https://forums.swift.org/t/unaligned-load/22916/4 "2019-04-10T14:32:30Z")

</div>

> [@Avi](#):
>
> ```swift
> fileprivate func read<T: FixedWidthInteger>(_ type: T.Type) throws -> T {
> let byteCount = MemoryLayout<T>.size
> 
> guard cursor + byteCount <= data.count else { throw Errors.prematureEndOfData }
> 
> defer { advance(by: byteCount) }
> 
> return data[cursor ..< cursor + byteCount]
> .reduce(T(0), { $0 << 8 | T($1) })
> }
> 
> ```

Is this code implicitly assuming that `data` has zero-based indices? (It’s hard to tell without knowing what `cursor` represents.)

---

<div class="post-metadata">

**Author:** ![Avi](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/avi/32/2962_2.png) [@Avi](https://forums.swift.org/u/Avi)\
**Post date:** [April 10, 2019, 2:56pm UTC](https://forums.swift.org/t/unaligned-load/22916/5 "2019-04-10T14:56:24Z")

</div>

Yes, that assumption is being made. It's not an issue in the codebase in which this method appears. The key here, though, is to demonstrate how I'm forming integers.

---

<div class="post-metadata">

**Author:** ![cconway](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/cconway/32/7068_2.png) [@cconway](https://forums.swift.org/u/cconway)\
**Post date:** [April 10, 2019, 5:19pm UTC](https://forums.swift.org/t/unaligned-load/22916/6 "2019-04-10T17:19:44Z")

</div>

I'm with @Avi in that, based on those other threads, I have switched to parsing FixedWidthIntegers using the indexed byte access from Data and shifting. From what I understand you _can_ avoid unaligned access via pointers, but that maybe if you don't require using pointers it's safer to use more abstract APIs. I created some extensions to suit my major use cases which involve stepping over a specified count of FixedWidthIntegers and then parsing a FixedWidthInteger. If you're relying on `.prefix()` and such it's much harder to escape the bounds of your Data instance then with UnsafeRawPointer.
