View source code
Display the source code in std/algorithm/comparison.d from which this
page was generated on github.
Report a bug
If you spot a problem with this page, click here to create a
Bugzilla issue.
Improve this page
Quickly fork, edit online, and submit a pull request for this page.
Requires a signed-in GitHub account. This works well for small changes.
If you'd like to make larger changes you may want to consider using
local clone.
Function std.algorithm.comparison.clamp
Clamps val
into the given bounds. Result has the same type as val
.
T1 clamp(T1, T2, T3)
(
T1 val,
T2 lower,
T3 upper
)
if (is(typeof(val .lessThan(lower) ? lower : val .greaterThan(upper) ? upper : val) : T1));
Parameters
Name | Description |
---|---|
val | The value to clamp. |
lower | The lower bound of the clamp. |
upper | The upper bound of the clamp. |
Returns
lower
if val
is less than lower
, upper
if val
is greater than
upper
, and val
in all other cases. Comparisons are made
correctly (using lessThan
and the return value
is converted to the return type using the standard integer coversion rules
greaterThan
) even if the signedness of T1
, T2
,
and T3
are different.
Example
writeln(clamp(2, 1, 3)); // 2
writeln(clamp(0, 1, 3)); // 1
writeln(clamp(4, 1, 3)); // 3
writeln(clamp(1, 1, 1)); // 1
writeln(clamp(5, -1, 2u)); // 2
auto x = clamp(42, uint .max, uint .max);
static assert(is(typeof(x) == int));
writeln(x); // -1
Authors
License
Copyright © 1999-2022 by the D Language Foundation | Page generated by ddox.