Skip to content

Commit 70cef22

Browse files
committed
Test generalized functions
1 parent d1249fc commit 70cef22

File tree

1 file changed

+73
-0
lines changed

1 file changed

+73
-0
lines changed

Tests/FoundationEssentialsTests/DataTests.swift

Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1484,6 +1484,79 @@ private final class DataTests {
14841484
}
14851485
}
14861486

1487+
private struct Value: ~Copyable {
1488+
var stored: Int
1489+
init(_ value: Int) { stored = value }
1490+
}
1491+
1492+
private enum LocalError: Error, Equatable { case error }
1493+
1494+
@Test func validateGeneralizedParameters_withUnsafeBytes() {
1495+
var data: Data
1496+
1497+
do throws(LocalError) {
1498+
data = Data(repeating: 2, count: 12)
1499+
let value = data.withUnsafeBytes {
1500+
let sum = $0.withMemoryRebound(to: UInt8.self) { Int($0.reduce(0,+)) }
1501+
return Value(sum)
1502+
}
1503+
#expect(value.stored == 24)
1504+
try data.withUnsafeBytes { _ throws(LocalError) in throw(LocalError.error) }
1505+
Issue.record("Should be unreachable")
1506+
} catch {
1507+
#expect(error == .error)
1508+
}
1509+
1510+
do throws(LocalError) {
1511+
data = Data(repeating: 1, count: 128)
1512+
let value = data.withUnsafeBytes {
1513+
let sum = $0.withMemoryRebound(to: UInt8.self) { Int($0.reduce(0,+)) }
1514+
return Value(sum)
1515+
}
1516+
#expect(value.stored == 128)
1517+
try data.withUnsafeBytes { _ throws(LocalError) in throw(LocalError.error) }
1518+
Issue.record("Should be unreachable")
1519+
} catch {
1520+
#expect(error == .error)
1521+
}
1522+
}
1523+
1524+
@Test func validateGeneralizedParameters_withUnsafeMutableBytes() {
1525+
var data: Data
1526+
1527+
do throws(LocalError) {
1528+
data = Data(count: 12)
1529+
let value = data.withUnsafeMutableBytes {
1530+
$0.withMemoryRebound(to: UInt8.self) {
1531+
for i in $0.indices { $0[i] = 2 }
1532+
}
1533+
let sum = $0.withMemoryRebound(to: UInt8.self) { Int($0.reduce(0,+)) }
1534+
return Value(sum)
1535+
}
1536+
#expect(value.stored == 24)
1537+
try data.withUnsafeBytes { _ throws(LocalError) in throw(LocalError.error) }
1538+
Issue.record("Should be unreachable")
1539+
} catch {
1540+
#expect(error == .error)
1541+
}
1542+
1543+
do throws(LocalError) {
1544+
data = Data(count: 128)
1545+
let value = data.withUnsafeMutableBytes {
1546+
$0.withMemoryRebound(to: UInt8.self) {
1547+
for i in $0.indices { $0[i] = 1 }
1548+
}
1549+
let sum = $0.withMemoryRebound(to: UInt8.self) { Int($0.reduce(0,+)) }
1550+
return Value(sum)
1551+
}
1552+
#expect(value.stored == 128)
1553+
try data.withUnsafeBytes { _ throws(LocalError) in throw(LocalError.error) }
1554+
Issue.record("Should be unreachable")
1555+
} catch {
1556+
#expect(error == .error)
1557+
}
1558+
}
1559+
14871560
@Test func sliceHash() {
14881561
let base1 = Data([0, 0xFF, 0xFF, 0])
14891562
let base2 = Data([0, 0xFF, 0xFF, 0])

0 commit comments

Comments
 (0)