RFR: 8301226: Add clamp() methods to java.lang.Math and to StrictMath [v8]

Karl T duke at openjdk.org
Tue Feb 14 21:07:56 UTC 2023


On Tue, 7 Feb 2023 12:53:25 GMT, Tagir F. Valeev <tvaleev at openjdk.org> wrote:

>> clamp() methods added to Math and StrictMath
>> 
>> `int clamp(long, int, int)` is somewhat different, as it accepts a `long` value and safely clamps it to an `int` range. Other overloads work with a particular type (long, float and double). Using similar approach in other cases (e.g. `float clamp(double, float, float)`) may cause accidental precision loss even if the value is within range, so I decided to avoid this.
>> 
>> In all cases, `max >= min` precondition should met. For double and float we additionally order `-0.0 < 0.0`, similarly to what Math.max or Double.compare do. In double and float overloads I try to keep at most one arg-check comparison on common path, so the order of checks might look unusual.
>> 
>> For tests, I noticed that tests in java/lang/Math don't use any testing framework (even newer tests), so I somehow mimic the approach of neighbour tests.
>
> Tagir F. Valeev has updated the pull request incrementally with one additional commit since the last revision:
> 
>   Comments in tests

I agree that using `var` for primitive types is maybe not the best idea, but there are thousands (or millions) of Java developers out there doing such things.
Personally, I rarely use the `var` keyword because I still prefer explicit types.

> In this particular case, you lose nothing, as even if the resulting variable is unexpectedly int, you don't lose precision and you don't overflow.

Well there is a overflow risk if calculations are done.
Here is some "dummy" code that demonstrates an int overflow:

~~~java
var a = 1234L;
var b = Math.clamp( a, 0, 100 );
var c = b * 2_000_000_000;
System.out.println( c );
~~~

With `int clamp( long value, int min, int max )`, this outputs `-1863462912`. (int overflow)
But with `int clamp( int value, int min, int max )`, this outputs `200000000000`.

Still think that the API would be cleaner with `int clamp( int value, int min, int max )` 😉

-------------

PR: https://git.openjdk.org/jdk/pull/12428


More information about the core-libs-dev mailing list