Add Math.Clamp methods#7242
Conversation
| <Member Name="Clamp(System.Single,System.Single)" /> | ||
| <Member Name="Clamp(System.UInt16,System.UInt16)" /> | ||
| <Member Name="Clamp(System.UInt32,System.UInt32)" /> | ||
| <Member Name="Clamp(System.UInt64,System.UInt64)" /> |
There was a problem hiding this comment.
These lines should have 3 parameters instead of 2
There was a problem hiding this comment.
knew I was doing something wrong! Thansk
With the current JIT adding an additional branch for the check will prevent the method from being inlined. For better or worse this can be avoided by using It's worth noting here that if the method is inlined and if the min/max arguments are constants (that's pretty common) then the check will be eliminated.
It may make sense to return NaN if any argument is NaN but currently The results you get if don't add special handling for NaNs (directly or indirectly by using |
|
@mikedn thanks for taking a look - I'll add the argument validation and the inlining attribute as you suggested, and will remove the |
| return value; | ||
| } | ||
|
|
||
| private static void ThrowMinMaxException(object min, object max) |
There was a problem hiding this comment.
Using object will result in boxing at the callsite, that will make clamp code larger. You could probably make this generic so boxing moves from the caller to the callee.
Avoid boxing at call site
|
|
||
| private static void ThrowMinMaxException<T>(T min, T max) | ||
| { | ||
| throw new ArgumentException(Environment.GetResourceString("Argument_MinMaxValue", min, max)); |
There was a problem hiding this comment.
would it potentially help debugging if the value appeared in the exception message also?
There was a problem hiding this comment.
It does, unless I misunderstand. The message is "'{0}' cannot be greater than {1}."
|
Has any consideration been given for a generic |
|
@bendono Yes, it has been discussed in this issue: dotnet/corefx#467 |
|
@jkotas PTAL, thanks |
|
LGTM. Thanks! |
|
I was just looking at another PR updating src/mscorlib/model.xml, and I realised that they also update src/mscorlib/ref/mscorlib.cs. |
|
cc @weshaggard |
|
We are enabling people to start exposing APIs as .NET Core specific (see dotnet/corefx#11886). So if that is going to happen before we make the switch to building everything against S.P.CoreLib then these will need to be added to mscorlib ref. In either case it doesn't hurt to include them. |
Commit migrated from dotnet/coreclr@fe98399
Open Questions
Math.Max(Math.Min(value, max), min)as I was unsure whether the JIT would inline these method calls (plus the code reads more easily IMO)dotnet/corefx#467
/cc @sgtfrankieboy @weshaggard @mellinoe @mikedn