Skip to content

Commit

Permalink
Implement fast path for Meter.Kind addition when both elements are .s…
Browse files Browse the repository at this point in the history
…ingle (#120)
  • Loading branch information
jsbean committed Nov 22, 2018
1 parent 38b61f6 commit 37779ce
Show file tree
Hide file tree
Showing 5 changed files with 16 additions and 3 deletions.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -163,7 +163,7 @@ let fractional = Meter(Fraction(3,5),16)
Ordinary and fractional meters can be concatenated into a single additive meter.

```Swift
let blueRondo = Meter(2,8) + Meter(2,8) + Meter(2,8) + Meter(3,8)
let blueRondo = Meter(Meter(2,8), Meter(2,8),Meter(2,8),Meter(3,8))
let czernowinSQm5 = Meter(Meter(1,4),Meter(3,16))
let czernowinSQm7 = Meter(Meter(1,4),Meter(Fraction(2,3),4))
```
Expand Down
8 changes: 7 additions & 1 deletion Sources/Duration/Meter/Meter.Kind.swift
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,13 @@ extension Meter.Kind: Additive {

/// The additive operation.
static func + (_ lhs: Meter.Kind, _ rhs: Meter.Kind) -> Meter.Kind {
return .additive([lhs,rhs])
switch (lhs,rhs) {
case let (.single(lhsBeats, lhsSubdivision), .single(rhsBeats, rhsSubdivision)):
let fraction = Fraction(lhsBeats, lhsSubdivision) + Fraction(rhsBeats, rhsSubdivision)
return .single(fraction.numerator, fraction.denominator)
default:
return .additive([lhs,rhs])
}
}
}

Expand Down
2 changes: 1 addition & 1 deletion Sources/Duration/Meter/Meter.swift
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ extension Meter: Additive {

/// - Returns: An additive meter composed of the two given meters.
public static func + (_ lhs: Meter, _ rhs: Meter) -> Meter {
return .init(kinds: [lhs.kind, rhs.kind])
return Meter(kind: lhs.kind + rhs.kind)
}
}

Expand Down
6 changes: 6 additions & 0 deletions Tests/DurationTests/MeterTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -67,4 +67,10 @@ class MeterTests: XCTestCase {
let _ = meters.sum.numerator
let _ = meters.sum.denominator
}

func testManyMetersSum() {
let meters = (0..<10_000).map { _ in Meter(Int.random(in: 1 ..< 8), 4) }
let sum: Meter = meters.sum
let _ = sum.numerator
}
}
1 change: 1 addition & 0 deletions Tests/DurationTests/XCTestManifests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,7 @@ extension MeterTests {
("testBeatOffsetsFractional", testBeatOffsetsFractional),
("testFractionalMeter", testFractionalMeter),
("testIrrationalMeter", testIrrationalMeter),
("testManyMetersSum", testManyMetersSum),
("testMetersSum", testMetersSum),
("testNormalMeter", testNormalMeter),
]
Expand Down

0 comments on commit 37779ce

Please sign in to comment.