Backcompat.swift 840 B

1234567891011121314151617181920212223242526272829
  1. /*
  2. This source file is part of the Swift System open source project
  3. Copyright (c) 2021 Apple Inc. and the Swift System project authors
  4. Licensed under Apache License v2.0 with Runtime Library Exception
  5. See https://swift.org/LICENSE.txt for license information
  6. */
  7. extension String {
  8. internal init(
  9. _unsafeUninitializedCapacity capacity: Int,
  10. initializingUTF8With body: (UnsafeMutableBufferPointer<UInt8>) throws -> Int
  11. ) rethrows {
  12. if #available(macOS 11, iOS 14.0, watchOS 7.0, tvOS 14.0, *) {
  13. self = try String(
  14. unsafeUninitializedCapacity: capacity,
  15. initializingUTF8With: body)
  16. return
  17. }
  18. let array = try Array<UInt8>(
  19. unsafeUninitializedCapacity: capacity
  20. ) { buffer, count in
  21. count = try body(buffer)
  22. }
  23. self = String(decoding: array, as: UTF8.self)
  24. }
  25. }