rspec/rules/S6179/cfamily/rule.adoc
2023-10-09 13:50:05 +02:00

52 lines
1.7 KiB
Plaintext

== Why is this an issue?
{cpp}20 introduced the standard algorithms to compute the midpoint between two values and linear interpolation for a given coefficient.
``++std::midpoint(a, b)++`` computes the midpoint, or average, or arithmetic mean of two values ``++a++`` and ``++b++``: ``++(a+b)/2++``. The result is halfway from ``++a++`` to ``++b++``, and if ``++a++`` and ``++b++`` are pointers, it points to the middle of a contiguous memory segment between the two. A naive midpoint computation might suffer from a possible overflow or be inefficient. That is why, in most cases, ``++std::midpoint++`` is preferable.
``++std::lerp(a, b, t)++`` returns linear interpolation between values ``++a++`` and ``++b++`` with a coefficient ``++t++``: ``++a+t*(a-b)++``, where ``++t++`` is between 0 and 1.
This rule reports computations that should be replaced with ``++std::midpoint++`` or ``++std::lerp++``.
=== Noncompliant code example
[source,cpp]
----
auto avg1 = (a + b)/2; // Noncompliant: might overflow
auto avg2 = a + (b - a)/2; // Noncompliant
auto third = a + (b - a)*0.3f; // Noncompliant
----
=== Compliant solution
[source,cpp]
----
auto avg1 = std::midpoint(a, b);
auto avg2 = std::midpoint(a, b);
auto third = std::lerp(a, b, 0.3f);
----
== Resources
* {cpp} reference - https://en.cppreference.com/w/cpp/numeric/midpoint[std::midpoint]
* {cpp} reference - https://en.cppreference.com/w/cpp/numeric/lerp[std::lerp]
ifdef::env-github,rspecator-view[]
'''
== Implementation Specification
(visible only on this page)
=== Message
* Use "std::midpoint" to compute the midpoint between X and Y.
* Use "std::lerp" to compute linear interpolation between X and Y.
endif::env-github,rspecator-view[]