Skip to content

Commit 3c60204

Browse files
author
Tim Vermeulen
committed
Ensure CommonPrefix.Iterator keeps returning nil after it has done so once
1 parent 506f2aa commit 3c60204

File tree

2 files changed

+15
-1
lines changed

2 files changed

+15
-1
lines changed

Sources/Algorithms/CommonPrefix.swift

+6-1
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,9 @@ extension CommonPrefix: Sequence {
4444
@usableFromInline
4545
internal let areEquivalent: (Base.Element, Other.Element) -> Bool
4646

47+
@usableFromInline
48+
internal var isDone = false
49+
4750
@inlinable
4851
internal init(
4952
base: Base.Iterator,
@@ -56,11 +59,13 @@ extension CommonPrefix: Sequence {
5659
}
5760

5861
public mutating func next() -> Base.Element? {
59-
if let next = base.next(),
62+
if !isDone,
63+
let next = base.next(),
6064
let otherNext = other.next(),
6165
areEquivalent(next, otherNext) {
6266
return next
6367
} else {
68+
isDone = true
6469
return nil
6570
}
6671
}

Tests/SwiftAlgorithmsTests/CommonPrefixTests.swift

+9
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,15 @@ final class CommonPrefixTests: XCTestCase {
4343
XCTAssertLazyCollection([1, 2, 3].lazy.commonPrefix(with: [4, 5, 6]))
4444
}
4545

46+
func testCommonPrefixIteratorKeepsReturningNil() {
47+
var iter = AnySequence("12A34").commonPrefix(with: "12B34").makeIterator()
48+
XCTAssertEqual(iter.next(), "1")
49+
XCTAssertEqual(iter.next(), "2")
50+
XCTAssertEqual(iter.next(), nil)
51+
XCTAssertEqual(iter.next(), nil)
52+
XCTAssertEqual(iter.next(), nil)
53+
}
54+
4655
func testCommonSuffix() {
4756
func testCommonSuffix(of a: String, and b: String, equals c: String) {
4857
XCTAssertEqualSequences(a.commonSuffix(with: b, by: ==), c)

0 commit comments

Comments
 (0)