-
Notifications
You must be signed in to change notification settings - Fork 145
Expand file tree
/
Copy pathABI.EncodedAttachment.swift
More file actions
286 lines (254 loc) · 9.39 KB
/
ABI.EncodedAttachment.swift
File metadata and controls
286 lines (254 loc) · 9.39 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2024 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for Swift project authors
//
#if canImport(Foundation)
private import Foundation
#endif
extension ABI {
/// A type implementing the JSON encoding of ``Attachment`` for the ABI entry
/// point and event stream output.
///
/// You can use this type and its conformance to [`Codable`](https://developer.apple.com/documentation/swift/codable),
/// when integrating the testing library with development tools. It is not
/// part of the testing library's public interface.
public struct EncodedAttachment<V>: Sendable where V: ABI.Version {
/// The different kinds of encoded attachment.
fileprivate enum Kind: Sendable {
/// The attachment has already been saved to disk and we have its local
/// file system path.
case savedAtPath(String)
/// The attachment is stored in memory and we have its serialized form.
case inMemory([UInt8])
/// The attachment has not been saved nor serialized yet and we still have
/// it as an attachable value.
case abstract(Attachment<AnyAttachable>)
/// An error occurred when the attachment was encoded that prevented it
/// from being properly serialized.
case error(ABI.EncodedError<V>)
}
/// The kind of encoded attachment.
fileprivate var kind: Kind
/// The preferred name of the attachment.
///
/// - Warning: Attachments' preferred names are not yet part of the JSON
/// schema.
var _preferredName: String?
}
}
// MARK: - Codable
extension ABI.EncodedAttachment: Codable {
private enum CodingKeys: String, CodingKey {
case path
case preferredName = "_preferredName"
case bytes = "_bytes"
case error = "_error"
}
public func encode(to encoder: any Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
func encodeBytes(_ bytes: UnsafeRawBufferPointer) throws {
#if canImport(Foundation)
// If possible, encode this structure as Base64 data.
try bytes.withUnsafeBytes { bytes in
let data = Data(bytesNoCopy: .init(mutating: bytes.baseAddress!), count: bytes.count, deallocator: .none)
try container.encode(data.base64EncodedString(), forKey: .bytes)
}
#else
// Otherwise, it's an array of integers.
try container.encode(bytes, forKey: .bytes)
#endif
}
switch kind {
case let .savedAtPath(path):
try container.encode(path, forKey: .path)
case let .abstract(attachment):
if let path = attachment.fileSystemPath {
try container.encode(path, forKey: .path)
} else if V.includesExperimentalFields {
var errorWhileEncoding: (any Error)?
do {
try attachment.withUnsafeBytes { bytes in
do {
try encodeBytes(bytes)
} catch {
// An error occurred during encoding rather than coming from the
// attachment itself. Preserve it and throw it before returning.
errorWhileEncoding = error
}
}
} catch {
// An error occurred while serializing the attachment. Encode it
// separately for recovery on the calling side.
let error = ABI.EncodedError<V>(encoding: error)
try container.encode(error, forKey: .error)
}
if let errorWhileEncoding {
throw errorWhileEncoding
}
}
case let .inMemory(bytes):
if V.includesExperimentalFields {
try bytes.withUnsafeBytes(encodeBytes)
}
case let .error(error):
if V.includesExperimentalFields {
try container.encode(error, forKey: .error)
}
}
if V.includesExperimentalFields {
try container.encodeIfPresent(_preferredName, forKey: .preferredName)
}
}
public init(from decoder: any Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
kind = try {
if let path = try container.decodeIfPresent(String.self, forKey: .path) {
return .savedAtPath(path)
}
if V.includesExperimentalFields {
#if canImport(Foundation)
// If possible, decode a whole Foundation Data object.
if let data = try? container.decodeIfPresent(Data.self, forKey: .bytes) {
return .inMemory([UInt8](data))
}
#endif
// Fall back to trying to decode an array of integers.
if let bytes = try container.decodeIfPresent([UInt8].self, forKey: .bytes) {
return .inMemory(bytes)
}
// Finally, look for an error caught during encoding.
if let error = try container.decodeIfPresent(ABI.EncodedError<V>.self, forKey: .error) {
return .error(error)
}
}
// Couldn't find anything to decode.
throw DecodingError.valueNotFound(
String.self,
DecodingError.Context(
codingPath: decoder.codingPath + [CodingKeys.path],
debugDescription: "Encoded attachment did not include any persistent representation."
)
)
}()
if V.includesExperimentalFields {
_preferredName = try container.decodeIfPresent(String.self, forKey: .preferredName)
}
}
}
// MARK: - Attachable
extension ABI.EncodedAttachment: Attachable {
public var estimatedAttachmentByteCount: Int? {
switch kind {
case .savedAtPath, .error:
return nil
case let .inMemory(bytes):
return bytes.count
case let .abstract(attachment):
return attachment.attachableValue.estimatedAttachmentByteCount
}
}
/// An error type that is thrown when ``ABI/EncodedAttachment`` cannot satisfy
/// a request for the underlying attachment's bytes.
fileprivate struct BytesUnavailableError: Error {}
public borrowing func withUnsafeBytes<R>(for attachment: borrowing Attachment<Self>, _ body: (UnsafeRawBufferPointer) throws -> R) throws -> R {
switch kind {
case let .savedAtPath(path):
#if !SWT_NO_FILE_IO
#if canImport(Foundation)
// Leverage Foundation's file-mapping logic since we're using Data anyway.
let url = URL(fileURLWithPath: path, isDirectory: false)
let bytes = try Data(contentsOf: url, options: [.mappedIfSafe])
#else
let fileHandle = try FileHandle(forReadingAtPath: path)
let bytes = try fileHandle.readToEnd()
#endif
return try bytes.withUnsafeBytes(body)
#else
// Cannot read the attachment from disk on this platform.
throw BytesUnavailableError()
#endif
case let .inMemory(bytes):
return try bytes.withUnsafeBytes(body)
case let .abstract(attachment):
return try attachment.withUnsafeBytes(body)
case let .error(error):
throw error
}
}
public borrowing func preferredName(for attachment: borrowing Attachment<Self>, basedOn suggestedName: String) -> String {
_preferredName ?? suggestedName
}
}
#if !SWT_NO_FILE_CLONING
extension ABI.EncodedAttachment: FileClonable {
package func clone(toFileAtPath filePath: String) -> Bool {
guard case let .abstract(attachment) = kind else {
return false
}
return attachment.attachableValue.clone(toFileAtPath: filePath)
}
}
#endif
extension ABI.EncodedAttachment.BytesUnavailableError: CustomStringConvertible {
var description: String {
"The attachment's content could not be deserialized."
}
}
// MARK: - Conversion to/from library types
extension ABI.EncodedAttachment {
/// Initialize an instance of this type from the given value.
///
/// - Parameters:
/// - attachment: The attachment to initialize this instance from.
public init(encoding attachment: borrowing Attachment<AnyAttachable>) {
kind = .abstract(copy attachment)
if V.includesExperimentalFields {
_preferredName = attachment.preferredName
}
}
/// Initialize an instance of this type from the given value.
///
/// - Parameters:
/// - attachment: The attachment to initialize this instance from.
public init(encoding attachment: borrowing Attachment<some Attachable & Sendable & ~Copyable>) {
let attachmentCopy = Attachment<AnyAttachable>(copy attachment)
self.init(encoding: attachmentCopy)
}
}
@_spi(ForToolsIntegrationOnly)
extension Attachment where AttachableValue == AnyAttachable {
/// Initialize an instance of this type from the given value.
///
/// - Parameters:
/// - event: The encoded event to initialize this instance from.
///
/// If `event` does not represent an attached value, the initializer returns
/// `nil`.
public init?<V>(decoding event: ABI.EncodedEvent<V>) {
guard let attachment = event.attachment else {
return nil
}
self.init(decoding: attachment)
if let sourceLocation = event._sourceLocation.flatMap(SourceLocation.init(decoding:)) {
self.sourceLocation = sourceLocation
}
}
/// Initialize an instance of this type from the given value.
///
/// - Parameters:
/// - attachment: The encoded attachment to initialize this instance from.
public init?<V>(decoding attachment: ABI.EncodedAttachment<V>) {
switch attachment.kind {
case let .abstract(attachment):
self = attachment // No need to nest it further.
default:
let attachmentCopy = Attachment<ABI.EncodedAttachment<V>>(attachment, sourceLocation: .unknown)
self.init(attachmentCopy)
}
}
}