Uploaded image for project: 'Swift'
  1. Swift
  2. SR-10273

Add an UnsafeRaw[Buffer]Pointer API for loading and storing unaligned/packed data

    XMLWordPrintable

    Details

      Description

      Swift does not currently provide any reasonable way to load potentially misaligned data from a raw byte buffer.

      This API currently requires an aligned pointer:

       

      struct UnsafeRawPointer {
       public func load<T>(fromByteOffset offset: Int = 0, as type: T.Type) -> T {
         _debugPrecondition(0 == (UInt(bitPattern: self + offset)
                            & (UInt(MemoryLayout<T>.alignment) - 1)),
                            "load from misaligned raw pointer")
       //...
      }
      

      Users need to be able to do something like this:

      receivedData.withUnsafeBytes { (rawPointer) -> Void in
       var offset = 0
       let parsedLength = rawPointer.load(as: UInt8.self)
       offset += MemoryLayout.size(ofValue: parsedLength)
       let parsedType = rawPointer.load(fromByteOffset: offset, as: UInt16.self)
       offset += MemoryLayout.size(ofValue: parsedType)
       ... 
       // Do something with the parsed values
      }

      We should either remove the alignment restriction from the `UnsafeRawPointer.load` API, or add a new flag to allow unalgined loads. The current default requires alignment because:

      • ignoring alignment may indicate a programmer error, this way you're forced to think about alignment and make it explicit
      • we wanted higher-level APIs to be expressible in terms of raw pointers without changing semantics or losing performance
      • we can loosen the requirement over time but can't strengthen it

       

        Attachments

          Activity

            People

            • Assignee:
              Unassigned
              Reporter:
              atrick Andrew Trick
            • Votes:
              4 Vote for this issue
              Watchers:
              7 Start watching this issue

              Dates

              • Created:
                Updated: