Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[SR-14492] Add Data.init(unsafeUninitializedCapacity:initializingWith:) to better align with Array #4215

Open
swift-ci opened this issue Apr 15, 2021 · 2 comments

Comments

@swift-ci
Copy link
Contributor

Previous ID SR-14492
Radar rdar://problem/76709130
Original Reporter rmann (JIRA User)
Type Improvement
Additional Detail from JIRA
Votes 0
Component/s Foundation
Labels Improvement
Assignee None
Priority Medium

md5: ecc07e962cbe287f93359394ba00bddb

Issue Description:

Array has this wonderful `init(unsafeUninitializedCapacity:initializingWith🙂`. Unfortunately, `Data` does not, and so allocating and initializing a Data from a file read looks a bit like this:

let fd = FileDescriptor.open()
let blockSize = 4
let buffer = UnsafeMutableRawPointer.allocate(byteCount: blockSize, alignment: MemoryLayout<UInt8>.alignment)
let bp = UnsafeMutableRawBufferPointer(start: buffer, count: blockSize)
let bytesRead = try fd.read(fromAbsoluteOffset: 0, into: bp)
let data = Data(bytesNoCopy: buffer, count: blockSize, deallocator: .custom({ b,c in b.deallocate() }))

It’s much clearer and less error-prone like this:

let fd = FileDescriptor.open()
let data = try Data(unsafeUninitializedCapacity: count)
                { (ioBuf: inout UnsafeMutableRawBufferPointer, ioCount: inout Int) in
                     let buffer = UnsafeMutableRawBufferPointer(ioBuf)
                     let bytesRead = try fd.read(into: buffer)
                     ioCount = bytesRead
                }
@swift-ci
Copy link
Contributor Author

Comment by Rick M (JIRA)

Not sure this is 100%, but a quick test seemed to work. Here’s one possible implementation of the initializer. I tried to mimic Array as best I could (https://github.com/apple/swift/blob/7123d2614b5f222d03b3762cb110d27a9dd98e24/stdlib/public/core/Array.swift#L1457), but I'm not sure it handles all the error cases properly.

extension
Data
{
    init(unsafeUninitializedCapacity inCapacity: Int,
            initializingWith initializer: (inout UnsafeMutableRawBufferPointer, inout Int) throws -> Void)
        rethrows
    {
        let buffer = UnsafeMutableRawPointer.allocate(byteCount: inCapacity, alignment: MemoryLayout<UInt8>.alignment)
        var bp = UnsafeMutableRawBufferPointer(start: buffer, count: inCapacity)
        let originalAddress = bp.baseAddress
        var count: Int = 0
        defer
        {
            precondition(count <= inCapacity, "Initialized count set to greater than specified capacity.")
            precondition(bp.baseAddress == originalAddress, "Can't reassign buffer in Array(unsafeUninitializedCapacity:initializingWith:)")
        }
        
        do
        {
            try initializer(&bp, &count)
        }
        
        catch (let e)
        {
            self = Data(bytesNoCopy: buffer, count: count, deallocator: .custom({ b,c in b.deallocate() }))
            throw e
        }
        
        self = Data(bytesNoCopy: buffer, count: count, deallocator: .custom({ b,c in b.deallocate() }))
    }
}

@typesanitizer
Copy link

@swift-ci create

@swift-ci swift-ci transferred this issue from apple/swift-issues Apr 25, 2022
@shahmishal shahmishal transferred this issue from apple/swift May 5, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants