On Sun, 9 Jun 2024 at 11:00, Akihiko Odaki <akihiko.od...@daynix.com> wrote: > > On 2024/06/09 5:20, Phil Dennis-Jordan wrote: > > Both hw/input/hid.c and hw/usb/dev-wacom.c define identical versions > > (aside from code formatting) of a clamping function, int_clamp(). > > (marked inline) To avoid duplication and to enable further re-use, this > > change moves the function into qemu/cutils.h. > > Wht about replacing int_clamp(a, b, c) with MIN(MAX(a, b), c)? > MIN(MAX(a, b), c) has a few advantages: > - It works with any integer types > (so you can replace even uint_clamp() in hw/display/vga.c)
Well, that can of course also be achieved by wrapping MIN(MAX(v, min), max) in a new CLAMP(v, min, max) macro. > - It makes clear that b is the minimum value and c is the maximum value > while it is not with int_clamp() I guess this aspect is rather subjective. When I see a MIN(MAX( construct I generally feel the need to triple-check to make sure which way around it is. (The minimum value is passed to MAX, the maximum to MIN.) On the other hand, there is precedent and convention for a clamp() function with that order of parameters in other APIs and programming languages: C++ std::clamp, Java Math.clamp(), OpenCL kernels and OpenGL shaders can both use a built-in clamp() function, etc. > - It is already used in other places. The CLAMP macro would be my preferred compromise, although I don't know how keen everyone is on introducing a new macro named after a short, generic word.