Skip to content

Commit 4d11beb

Browse files
spevansparkera
authored andcommitted
Fix Data(capacity:) and Data(count:) to return non-optional (#538)
- This matches the Foundation API in Darwin
1 parent cde6534 commit 4d11beb

File tree

5 files changed

+32
-25
lines changed

5 files changed

+32
-25
lines changed

Foundation/Data.swift

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -217,12 +217,18 @@ public struct Data : ReferenceConvertible, CustomStringConvertible, Equatable, H
217217

218218
/// Initialize a `Data` with the specified size.
219219
///
220+
/// This initializer doesn't necessarily allocate the requested memory right away. `Data` allocates additional memory as needed, so `capacity` simply establishes the initial capacity. When it does allocate the initial memory, though, it allocates the specified amount.
221+
///
222+
/// This method sets the `count` of the data to 0.
223+
///
224+
/// If the capacity specified in `capacity` is greater than four memory pages in size, this may round the amount of requested memory up to the nearest full page.
225+
///
220226
/// - parameter capacity: The size of the data.
221-
public init?(capacity: Int) {
227+
public init(capacity: Int) {
222228
if let d = NSMutableData(capacity: capacity) {
223229
_wrapped = _SwiftNSData(immutableObject: d)
224230
} else {
225-
return nil
231+
fatalError("Unable to allocate data of the requested capacity")
226232
}
227233
}
228234

@@ -281,11 +287,11 @@ public struct Data : ReferenceConvertible, CustomStringConvertible, Equatable, H
281287
/// Initialize a `Data` with the specified count of zeroed bytes.
282288
///
283289
/// - parameter count: The number of bytes the data initially contains.
284-
public init?(count: Int) {
290+
public init(count: Int) {
285291
if let memory = calloc(1, count)?.bindMemory(to: UInt8.self, capacity: count) {
286292
self.init(bytesNoCopy: memory, count: count, deallocator: .free)
287293
} else {
288-
return nil
294+
fatalError("Unable to allocate data of the requested count")
289295
}
290296
}
291297

Foundation/NSString.swift

Lines changed: 11 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -844,20 +844,18 @@ extension NSString {
844844
if convertedLen != len {
845845
return nil // Not able to do it all...
846846
}
847-
848-
var data = Data(count: reqSize)
849-
if data != nil {
850-
if 0 < reqSize {
851-
data!.count = data!.withUnsafeMutableBytes { (mutableBytes: UnsafeMutablePointer<UInt8>) -> Int in
852-
if __CFStringEncodeByteStream(_cfObject, 0, len, true, cfStringEncoding, lossy ? (encoding == String.Encoding.ascii.rawValue ? 0xFF : 0x3F) : 0, UnsafeMutablePointer<UInt8>(mutableBytes), reqSize, &reqSize) == convertedLen {
853-
return reqSize
854-
} else {
855-
fatalError("didn't convert all characters")
856-
}
857-
}
858847

859-
return data
848+
if 0 < reqSize {
849+
var data = Data(count: reqSize)
850+
data.count = data.withUnsafeMutableBytes { (mutableBytes: UnsafeMutablePointer<UInt8>) -> Int in
851+
if __CFStringEncodeByteStream(_cfObject, 0, len, true, cfStringEncoding, lossy ? (encoding == String.Encoding.ascii.rawValue ? 0xFF : 0x3F) : 0, UnsafeMutablePointer<UInt8>(mutableBytes), reqSize, &reqSize) == convertedLen {
852+
return reqSize
853+
} else {
854+
fatalError("didn't convert all characters")
855+
}
860856
}
857+
858+
return data
861859
}
862860
return nil
863861
}
@@ -1145,7 +1143,7 @@ extension NSString {
11451143
NSURLErrorKey: dest,
11461144
])
11471145
}
1148-
var mData = Data(count: numBytes)!
1146+
var mData = Data(count: numBytes)
11491147
// The getBytes:... call should hopefully not fail, given it succeeded above, but check anyway (mutable string changing behind our back?)
11501148
var used = 0
11511149
// This binds mData memory to UInt8 because Data.withUnsafeMutableBytes does not handle raw pointers.

TestFoundation/TestNSData.swift

Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,8 @@ class TestNSData: XCTestCase {
4242
("test_rangeOfData",test_rangeOfData),
4343
("test_initMutableDataWithLength", test_initMutableDataWithLength),
4444
("test_replaceBytes", test_replaceBytes),
45-
("test_initDataWithCount", test_initDataWithCount)
45+
("test_initDataWithCapacity", test_initDataWithCapacity),
46+
("test_initDataWithCount", test_initDataWithCount),
4647
]
4748
}
4849

@@ -378,12 +379,14 @@ class TestNSData: XCTestCase {
378379
XCTAssertEqual(mData, expected)
379380
}
380381

382+
func test_initDataWithCapacity() {
383+
let data = Data(capacity: 123)
384+
XCTAssertEqual(data.count, 0)
385+
}
386+
381387
func test_initDataWithCount() {
382388
let dataSize = 1024
383-
guard let data = Data(count: dataSize) else {
384-
XCTFail("Could not create zeroed data")
385-
return
386-
}
389+
let data = Data(count: dataSize)
387390
XCTAssertEqual(data.count, dataSize)
388391
if let index = (data.index { $0 != 0 }) {
389392
XCTFail("Byte at index: \(index) is not zero: \(data[index])")

TestFoundation/TestNSJSONSerialization.swift

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -787,7 +787,7 @@ extension TestNSJSONSerialization {
787787
func test_jsonObjectToOutputStreamFile() {
788788
let dict = ["a":["b":1]]
789789
do {
790-
let filePath = createTestFile("TestFileOut.txt",_contents: Data(capacity: 128)!)
790+
let filePath = createTestFile("TestFileOut.txt",_contents: Data(capacity: 128))
791791
if filePath != nil {
792792
let outputStream = NSOutputStream(toFileAtPath: filePath!, append: true)
793793
outputStream?.open()

TestFoundation/TestNSStream.swift

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -125,7 +125,7 @@ class TestNSStream : XCTestCase {
125125
}
126126

127127
func test_outputStreamCreationToFile() {
128-
let filePath = createTestFile("TestFileOut.txt", _contents: Data(capacity: 256)!)
128+
let filePath = createTestFile("TestFileOut.txt", _contents: Data(capacity: 256))
129129
if filePath != nil {
130130
let outputStream = NSOutputStream(toFileAtPath: filePath!, append: true)
131131
XCTAssertEqual(Stream.Status.notOpen, outputStream!.streamStatus)
@@ -159,7 +159,7 @@ class TestNSStream : XCTestCase {
159159
}
160160

161161
func test_outputStreamCreationWithUrl() {
162-
let filePath = createTestFile("TestFileOut.txt", _contents: Data(capacity: 256)!)
162+
let filePath = createTestFile("TestFileOut.txt", _contents: Data(capacity: 256))
163163
if filePath != nil {
164164
let outputStream = NSOutputStream(url: URL(fileURLWithPath: filePath!), append: true)
165165
XCTAssertEqual(Stream.Status.notOpen, outputStream!.streamStatus)

0 commit comments

Comments
 (0)