View source code Display the source code in std/algorithm/comparison.d from which this page was generated on github. 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. Page wiki View or edit the community-maintained wiki page associated with this page.

Function std.algorithm.comparison.clamp

Clamps a value into the given bounds.

This functions is equivalent to max(lower, min(upper,val)).

Prototype

auto clamp(T1, T2, T3)(
  T1 val,
  T2 lower,
  T3 upper
);

Parameters

NameDescription
val The value to clamp.
lower The lower bound of the clamp.
upper The upper bound of the clamp.

Returns

Returns val, if it is between lower and upper. Otherwise returns the nearest of the two.

Example

assert(clamp(2, 1, 3) == 2);
assert(clamp(0, 1, 3) == 1);
assert(clamp(4, 1, 3) == 3);

assert(clamp(1, 1, 1) == 1);

assert(clamp(5, -1, 2u) == 2);

Authors

Andrei Alexandrescu

License

Boost License 1.0.

Comments