Skip to content

Commit

Permalink
Simplify Temporals.durationFromBigDecimalSeconds (#202)
Browse files Browse the repository at this point in the history
* Simplify Temporals.durationFromBigDecimalSeconds
* Pull out min and max into constants
* Avoid octal integer
  • Loading branch information
perceptron8 committed Jun 15, 2022
1 parent a32fd5d commit 58c9c6d
Showing 1 changed file with 13 additions and 10 deletions.
23 changes: 13 additions & 10 deletions src/main/java/org/threeten/extra/Temporals.java
Original file line number Diff line number Diff line change
Expand Up @@ -412,16 +412,9 @@ public static BigDecimal durationToBigDecimalSeconds(Duration duration) {
* @return a {@code Duration}, not null
*/
public static Duration durationFromBigDecimalSeconds(BigDecimal seconds) {
BigInteger nanos = seconds.setScale(9, RoundingMode.UP).movePointRight(9).toBigIntegerExact();
BigInteger[] divRem = nanos.divideAndRemainder(BigInteger.valueOf(1_000_000_000));
if (divRem[0].bitLength() > 63) {
if (divRem[0].signum() >= 1) {
return Duration.ofSeconds(Long.MAX_VALUE, 999_999_999);
} else {
return Duration.ofSeconds(Long.MIN_VALUE);
}
}
return Duration.ofSeconds(divRem[0].longValue(), divRem[1].intValue());
BigInteger nanos = seconds.setScale(9, RoundingMode.UP).max(BigDecimalSeconds.MIN).min(BigDecimalSeconds.MAX).unscaledValue();
BigInteger[] secondsNanos = nanos.divideAndRemainder(BigInteger.valueOf(1_000_000_000));
return Duration.ofSeconds(secondsNanos[0].longValue(), secondsNanos[1].intValue());
}

/**
Expand Down Expand Up @@ -474,4 +467,14 @@ public static Duration multiply(Duration duration, double multiplicand) {
return durationFromBigDecimalSeconds(amount);
}

/**
* Useful Duration constants expressed as BigDecimal seconds with a scale of 9.
*/
private static final class BigDecimalSeconds {
public static final BigDecimal MIN = BigDecimal.valueOf(Long.MIN_VALUE).add(BigDecimal.valueOf(0, 9));
public static final BigDecimal MAX = BigDecimal.valueOf(Long.MAX_VALUE).add(BigDecimal.valueOf(999_999_999, 9));

private BigDecimalSeconds() {
}
}
}

0 comments on commit 58c9c6d

Please sign in to comment.