Skip to content
Open
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
9 changes: 9 additions & 0 deletions Sources/Algorithms/Product.swift
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,15 @@ public struct Product2Sequence<Base1: Sequence, Base2: Collection> {
extension Product2Sequence: Sequence {
public typealias Element = (Base1.Element, Base2.Element)

public var underestimatedCount: Int {
// Watch out if at least one source doesn't actually implement their
// `underestimatedCount` in constant time
// (which `Collection` can permit, unlike `Sequence`).
let (product, overflow) = base1.underestimatedCount
.multipliedReportingOverflow(by: base2.underestimatedCount)
return overflow ? .max : product
}

/// The iterator for a `Product2Sequence` sequence.
public struct Iterator: IteratorProtocol {
@usableFromInline
Expand Down
7 changes: 7 additions & 0 deletions Tests/SwiftAlgorithmsTests/ProductTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,13 @@ final class ProductTests: XCTestCase {
func testProductDistanceFromTo() {
let p = product([1, 2], "abc")
XCTAssertEqual(p.distance(from: p.startIndex, to: p.endIndex), 6)
XCTAssertLessThanOrEqual(p.underestimatedCount, 6)
}

func testOverflowingUnderestimatedCount() {
let p = product(repeatElement(true, count: .max / 2),
repeatElement(false, count: .max / 2))
XCTAssertLessThanOrEqual(p.underestimatedCount, .max)
}

func testProductIndexTraversals() {
Expand Down
Loading