Skip to content

[SR-10778] Foundation Data should have an API for reading/writing arbitrary trivial types (without exposing unsafe pointers) #3329

Open
@atrick

Description

@atrick
Previous ID SR-10778
Radar rdar://28201395
Original Reporter @atrick
Type New Feature
Additional Detail from JIRA
Votes 1
Component/s Foundation
Labels New Feature
Assignee None
Priority Medium

md5: 9114378c80fc22dfef1c2f8e6aee6a92

Issue Description:

The fundamental operations are:

public mutating func append<SourceType>(_ value: SourceType)
public mutating func replaceSubrange<SourceType>(_ subrange: Range<Index>, with value: SourceType)
public func copyBytes<ResultType>(from index: Index, as type: ResultType.Type) -> ResultType

Note that this API should support unaligned data. Until UnsafeRawPointer directly supports unaligned loads, the implementation will need to create a temporary variable and copy bytes into it using withUnsafeButes(of: &var). See Unaligned UnsafeRawPointer loads

We could consider altenatives to the copyBytes name. It is analgous to

UnsafeRawBufferPointer.load(fromByteOffset:as:)

...but Data APIs should be expressed as Collection indices, not byte offsets, which are not the same thing for Data slices.

Additionally, we could have extensions on the basic scalar data types, although this can't completely replace the primitive copyBytes.

See Forum post: withUnsafeBytes is deprecated

extension Int64 {
 init(data: Data, from: Data.Index? = nil) {
   let startIndex = from ?? data.startIndex
   let range = startIndex..<startIndex + MemoryLayout<Int64>.size
   var value = Int64(0)
   _ = withUnsafeMutableBytes(of: &value) {
     data.copyBytes(to: $0, from: range)
   }
   self.init(value)
 }
}

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions