Skip to content
Merged
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
13 changes: 12 additions & 1 deletion Semantics.Music/Duration.cs
Original file line number Diff line number Diff line change
Expand Up @@ -117,7 +117,18 @@ public static bool TryParse(string? text, [System.Diagnostics.CodeAnalysis.NotNu
return false;
}

result = Create(numerator, denominator);
// A negative denominator negates the numerator, so int.MinValue over an odd negative
// denominator reduces to a numerator past int.MaxValue. That is bad text, not a bug in the
// caller, so it fails the parse rather than escaping a Try method.
try
{
result = Create(numerator, denominator);
}
catch (OverflowException)
{
return false;
}

return true;
}

Expand Down
26 changes: 26 additions & 0 deletions Semantics.Test/Music/DurationTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -130,4 +130,30 @@ public void TryParseFailsOnMissingSlashOrZeroDenominator()
Assert.IsFalse(Duration.TryParse("1/0", out Duration? b));
Assert.IsNull(b);
}

[TestMethod]
[DataRow("-2147483648/-1")]
[DataRow("-2147483648/-3")]
public void TryParseFailsWhenTheReducedFractionDoesNotFitInInt(string text)
{
Assert.IsFalse(Duration.TryParse(text, out Duration? result));
Assert.IsNull(result);
_ = Assert.ThrowsExactly<FormatException>(() => Duration.Parse(text));
}

[TestMethod]
public void TryParseAcceptsIntMinValueOverANegativeDenominatorWhenTheReducedFractionFits()
{
Assert.IsTrue(Duration.TryParse("-2147483648/-2", out Duration? result));
Assert.AreEqual(Duration.Create(1 << 30, 1), result);
}

[TestMethod]
public void ContainerTryParseFailsRatherThanThrowingOnAnOverflowingDuration()
{
Assert.IsFalse(ChordEvent.TryParse("C:-2147483648/-1", out ChordEvent? chordEvent));
Assert.IsNull(chordEvent);
Assert.IsFalse(Progression.TryParse("4/4 C@-2147483648/-1", out Progression? progression));
Assert.IsNull(progression);
}
}
Loading