Skip to content

Parity: NSCoding stragglers: NSIndexPath #2492

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Aug 28, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
96 changes: 93 additions & 3 deletions Foundation/NSIndexPath.swift
Original file line number Diff line number Diff line change
Expand Up @@ -40,12 +40,80 @@ open class NSIndexPath : NSObject, NSCopying, NSSecureCoding {
self.init(indexes: [index])
}

fileprivate enum NSCodingKeys {
static let lengthKey = "NSIndexPathLength"
static let singleValueKey = "NSIndexPathValue"
static let dataKey = "NSIndexPathData"
}

open func encode(with aCoder: NSCoder) {
NSUnimplemented()
guard aCoder.allowsKeyedCoding else {
aCoder.failWithError(NSError(domain: NSCocoaErrorDomain, code: NSCoderReadCorruptError, userInfo: [NSLocalizedDescriptionKey: "Cannot be serialized with a coder that does not support keyed archives"]))
return
}

let length = self.length
aCoder.encode(length, forKey: NSCodingKeys.lengthKey)
switch length {
case 0:
break
case 1:
aCoder.encode(index(atPosition: 0), forKey: NSCodingKeys.singleValueKey)
default:
var sequence = PackedUIntSequence(data: Data(capacity: length * 2 + 16))
for position in 0 ..< length {
sequence.append(UInt(index(atPosition: position)))
}
aCoder.encode(sequence.data, forKey: NSCodingKeys.dataKey)
}
}

public required init?(coder aDecoder: NSCoder) {
NSUnimplemented()
public required convenience init?(coder aDecoder: NSCoder) {
guard aDecoder.allowsKeyedCoding else {
aDecoder.failWithError(NSError(domain: NSCocoaErrorDomain, code: NSCoderReadCorruptError, userInfo: [NSLocalizedDescriptionKey: "Cannot be deserialized with a coder that does not support keyed archives"]))
return nil
}

guard aDecoder.containsValue(forKey: NSCodingKeys.lengthKey) else {
aDecoder.failWithError(NSError(domain: NSCocoaErrorDomain, code: NSCoderReadCorruptError, userInfo: [NSLocalizedDescriptionKey: "Decoder did not provide a length value for the indexPath."]))
return nil
}

let len = aDecoder.decodeInteger(forKey: NSCodingKeys.lengthKey)
guard len > 0 else {
self.init()
return
}

switch len {
case 0:
self.init()
return

case 1:
guard aDecoder.containsValue(forKey: NSCodingKeys.singleValueKey) else {
aDecoder.failWithError(NSError(domain: NSCocoaErrorDomain, code: NSCoderReadCorruptError, userInfo: [NSLocalizedDescriptionKey: "Decoder did not provide indexPath data."]))
return nil
}

let index = aDecoder.decodeInteger(forKey: NSCodingKeys.singleValueKey)
self.init(index: index)
return

default:
guard let bytes = aDecoder.decodeObject(of: NSData.self, forKey: NSCodingKeys.dataKey) else {
aDecoder.failWithError(NSError(domain: NSCocoaErrorDomain, code: NSCoderReadCorruptError, userInfo: [NSLocalizedDescriptionKey: "Range data missing."]))
return nil
}

let sequence = PackedUIntSequence(data: bytes._swiftObject)
guard sequence.count == len else {
aDecoder.failWithError(NSError(domain: NSCocoaErrorDomain, code: NSCoderReadCorruptError, userInfo: [NSLocalizedDescriptionKey: "Range data did not match expected length."]))
return nil
}

self.init(indexes: sequence.integers)
}
}

public static var supportsSecureCoding: Bool { return true }
Expand Down Expand Up @@ -110,6 +178,28 @@ open class NSIndexPath : NSObject, NSCopying, NSSecureCoding {
}
return .orderedSame
}

