Skip to content

Commit

Permalink
switch timespan mult/div to use doubles until creating the timespan
Browse files Browse the repository at this point in the history
  • Loading branch information
sovdeeth committed Feb 25, 2025
1 parent f32613d commit cc7d195
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 9 deletions.
21 changes: 12 additions & 9 deletions src/main/java/ch/njol/skript/classes/data/DefaultOperations.java
Original file line number Diff line number Diff line change
Expand Up @@ -99,21 +99,24 @@ public class DefaultOperations {
// Timespan - Number
// Number - Timespan
Arithmetics.registerOperation(Operator.MULTIPLICATION, Timespan.class, Number.class, (left, right) -> {
long scalar = right.longValue();
if (scalar < 0)
double scalar = right.doubleValue();
if (scalar < 0 || !Double.isFinite(scalar))
return null;
return new Timespan(Math2.multiplyClamped(left.getAs(TimePeriod.MILLISECOND), scalar));
double value = left.getAs(TimePeriod.MILLISECOND) * scalar;
return new Timespan((long) Math.min(value, Long.MAX_VALUE));
}, (left, right) -> {
long scalar = left.longValue();
if (scalar < 0)
double scalar = left.doubleValue();
if (scalar < 0 || !Double.isFinite(scalar))
return null;
return new Timespan(scalar * right.getAs(TimePeriod.MILLISECOND));
double value = right.getAs(TimePeriod.MILLISECOND) * scalar;
return new Timespan((long) Math.min(value, Long.MAX_VALUE));
});
Arithmetics.registerOperation(Operator.DIVISION, Timespan.class, Number.class, (left, right) -> {
long scalar = right.longValue();
if (scalar <= 0)
double scalar = right.doubleValue();
if (scalar < 0 || !Double.isFinite(scalar))
return null;
return new Timespan(left.getAs(TimePeriod.MILLISECOND) / scalar);
double value = left.getAs(TimePeriod.MILLISECOND) / scalar;
return new Timespan((long) Math.min(value, Long.MAX_VALUE));
});

// Timespan / Timespan = Number
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
options:
max-timespan: 9223372036854775807 milliseconds

test "floating point timespan math":
assert (0.9 * 5 seconds) is 4.5 seconds with "failed basic floating point multiplication"
assert (1 * 5 seconds) is 5 seconds with "failed basic integer multiplication"
assert (0.0 * 5 seconds) is 0 seconds with "failed multiplication by 0"
assert (5 seconds / 5) is 1 seconds with "failed integer division"
assert (5 seconds / 2.5) is 2 seconds with "failed floating point division"
assert (5 seconds / infinity value) is not set with "Division by infinity unexpectedly returned real value"

assert (5 seconds * 10 ^ 308) is {@max-timespan} with "failed to clamp to the long max value"

0 comments on commit cc7d195

Please sign in to comment.