Files
swift-nio-ssl/Sources/NIOSSL/String+unsafeUninitializedCapacity.swift
T
Rick Newton-Rogers 61cfaf9798 Migrate to GitHub Actions (#487)
Migrate CI to use GitHub Actions.

### Motivation:

To migrate to GitHub actions and centralised infrastructure.

### Modifications:

Changes of note:
* Disable warnings-as-errors until issues with recent NIO changes are
resolved
* Adopt swift-format using rules from SwiftNIO
* Remove scripts which are no longer needed

### Result:

Feature parity with old CI minus allocation tests which remain on the
old CI.
2024-10-25 09:32:23 +01:00

49 lines
1.9 KiB
Swift

//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftNIO open source project
//
// Copyright (c) 2017-2022 Apple Inc. and the SwiftNIO project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
extension String {
/// This is a backport of `String.init(unsafeUninitializedCapacity:initializingUTF8With:)`
/// that allows writing directly into an uninitialized String's backing memory.
///
/// As this API does not exist on older Apple platforms, we fake it out with a pointer and accept the extra copy.
init(
customUnsafeUninitializedCapacity capacity: Int,
initializingUTF8With initializer: (_ buffer: UnsafeMutableBufferPointer<UInt8>) throws -> Int
) rethrows {
if #available(macOS 11.0, iOS 14.0, tvOS 14.0, watchOS 7.0, *) {
try self.init(unsafeUninitializedCapacity: capacity, initializingUTF8With: initializer)
} else {
try self.init(backportUnsafeUninitializedCapacity: capacity, initializingUTF8With: initializer)
}
}
private init(
backportUnsafeUninitializedCapacity capacity: Int,
initializingUTF8With initializer: (_ buffer: UnsafeMutableBufferPointer<UInt8>) throws -> Int
) rethrows {
let buffer = UnsafeMutableBufferPointer<UInt8>.allocate(capacity: capacity)
defer {
buffer.deallocate()
}
let initializedCount = try initializer(buffer)
precondition(initializedCount <= capacity, "Overran buffer in initializer!")
self = String(
decoding: UnsafeMutableBufferPointer(start: buffer.baseAddress!, count: initializedCount),
as: UTF8.self
)
}
}