Skip to content
New issue

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

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

Already on GitHub? # to your account

Implement underestimatedCount for Product2Sequence #255

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
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
@@ -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
7 changes: 7 additions & 0 deletions Tests/SwiftAlgorithmsTests/ProductTests.swift
Original file line number Diff line number Diff line change
@@ -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() {
Loading