open override var hash: Int {
var hasher = Hasher()
for i in 0 ..< length {
hasher.combine(index(atPosition: i))
}
return hasher.finalize()
}

open override func isEqual(_ object: Any?) -> Bool {
guard let indexPath = object as? NSIndexPath,
indexPath.length == self.length else { return false }

let length = self.length
for i in 0 ..< length {
if index(atPosition: i) != indexPath.index(atPosition: i) {
return false
}
}

return true
}
}


Expand Down
93 changes: 51 additions & 42 deletions Foundation/NSIndexSet.swift
Original file line number Diff line number Diff line change
Expand Up @@ -858,52 +858,61 @@ extension NSIndexSet : _StructTypeBridgeable, _SwiftBridgeable {

// MARK: NSCoding

extension NSIndexSet {
struct PackedUIntSequence {
var data: Data
init(data: Data) {
self.data = data
}

var count: Int {
var result = 0
for byte in data {
if byte < 128 {
result += 1
}
internal struct PackedUIntSequence {
var data: Data
init(data: Data = Data()) {
self.data = data
}

var count: Int {
var result = 0
for byte in data {
if byte < 128 {
result += 1
}
return result
}

var unsignedIntegers: [UInt] {
var result: [UInt] = []
var index = data.startIndex
while index < data.endIndex {
let fromIndex = unsignedInt(atIndex: index)
result.append(fromIndex.value)
index = fromIndex.nextIndex
}
return result
return result
}

var unsignedIntegers: [UInt] {
var result: [UInt] = []
var index = data.startIndex
while index < data.endIndex {
let fromIndex = unsignedInt(atIndex: index)
result.append(fromIndex.value)
index = fromIndex.nextIndex
}

private func unsignedInt(atIndex index: Int) -> (value: UInt, nextIndex: Int) {
var result = UInt(data[index])
if result < 128 {
return (value: result, nextIndex: index + 1)
} else {
let fromNext = unsignedInt(atIndex: index + 1)
result = (result - 128) + 128 * fromNext.value
return (value: result, nextIndex: fromNext.nextIndex)
}
return result
}

var integers: [Int] {
var result: [Int] = []
var index = data.startIndex
while index < data.endIndex {
let fromIndex = unsignedInt(atIndex: index)
result.append(Int(fromIndex.value))
index = fromIndex.nextIndex
}

mutating func append(_ value: UInt) {
if value > 127 {
data.append(UInt8(128 + (value % 128)))
append(value / 128)
} else {
data.append(UInt8(value))
}
return result
}

private func unsignedInt(atIndex index: Int) -> (value: UInt, nextIndex: Int) {
var result = UInt(data[index])
if result < 128 {
return (value: result, nextIndex: index + 1)
} else {
let fromNext = unsignedInt(atIndex: index + 1)
result = (result - 128) + 128 * fromNext.value
return (value: result, nextIndex: fromNext.nextIndex)
}
}

mutating func append(_ value: UInt) {
if value > 127 {
data.append(UInt8(128 + (value % 128)))
append(value / 128)
} else {
data.append(UInt8(value))
}
}
}
19 changes: 19 additions & 0 deletions TestFoundation/FixtureValues.swift
Original file line number Diff line number Diff line change
Expand Up @@ -200,6 +200,22 @@ enum Fixtures {
return (try Fixtures.indexSetManyRanges.make()).mutableCopy() as! NSMutableIndexSet
}

// ===== NSIndexPath =====

static let indexPathEmpty = TypedFixture<NSIndexPath>("NSIndexPath-Empty") {
return NSIndexPath()
}

static let indexPathOneIndex = TypedFixture<NSIndexPath>("NSIndexPath-OneIndex") {
return NSIndexPath(index: 52)
}

static let indexPathManyIndices = TypedFixture<NSIndexPath>("NSIndexPath-ManyIndices") {
var indexPath = IndexPath()
indexPath.append([4, 8, 15, 16, 23, 42])
return indexPath as NSIndexPath
}

// ===== NSSet, NSMutableSet =====

static let setOfNumbers = TypedFixture<NSSet>("NSSet-Numbers") {
Expand Down Expand Up @@ -284,6 +300,9 @@ enum Fixtures {
AnyFixture(Fixtures.mutableIndexSetEmpty),
AnyFixture(Fixtures.mutableIndexSetOneRange),
AnyFixture(Fixtures.mutableIndexSetManyRanges),
AnyFixture(Fixtures.indexPathEmpty),
AnyFixture(Fixtures.indexPathOneIndex),
AnyFixture(Fixtures.indexPathManyIndices),
AnyFixture(Fixtures.setOfNumbers),
AnyFixture(Fixtures.setEmpty),
AnyFixture(Fixtures.mutableSetOfNumbers),
Expand Down
Binary file not shown.
Binary file not shown.
Binary file not shown.
129 changes: 75 additions & 54 deletions TestFoundation/TestIndexPath.swift
Original file line number Diff line number Diff line change
Expand Up @@ -9,60 +9,6 @@

class TestIndexPath: XCTestCase {

static var allTests: [(String, (TestIndexPath) -> () throws -> Void)] {
return [
("testEmpty", testEmpty),
("testSingleIndex", testSingleIndex),
("testTwoIndexes", testTwoIndexes),
("testManyIndexes", testManyIndexes),
("testCreateFromSequence", testCreateFromSequence),
("testCreateFromLiteral", testCreateFromLiteral),
("testDropLast", testDropLast),
("testDropLastFromEmpty", testDropLastFromEmpty),
("testDropLastFromSingle", testDropLastFromSingle),
("testDropLastFromPair", testDropLastFromPair),
("testDropLastFromTriple", testDropLastFromTriple),
("testStartEndIndex", testStartEndIndex),
("testIterator", testIterator),
("testIndexing", testIndexing),
("testCompare", testCompare),
("testHashing", testHashing),
("testEquality", testEquality),
("testSubscripting", testSubscripting),
("testAppending", testAppending),
("testAppendEmpty", testAppendEmpty),
("testAppendEmptyIndexPath", testAppendEmptyIndexPath),
("testAppendManyIndexPath", testAppendManyIndexPath),
("testAppendEmptyIndexPathToSingle", testAppendEmptyIndexPathToSingle),
("testAppendSingleIndexPath", testAppendSingleIndexPath),
("testAppendSingleIndexPathToSingle", testAppendSingleIndexPathToSingle),
("testAppendPairIndexPath", testAppendPairIndexPath),
("testAppendManyIndexPathToEmpty", testAppendManyIndexPathToEmpty),
("testAppendByOperator", testAppendByOperator),
("testAppendArray", testAppendArray),
("testRanges", testRanges),
("testRangeFromEmpty", testRangeFromEmpty),
("testRangeFromSingle", testRangeFromSingle),
("testRangeFromPair", testRangeFromPair),
("testRangeFromMany", testRangeFromMany),
("testRangeReplacementSingle", testRangeReplacementSingle),
("testRangeReplacementPair", testRangeReplacementPair),
("testMoreRanges", testMoreRanges),
("testIteration", testIteration),
("testDescription", testDescription),
("testBridgeToObjC", testBridgeToObjC),
("testForceBridgeFromObjC", testForceBridgeFromObjC),
("testConditionalBridgeFromObjC", testConditionalBridgeFromObjC),
("testUnconditionalBridgeFromObjC", testUnconditionalBridgeFromObjC),
("testObjcBridgeType", testObjcBridgeType),
("test_AnyHashableContainingIndexPath", test_AnyHashableContainingIndexPath),
("test_AnyHashableCreatedFromNSIndexPath", test_AnyHashableCreatedFromNSIndexPath),
("test_unconditionallyBridgeFromObjectiveC", test_unconditionallyBridgeFromObjectiveC),
("test_slice_1ary", test_slice_1ary),
("test_copy", test_copy),
]
}

func testEmpty() {
let ip = IndexPath()
XCTAssertEqual(ip.count, 0)
Expand Down Expand Up @@ -790,4 +736,79 @@ class TestIndexPath: XCTestCase {
XCTAssertEqual(nip2.length, 3)
XCTAssertEqual(nip1, nip2)
}

let fixtures: [TypedFixture<NSIndexPath>] = [
Fixtures.indexPathEmpty,
Fixtures.indexPathOneIndex,
Fixtures.indexPathManyIndices,
]

func testCodingRoundtrip() throws {
for fixture in fixtures {
try fixture.assertValueRoundtripsInCoder()
}
}

func testLoadedValuesMatch() throws {
for fixture in fixtures {
try fixture.assertLoadedValuesMatch()
}
}

static var allTests: [(String, (TestIndexPath) -> () throws -> Void)] {
return [
("testEmpty", testEmpty),
("testSingleIndex", testSingleIndex),
("testTwoIndexes", testTwoIndexes),
("testManyIndexes", testManyIndexes),
("testCreateFromSequence", testCreateFromSequence),
("testCreateFromLiteral", testCreateFromLiteral),
("testDropLast", testDropLast),
("testDropLastFromEmpty", testDropLastFromEmpty),
("testDropLastFromSingle", testDropLastFromSingle),
("testDropLastFromPair", testDropLastFromPair),
("testDropLastFromTriple", testDropLastFromTriple),
("testStartEndIndex", testStartEndIndex),
("testIterator", testIterator),
("testIndexing", testIndexing),
("testCompare", testCompare),
("testHashing", testHashing),
("testEquality", testEquality),
("testSubscripting", testSubscripting),
("testAppending", testAppending),
("testAppendEmpty", testAppendEmpty),
("testAppendEmptyIndexPath", testAppendEmptyIndexPath),
("testAppendManyIndexPath", testAppendManyIndexPath),
("testAppendEmptyIndexPathToSingle", testAppendEmptyIndexPathToSingle),
("testAppendSingleIndexPath", testAppendSingleIndexPath),
("testAppendSingleIndexPathToSingle", testAppendSingleIndexPathToSingle),
("testAppendPairIndexPath", testAppendPairIndexPath),
("testAppendManyIndexPathToEmpty", testAppendManyIndexPathToEmpty),
("testAppendByOperator", testAppendByOperator),
("testAppendArray", testAppendArray),
("testRanges", testRanges),
("testRangeFromEmpty", testRangeFromEmpty),
("testRangeFromSingle", testRangeFromSingle),
("testRangeFromPair", testRangeFromPair),
("testRangeFromMany", testRangeFromMany),
("testRangeReplacementSingle", testRangeReplacementSingle),
("testRangeReplacementPair", testRangeReplacementPair),
("testMoreRanges", testMoreRanges),
("testIteration", testIteration),
("testDescription", testDescription),
("testBridgeToObjC", testBridgeToObjC),
("testForceBridgeFromObjC", testForceBridgeFromObjC),
("testConditionalBridgeFromObjC", testConditionalBridgeFromObjC),
("testUnconditionalBridgeFromObjC", testUnconditionalBridgeFromObjC),
("testObjcBridgeType", testObjcBridgeType),
("test_AnyHashableContainingIndexPath", test_AnyHashableContainingIndexPath),
("test_AnyHashableCreatedFromNSIndexPath", test_AnyHashableCreatedFromNSIndexPath),
("test_unconditionallyBridgeFromObjectiveC", test_unconditionallyBridgeFromObjectiveC),
("test_slice_1ary", test_slice_1ary),
("test_copy", test_copy),
("testCodingRoundtrip", testCodingRoundtrip),
("testLoadedValuesMatch", testLoadedValuesMatch),
]
}

}