Skip to content

Commit e518146

Browse files
phauslerparkera
authored andcommitted
Correct sequence initializers for Data when repeating:count: is called and add a memset fast-path (#764)
Resolves SR-3566.
1 parent 2dbc6cc commit e518146

File tree

2 files changed

+29
-1
lines changed

2 files changed

+29
-1
lines changed

Foundation/Data.swift

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -971,6 +971,17 @@ public struct Data : ReferenceConvertible, Equatable, Hashable, RandomAccessColl
971971
return _DataStorage(bytes: $0.baseAddress, length: $0.count)
972972
}
973973
}
974+
975+
/// Initialze a `Data` with a repeating byte pattern
976+
///
977+
/// - parameter repeatedValue: A byte to initialze the pattern
978+
/// - parameter count: The number of bytes the data initially contains initialzed to the repeatedValue
979+
public init(repeating repeatedValue: UInt8, count: Int) {
980+
self.init(count: count)
981+
withUnsafeMutableBytes { (bytes: UnsafeMutablePointer<UInt8>) -> Void in
982+
memset(bytes, Int32(repeatedValue), count)
983+
}
984+
}
974985

975986
/// Initialize a `Data` with the specified size.
976987
///
@@ -1293,7 +1304,9 @@ public struct Data : ReferenceConvertible, Equatable, Hashable, RandomAccessColl
12931304
for byte in newElements {
12941305
self[idx] = byte
12951306
idx += 1
1296-
count = idx
1307+
if idx > count {
1308+
count = idx
1309+
}
12971310
}
12981311
}
12991312

TestFoundation/TestNSData.swift

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -90,6 +90,7 @@ class TestNSData: XCTestCase {
9090
("test_initDataWithCapacity", test_initDataWithCapacity),
9191
("test_initDataWithCount", test_initDataWithCount),
9292
("test_emptyStringToData", test_emptyStringToData),
93+
("test_repeatingValueInitialization", test_repeatingValueInitialization),
9394
]
9495
}
9596

@@ -1032,5 +1033,19 @@ extension TestNSData {
10321033
XCTAssertEqual(6 * MemoryLayout<MyStruct>.stride, byteCount)
10331034
}
10341035
}
1036+
1037+
func test_repeatingValueInitialization() {
1038+
var d = Data(repeating: 0x01, count: 3)
1039+
let elements = repeatElement(UInt8(0x02), count: 3) // ensure we fall into the sequence case
1040+
d.append(contentsOf: elements)
1041+
1042+
XCTAssertEqual(d[0], 0x01)
1043+
XCTAssertEqual(d[1], 0x01)
1044+
XCTAssertEqual(d[2], 0x01)
1045+
1046+
XCTAssertEqual(d[3], 0x02)
1047+
XCTAssertEqual(d[4], 0x02)
1048+
XCTAssertEqual(d[5], 0x02)
1049+
}
10351050
}
10361051

0 commit comments

Comments
 (0)