-
Notifications
You must be signed in to change notification settings - Fork 10.5k
/
Copy pathUnsafeBufferPointer.swift.gyb
477 lines (405 loc) · 15.1 KB
/
UnsafeBufferPointer.swift.gyb
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
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
// RUN: %target-run-simple-swiftgyb
// REQUIRES: executable_test
import StdlibUnittest
import StdlibCollectionUnittest
// Tests
struct SubscriptGetTest {
// SubscriptGetTest operates on a `(end - start)` sized buffer containing
// monotonically increasing integers from `start` to `end - 1`.
static let start = 0
static let end = 20
let rangeSelection: RangeSelection
/// The values that should be expected by slicing the UBP, or `nil` if the
/// test is expected to crash.
let expectedValues: [Int]?
/// Same as `expectedValues`, but for closed ranges. `nil` if no difference.
let expectedClosedValues: [Int]?
let loc: SourceLoc
static var elementCount = (end - start)
% for SelfType in ['UnsafeBufferPointer', 'UnsafeMutableBufferPointer']:
/// Create and populate an `${SelfType}` for use with unit tests.
/// PRECONDITION: `memory` must be allocated with space for
/// `SubscriptGetTest.elementCount` elements.
func create${SelfType}(from memory: UnsafeMutablePointer<OpaqueValue<Int>>)
-> ${SelfType}<OpaqueValue<Int>>
{
for i in SubscriptGetTest.start..<SubscriptGetTest.end {
memory[i] = OpaqueValue(i)
}
return ${SelfType}(start: memory, count: SubscriptGetTest.elementCount)
}
% end
init(
rangeSelection: RangeSelection, expectedValues: [Int]? = nil,
expectedClosedValues: [Int]? = nil,
file: String = #file, line: UInt = #line
) {
self.rangeSelection = rangeSelection
self.expectedValues = expectedValues
self.expectedClosedValues = expectedClosedValues ?? expectedValues
self.loc = SourceLoc(file, line, comment: "test data")
}
}
let subscriptGetTests : [SubscriptGetTest] = [
// Valid, empty.
SubscriptGetTest(rangeSelection: .emptyRange, expectedValues: []),
// Valid, edges.
SubscriptGetTest(rangeSelection: .leftEdge,
expectedValues: [],
expectedClosedValues: [0]),
SubscriptGetTest(rangeSelection: .rightEdge,
expectedValues: [],
expectedClosedValues: [19]),
// Valid, internal.
SubscriptGetTest(rangeSelection: .leftHalf,
expectedValues: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]),
SubscriptGetTest(rangeSelection: .rightHalf,
expectedValues: [10, 11, 12, 13, 14, 15, 16, 17, 18, 19]),
SubscriptGetTest(rangeSelection: .middle,
expectedValues: [5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]),
SubscriptGetTest(rangeSelection: .full,
expectedValues: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]),
SubscriptGetTest(rangeSelection: .offsets(2, 4),
expectedValues: [2, 3],
expectedClosedValues: [2, 3, 4]),
SubscriptGetTest(rangeSelection: .offsets(16, 19),
expectedValues: [16, 17, 18],
expectedClosedValues: [16, 17, 18, 19]),
// Invalid, bottom out of bounds.
SubscriptGetTest(rangeSelection: .offsets(-1, -1)),
SubscriptGetTest(rangeSelection: .offsets(-1, 0)),
SubscriptGetTest(rangeSelection: .offsets(-100, 5)),
// Invalid, top out of bounds.
SubscriptGetTest(rangeSelection: .offsets(20, 20)),
SubscriptGetTest(rangeSelection: .offsets(19, 20)),
SubscriptGetTest(rangeSelection: .offsets(5, 100)),
// Invalid, both out of bounds.
SubscriptGetTest(rangeSelection: .offsets(-1, 20)),
SubscriptGetTest(rangeSelection: .offsets(-100, 100)),
]
struct SubscriptSetTest {
// SubscriptSetTest operates on a `(end - start)` sized buffer containing
// monotonically increasing integers from `start` to `end - 1`.
static let start = 0
static let end = 10
let rangeSelection: RangeSelection
let replacementValues: [OpaqueValue<Int>]
let replacementValuesClosed: [OpaqueValue<Int>]
/// The values that should be expected by slicing the UBP, or `nil` if the
/// test is expected to crash.
let expectedValues: [Int]?
let expectedValuesClosed: [Int]?
let loc: SourceLoc
static var elementCount = (end - start)
/// Create and populate an `UnsafeMutableBufferPointer` for use with unit
/// tests.
/// PRECONDITION: `memory` must be allocated with space for
/// `SubscriptSetTest.elementCount` elements.
func createUnsafeMutableBufferPointer(
from memory: UnsafeMutablePointer<OpaqueValue<Int>>
) -> UnsafeMutableBufferPointer<OpaqueValue<Int>>
{
for i in SubscriptSetTest.start..<SubscriptSetTest.end {
memory[i] = OpaqueValue(i)
}
return UnsafeMutableBufferPointer(
start: memory,
count: SubscriptSetTest.elementCount)
}
/// Create and populate a mutable buffer pointer slice for use with unit
/// tests.
/// PRECONDITION: `memory` must be allocated with space for
/// `replacementValues.count` elements.
func replacementValuesSlice(
from memory: UnsafeMutablePointer<OpaqueValue<Int>>,
replacementValues: [OpaqueValue<Int>]
) -> MutableRandomAccessSlice<UnsafeMutableBufferPointer<OpaqueValue<Int>>>
{
for (i, value) in replacementValues.enumerated() {
memory[i] = value
}
let buffer = UnsafeMutableBufferPointer(
start: memory,
count: replacementValues.count)
let fullRange = RangeSelection.full.range(in: buffer)
return buffer[fullRange]
}
init(
rangeSelection: RangeSelection,
replacementValues: [Int],
replacementValuesClosed: [Int]? = nil,
expectedValues: [Int]? = nil,
expectedValuesClosed: [Int]? = nil,
file: String = #file, line: UInt = #line
) {
self.rangeSelection = rangeSelection
self.replacementValues = replacementValues.map { OpaqueValue($0) }
if let replacements = replacementValuesClosed {
self.replacementValuesClosed = replacements.map { OpaqueValue($0) }
} else {
self.replacementValuesClosed = self.replacementValues
}
self.expectedValues = expectedValues
self.expectedValuesClosed = expectedValuesClosed ?? expectedValues
self.loc = SourceLoc(file, line, comment: "test data")
}
}
let subscriptSetTests : [SubscriptSetTest] = [
// Valid, empty.
SubscriptSetTest(
rangeSelection: .emptyRange,
replacementValues: [],
expectedValues: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]),
// Valid, edges.
SubscriptSetTest(
rangeSelection: .leftEdge,
replacementValues: [],
replacementValuesClosed: [9001],
expectedValues: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
expectedValuesClosed: [9001, 1, 2, 3, 4, 5, 6, 7, 8, 9]),
SubscriptSetTest(
rangeSelection: .rightEdge,
replacementValues: [],
replacementValuesClosed: [9001],
expectedValues: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
expectedValuesClosed: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9001]),
// Valid, internal.
SubscriptSetTest(
rangeSelection: .leftHalf,
replacementValues: [10, 11, 12, 13, 14],
expectedValues: [10, 11, 12, 13, 14, 5, 6, 7, 8, 9]),
SubscriptSetTest(
rangeSelection: .rightHalf,
replacementValues: [10, 11, 12, 13, 14],
expectedValues: [0, 1, 2, 3, 4, 10, 11, 12, 13, 14]),
SubscriptSetTest(
rangeSelection: .middle,
replacementValues: [10, 11, 12, 13, 14, 15],
expectedValues: [0, 1, 10, 11, 12, 13, 14, 15, 8, 9]),
SubscriptSetTest(
rangeSelection: .full,
replacementValues: [10, 11, 12, 13, 14, 15, 16, 17, 18, 19],
expectedValues: [10, 11, 12, 13, 14, 15, 16, 17, 18, 19]),
// Invalid, range and replacement count mismatch.
SubscriptSetTest(
rangeSelection: .leftEdge,
replacementValues: [],
replacementValuesClosed: [9]),
SubscriptSetTest(
rangeSelection: .leftEdge,
replacementValues: [9, 9],
replacementValuesClosed: [9, 9, 9]),
SubscriptSetTest(
rangeSelection: .offsets(1, 2),
replacementValues: [],
replacementValuesClosed: [9]),
SubscriptSetTest(
rangeSelection: .offsets(1, 2),
replacementValues: [9, 9],
replacementValuesClosed: [9, 9, 9]),
SubscriptSetTest(
rangeSelection: .offsets(2, 5),
replacementValues: [9, 9],
replacementValuesClosed: [9, 9, 9]),
SubscriptSetTest(
rangeSelection: .offsets(2, 5),
replacementValues: [9, 9, 9, 9],
replacementValuesClosed: [9, 9, 9, 9, 9]),
// Invalid, bottom out of bounds.
SubscriptSetTest(
rangeSelection: .offsets(-1, -1),
replacementValues: []),
SubscriptSetTest(
rangeSelection: .offsets(-1, 0),
replacementValues: [9]),
SubscriptSetTest(
rangeSelection: .offsets(-3, 5),
replacementValues: [9, 9, 9, 9, 9, 9, 9, 9]),
// Invalid, top out of bounds.
SubscriptSetTest(
rangeSelection: .offsets(10, 10),
replacementValues: []),
SubscriptSetTest(
rangeSelection: .offsets(9, 10),
replacementValues: [9]),
SubscriptSetTest(
rangeSelection: .offsets(8, 15),
replacementValues: [9, 9, 9, 9, 9, 9, 9]),
// Invalid, both out of bounds.
SubscriptSetTest(
rangeSelection: .offsets(-1, 10),
replacementValues: [9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9]),
SubscriptSetTest(
rangeSelection: .offsets(-2, 11),
replacementValues: [9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9]),
]
// Test Suites
var UnsafeBufferPointerTestSuite = TestSuite("UnsafeBufferPointer")
var UnsafeMutableBufferPointerTestSuite = TestSuite("UnsafeMutableBufferPointer")
% for (SelfName, IsMutable, SelfType, PointerType) in [
% ('UnsafeBufferPointer', False, 'UnsafeBufferPointer<Float>', 'UnsafePointer<Float>'),
% ('UnsafeMutableBufferPointer', True, 'UnsafeMutableBufferPointer<Float>', 'UnsafeMutablePointer<Float>')
% ]:
${SelfName}TestSuite.test("AssociatedTypes") {
typealias Subject = ${SelfName}<OpaqueValue<Int>>
expectRandomAccessCollectionAssociatedTypes(
collectionType: Subject.self,
iteratorType: IndexingIterator<Subject>.self,
subSequenceType: ${'Mutable' if IsMutable else ''}RandomAccessSlice<Subject>.self,
indexType: Int.self,
indexDistanceType: Int.self,
indicesType: CountableRange<Int>.self)
expect${'Mutable' if IsMutable else ''}CollectionType(Subject.self)
}
${SelfName}TestSuite.test("nilBaseAddress") {
let emptyBuffer = ${SelfType}(start: nil, count: 0)
expectEmpty(emptyBuffer.baseAddress)
expectEqual(0, emptyBuffer.count)
expectTrue(emptyBuffer.startIndex == emptyBuffer.endIndex)
var iter = emptyBuffer.makeIterator()
expectEmpty(iter.next())
expectEqualSequence([], emptyBuffer)
}
${SelfName}TestSuite.test("nonNilButEmpty") {
let emptyAllocated = UnsafeMutablePointer<Float>(allocatingCapacity: 0)
defer { emptyAllocated.deallocateCapacity(0) }
let emptyBuffer = ${SelfType}(start: ${PointerType}(emptyAllocated), count: 0)
expectEqual(emptyAllocated, emptyBuffer.baseAddress)
expectEqual(0, emptyBuffer.count)
expectTrue(emptyBuffer.startIndex == emptyBuffer.endIndex)
var iter = emptyBuffer.makeIterator()
expectEmpty(iter.next())
expectEqualSequence([], emptyBuffer)
}
${SelfName}TestSuite.test("nonNilNonEmpty") {
let count = 4
let allocated = UnsafeMutablePointer<Float>(allocatingCapacity: count)
defer { allocated.deallocateCapacity(count) }
allocated.initialize(with: 1.0, count: count)
allocated[count - 1] = 2.0
let buffer = ${SelfType}(start: ${PointerType}(allocated), count: count - 1)
expectEqual(allocated, buffer.baseAddress)
expectEqual(count - 1, buffer.count)
expectEqual(count - 1, buffer.endIndex - buffer.startIndex)
allocated[1] = 0.0
expectEqual(1.0, buffer[0])
expectEqual(0.0, buffer[1])
expectEqual(1.0, buffer[2])
var iter = buffer.makeIterator()
expectEqual(1.0, iter.next())
expectEqual(0.0, iter.next())
expectEqual(1.0, iter.next())
expectEmpty(iter.next())
expectEqualSequence([1.0, 0.0, 1.0], buffer)
expectEqual(2.0, allocated[count-1])
}
${SelfName}TestSuite.test("badCount")
.skip(.custom(
{ _isFastAssertConfiguration() },
reason: "this trap is not guaranteed to happen in -Ounchecked"))
.code {
expectCrashLater()
let emptyAllocated = UnsafeMutablePointer<Float>(allocatingCapacity: 0)
defer { emptyAllocated.deallocateCapacity(0) }
let buffer = ${SelfType}(start: ${PointerType}(emptyAllocated), count: -1)
_ = buffer
}
${SelfName}TestSuite.test("badNilCount")
.skip(.custom(
{ _isFastAssertConfiguration() },
reason: "this trap is not guaranteed to happen in -Ounchecked"))
.code {
expectCrashLater()
let buffer = ${SelfType}(start: nil, count: 1)
_ = buffer
}
% for RangeName in ['range', 'countableRange', 'closedRange', 'countableClosedRange']:
${SelfName}TestSuite.test("subscript/${RangeName}/get").forEach(in: subscriptGetTests) {
(test) in
let expectedValues: [Int]?
% if 'closed' in RangeName.lower():
if test.rangeSelection.isEmpty {
return
}
expectedValues = test.expectedClosedValues
% else:
expectedValues = test.expectedValues
% end
let elementCount = SubscriptGetTest.elementCount
var memory = UnsafeMutablePointer<OpaqueValue<Int>>(allocatingCapacity: elementCount)
let buffer = test.create${SelfName}(from: memory)
defer { memory.deallocateCapacity(elementCount) }
let range = test.rangeSelection.${RangeName}(in: buffer)
if expectedValues == nil { expectCrashLater() }
let slice = buffer[range]
expectEqual(
expectedValues!,
slice.map { $0.value },
stackTrace: SourceLocStack().with(test.loc)
)
}
% end
% end
% for RangeName in ['range', 'countableRange', 'closedRange', 'countableClosedRange']:
UnsafeMutableBufferPointerTestSuite.test("subscript/${RangeName}/set")
.forEach(in: subscriptSetTests) { (test) in
let expectedValues: [Int]?
let replacementValues: [OpaqueValue<Int>]
% if 'closed' in RangeName.lower():
if test.rangeSelection.isEmpty {
return
}
expectedValues = test.expectedValuesClosed
replacementValues = test.replacementValuesClosed
% else:
expectedValues = test.expectedValues
replacementValues = test.replacementValues
% end
let elementCount = SubscriptSetTest.elementCount
var memory = UnsafeMutablePointer<OpaqueValue<Int>>(
allocatingCapacity: elementCount)
var sliceMemory = UnsafeMutablePointer<OpaqueValue<Int>>(
allocatingCapacity: replacementValues.count)
var buffer = test.createUnsafeMutableBufferPointer(from: memory)
defer {
memory.deallocateCapacity(elementCount)
sliceMemory.deallocateCapacity(replacementValues.count)
}
let range = test.rangeSelection.${RangeName}(in: buffer)
let replacementSlice = test.replacementValuesSlice(
from: sliceMemory,
replacementValues: replacementValues)
if expectedValues == nil { expectCrashLater() }
buffer[range] = replacementSlice
expectEqual(
expectedValues!,
buffer.map { $0.value },
stackTrace: SourceLocStack().with(test.loc)
)
}
% end
UnsafeMutableBufferPointerTestSuite.test("changeElementViaBuffer") {
let count = 4
let allocated = UnsafeMutablePointer<Float>(allocatingCapacity: count)
defer { allocated.deallocateCapacity(count) }
allocated.initialize(with: 1.0, count: count)
allocated[count-1] = -1.0
var buffer = UnsafeMutableBufferPointer(start: allocated, count: count - 1)
buffer[1] = 0.0
expectEqual(1.0, buffer[0])
expectEqual(0.0, buffer[1])
expectEqual(1.0, buffer[2])
expectEqual(1.0, allocated[0])
expectEqual(0.0, allocated[1])
expectEqual(1.0, allocated[2])
expectEqual(-1.0, allocated[count-1])
buffer.sort()
expectEqual(0.0, buffer[0])
expectEqual(1.0, buffer[1])
expectEqual(1.0, buffer[2])
expectEqual(0.0, allocated[0])
expectEqual(1.0, allocated[1])
expectEqual(1.0, allocated[2])
expectEqual(-1.0, allocated[count-1])
}
runAllTests()