Skip to content

Commit

Permalink
Better std.algorithm.comparison.clamp error messages
Browse files Browse the repository at this point in the history
  • Loading branch information
burner committed Mar 15, 2023
1 parent 1b89dcf commit d8c627e
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 11 deletions.
8 changes: 8 additions & 0 deletions changelog/clamp_assert_message.dd
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
Better static assert messages for `std.algorithm.comparison.clamp`

Until now, `clamp` used a template constraint to check if the passed types
could be used. If they were not, it was very tedious to figure out why.

As the template constraint is not used for overload resolution
the constrains are moved into static asserts with expressive error
messages.
23 changes: 12 additions & 11 deletions std/algorithm/comparison.d
Original file line number Diff line number Diff line change
Expand Up @@ -577,19 +577,20 @@ Returns:
and `T3` are different.
*/
T1 clamp(T1, T2, T3)(T1 val, T2 lower, T3 upper)
if (is(typeof(val.lessThan(lower) ? lower : val.greaterThan(upper) ? upper : val))
&& (is(T2 : T1) && is(T3 : T1)))
// cannot use :
// `if (is(typeof(val.lessThan(lower) ? lower : val.greaterThan(upper) ? upper : val) : T1))
// because of https://issues.dlang.org/show_bug.cgi?id=16235.
// Once that is fixed, we can simply use the ternary in both the template constraint
// and the template body
in
{
static assert(is(T2 : T1), "T2 of type '", T2.stringof
, "' must be implicitly convertible to type of T1 '"
, T1.stringof, "'");
static assert(is(T3 : T1), "T3 of type '", T3.stringof
, "' must be implicitly convertible to type of T1 '"
, T1.stringof, "'");

assert(!lower.greaterThan(upper), "Lower can't be greater than upper.");
}
do
{

// `if (is(typeof(val.lessThan(lower) ? lower : val.greaterThan(upper) ? upper : val) : T1))
// because of https://issues.dlang.org/show_bug.cgi?id=16235.
// Once that is fixed, we can simply use the ternary in both the template constraint
// and the template body
if (val.lessThan(lower))
return lower;
else if (val.greaterThan(upper))
Expand Down

0 comments on commit d8c627e

Please sign in to comment.