Skip to content

Commit 64adba6

Browse files
committed
Implement underestimatedCount for Product2Sequence
Add corresponding tests, one for an overflowed count, and one producing a proper count.
1 parent 0e939e7 commit 64adba6

File tree

2 files changed

+16
-0
lines changed

2 files changed

+16
-0
lines changed

Sources/Algorithms/Product.swift

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,15 @@ public struct Product2Sequence<Base1: Sequence, Base2: Collection> {
2929
extension Product2Sequence: Sequence {
3030
public typealias Element = (Base1.Element, Base2.Element)
3131

32+
public var underestimatedCount: Int {
33+
// Watch out if at least one source doesn't actually implement their
34+
// `underestimatedCount` in constant time
35+
// (which `Collection` can permit, unlike `Sequence`).
36+
let (product, overflow) = base1.underestimatedCount
37+
.multipliedReportingOverflow(by: base2.underestimatedCount)
38+
return overflow ? .max : product
39+
}
40+
3241
/// The iterator for a `Product2Sequence` sequence.
3342
public struct Iterator: IteratorProtocol {
3443
@usableFromInline

Tests/SwiftAlgorithmsTests/ProductTests.swift

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,13 @@ final class ProductTests: XCTestCase {
3737
func testProductDistanceFromTo() {
3838
let p = product([1, 2], "abc")
3939
XCTAssertEqual(p.distance(from: p.startIndex, to: p.endIndex), 6)
40+
XCTAssertLessThanOrEqual(p.underestimatedCount, 6)
41+
}
42+
43+
func testOverflowingUnderestimatedCount() {
44+
let p = product(repeatElement(true, count: .max / 2),
45+
repeatElement(false, count: .max / 2))
46+
XCTAssertLessThanOrEqual(p.underestimatedCount, .max)
4047
}
4148

4249
func testProductIndexTraversals() {

0 commit comments

Comments
 (0)