|
| 1 | +// |
| 2 | +// This source file is part of the Swift.org open source project |
| 3 | +// |
| 4 | +// Copyright (c) 2026 Apple Inc. and the Swift project authors |
| 5 | +// Licensed under Apache License v2.0 with Runtime Library Exception |
| 6 | +// |
| 7 | +// See https://swift.org/LICENSE.txt for license information |
| 8 | +// See https://swift.org/CONTRIBUTORS.txt for Swift project authors |
| 9 | +// |
| 10 | + |
| 11 | +#if canImport(CoreTransferable) |
| 12 | +public import Testing |
| 13 | +public import CoreTransferable |
| 14 | + |
| 15 | +private import Foundation |
| 16 | +import UniformTypeIdentifiers |
| 17 | + |
| 18 | +private enum TransferableAttachmentError: Error { |
| 19 | + case suitableContentTypeNotFound |
| 20 | +} |
| 21 | + |
| 22 | +/// A wrapper type representing transferable values that can be attached |
| 23 | +/// indirectly. |
| 24 | +/// |
| 25 | +/// You do not need to use this type directly. Instead, initialize an instance |
| 26 | +/// of ``Attachment`` using an instance of a type conforming to both |
| 27 | +/// ``Attachable`` and ``Transferable``. |
| 28 | +@_spi(Experimental) |
| 29 | +@available(macOS 15.2, *) |
| 30 | +public struct _AttachableTransferableWrapper<T>: Sendable where T: Transferable { |
| 31 | + private var _transferableValue: T |
| 32 | + private var _contentType: UTType |
| 33 | + private var _bytes: Data |
| 34 | + |
| 35 | + init(transferring transferableValue: T, as contentType: UTType?) async throws { |
| 36 | + _transferableValue = transferableValue |
| 37 | + |
| 38 | + let contentType = contentType ?? transferableValue.exportedContentTypes() |
| 39 | + .first { $0.conforms(to: .data) } |
| 40 | + guard let contentType else { |
| 41 | + throw TransferableAttachmentError.suitableContentTypeNotFound |
| 42 | + } |
| 43 | + _contentType = contentType |
| 44 | + |
| 45 | + _bytes = try await _transferableValue.exported(as: contentType) |
| 46 | + } |
| 47 | +} |
| 48 | + |
| 49 | +// MARK: - |
| 50 | + |
| 51 | +@_spi(Experimental) |
| 52 | +@available(macOS 15.2, *) |
| 53 | +extension _AttachableTransferableWrapper: AttachableWrapper { |
| 54 | + public var wrappedValue: T { |
| 55 | + _transferableValue |
| 56 | + } |
| 57 | + |
| 58 | + public func withUnsafeBytes<R>(for attachment: borrowing Attachment<Self>, _ body: (UnsafeRawBufferPointer) throws -> R) throws -> R { |
| 59 | + try _bytes.withUnsafeBytes(body) |
| 60 | + } |
| 61 | + |
| 62 | + public borrowing func preferredName(for attachment: borrowing Attachment<Self>, basedOn suggestedName: String) -> String { |
| 63 | + let baseName = _transferableValue.suggestedFilename ?? suggestedName |
| 64 | + return (baseName as NSString).appendingPathExtension(for: _contentType) |
| 65 | + } |
| 66 | +} |
| 67 | +#endif |
0 commit comments