Skip to content

Commit 7d292f9

Browse files
committed
Improves differentiator initializer safeguards.
1 parent 5cef907 commit 7d292f9

File tree

1 file changed

+19
-2
lines changed

1 file changed

+19
-2
lines changed

Sources/DataSources/Differentiator.swift

Lines changed: 19 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ public enum DifferentiatorError
1313
, CustomDebugStringConvertible {
1414
case DuplicateItem(item: Any)
1515
case DuplicateSection(section: Any)
16+
case InvalidInitializerImplementation(section: Any, expectedItems: Any, expectedIdentifier: Any)
1617
}
1718

1819
extension DifferentiatorError {
@@ -22,6 +23,10 @@ extension DifferentiatorError {
2223
return "Duplicate item \(item)"
2324
case let .DuplicateSection(section):
2425
return "Duplicate section \(section)"
26+
case let InvalidInitializerImplementation(section, expectedItems, expectedIdentifier):
27+
return "Wrong initializer implementation for: \(section)\n" +
28+
"Expected it should return items: \(expectedItems)\n" +
29+
"Expected it should have id: \(expectedIdentifier)"
2530
}
2631
}
2732
}
@@ -284,6 +289,16 @@ public func differencesForSectionedView<S: AnimatableSectionModelType>(
284289
return result
285290
}
286291

292+
private extension AnimatableSectionModelType {
293+
init(safeOriginal: Self, safeItems: [Item]) throws {
294+
self.init(original: safeOriginal, items: safeItems)
295+
296+
if self.items != safeItems || self.identity != safeOriginal.identity {
297+
throw DifferentiatorError.InvalidInitializerImplementation(section: self, expectedItems: safeItems, expectedIdentifier: safeOriginal.identity)
298+
}
299+
}
300+
}
301+
287302
struct CommandGenerator<S: AnimatableSectionModelType> {
288303
let initialSections: [S]
289304
let finalSections: [S]
@@ -545,7 +560,7 @@ struct CommandGenerator<S: AnimatableSectionModelType> {
545560
}
546561
}
547562

548-
afterDeleteState.append(S(original: initialSection, items: afterDeleteItems))
563+
afterDeleteState.append(try S(safeOriginal: initialSection, safeItems: afterDeleteItems))
549564
}
550565
// }
551566

@@ -620,7 +635,9 @@ struct CommandGenerator<S: AnimatableSectionModelType> {
620635
items.append(self.finalSections[finalIndex.sectionIndex].items[finalIndex.itemIndex])
621636
}
622637

623-
return S(original: s, items: items)
638+
let modifiedSection = try S(safeOriginal: s, safeItems: items)
639+
640+
return modifiedSection
624641
}
625642
else {
626643
try rxPrecondition(false, "This is weird, this shouldn't happen")

0 commit comments

Comments
 (0)