graphics32 icon indicating copy to clipboard operation
graphics32 copied to clipboard

Clamp with negative Max

Open lamdalili opened this issue 5 years ago • 2 comments

In some situations GR32_LowLevel.Clamp(Value, Max: Integer) gives wrong result when Max hold negative value ie Clamp(pos,A-B) Original code:

  if Value > Max then 
    Result := Max
  else if Value < 0 then 
    Result := 0
  else
    Result := Value;

Correct version

  Result := Value;
  if Result > Max then
    Result := Max;
  if Result < 0 then
    Result := 0;

lamdalili avatar Jun 22 '19 13:06 lamdalili

Do you have any examples of places in the graphics32 code where the Max value can be negative? If so that is a bug.

As far as I know the Max value is assumed (i.e. required) to be >= 0 so the current implementation is correct and I'm not prepared to change this without input from the other contributors.

If it's important to your use of it it is trivial to create local version that behaves the way you want it to - as I'm sure you've already done.

andersmelander avatar Jul 02 '19 15:07 andersmelander

Do you have any examples of places in the graphics32 code where the Max value can be negative? If so that is a bug.

No I don't have any example ...but an implicit one can be found in TCustomRangeBar. AdjustPosition

procedure TCustomRangeBar.AdjustPosition;
begin
  if FPosition > Range - EffectiveWindow then
     FPosition := Range - EffectiveWindow;
  if FPosition < 0 then FPosition := 0;
end;

can be rewritten by any inattentive coder as: FPosition :=Clamp(FPosition ,Range - EffectiveWindow)

You can add the proposed code as new utility like ClampLength or ClampRange .

lamdalili avatar Jul 06 '19 11:07 lamdalili

No consideration

lamdalili avatar Apr 11 '23 06:04 lamdalili