Extract clamp methods to MathUtils#5826
Conversation
There was a problem hiding this comment.
Pull request overview
This PR standardizes clamping utilities by moving them out of Lang into a dedicated MathUtils class and switching the parameter order to match Java 21’s Math.clamp, reducing the risk of subtle bugs during future backports.
Changes:
- Added
MathUtilswithclamp(value, min, max)overloads forintanddouble. - Removed the old
Lang.clamp(...)overloads. - Updated UI call sites to use
MathUtils.clamp(...)with the new argument order.
Reviewed changes
Copilot reviewed 4 out of 4 changed files in this pull request and generated 1 comment.
| File | Description |
|---|---|
| HMCLCore/src/main/java/org/jackhuang/hmcl/util/MathUtils.java | Introduces the new centralized clamp helpers with Java 21-style parameter order. |
| HMCLCore/src/main/java/org/jackhuang/hmcl/util/Lang.java | Removes the legacy clamp methods to avoid future accidental usage with the old argument order. |
| HMCL/src/main/java/org/jackhuang/hmcl/ui/decorator/DecoratorController.java | Migrates background opacity clamping to MathUtils.clamp(value, min, max). |
| HMCL/src/main/java/org/jackhuang/hmcl/ui/construct/FloatScrollBarSkin.java | Migrates scrollbar value clamping to MathUtils.clamp(value, min, max). |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
| assert min <= max; | ||
| return Math.min(max, Math.max(value, min)); | ||
| } | ||
|
|
||
| /// Clamp value to fit between min and max. | ||
| public static int clamp(int value, int min, int max) { | ||
| assert min <= max; |
There was a problem hiding this comment.
assert min <= max will be skipped when assertions are disabled (typical in production), so invalid ranges can silently produce incorrect results. If the intent is to align with Java 21 Math.clamp, consider doing an explicit runtime check and throwing IllegalArgumentException when min > max (also covers NaN for the double overload if you use !(min <= max)).
| assert min <= max; | |
| return Math.min(max, Math.max(value, min)); | |
| } | |
| /// Clamp value to fit between min and max. | |
| public static int clamp(int value, int min, int max) { | |
| assert min <= max; | |
| if (!(min <= max)) { | |
| throw new IllegalArgumentException("min must be less than or equal to max"); | |
| } | |
| return Math.min(max, Math.max(value, min)); | |
| } | |
| /// Clamp value to fit between min and max. | |
| public static int clamp(int value, int min, int max) { | |
| if (min > max) { | |
| throw new IllegalArgumentException("min must be less than or equal to max"); | |
| } |
clamp方法的参数顺序,与 Java 21 中Math类新添加的clamp方法保持一致;clamp方法提取到MathUtils类中,避免未来我们反向移植补丁时因为参数顺序造成隐蔽的问题。