sys: time_units: Increase range of z_tmcvt

Avoid result overflow due to intermediate product overflow.
Algorithm was multiplying input value by target frequency
before dividing it by source frequency. If target frequency was
high (e.g. conversion to nanoseconds) it could easily lead to
overflow even though final result would not overflow. Adjusting
algorithm to avoid that.

Note, that typically this code is resolved at compile time so
it will not impact performance as long as it can be resolved.

Signed-off-by: Krzysztof Chruscinski <krzysztof.chruscinski@nordicsemi.no>
This commit is contained in:
Krzysztof Chruscinski 2022-01-05 15:10:28 +01:00 committed by Anas Nashif
commit fb5334d2cf

View file

@ -132,7 +132,7 @@ static TIME_CONSTEXPR ALWAYS_INLINE uint64_t z_tmcvt(uint64_t t, uint32_t from_h
if (result32) { if (result32) {
return (uint32_t)((t * to_hz + off) / from_hz); return (uint32_t)((t * to_hz + off) / from_hz);
} else { } else {
return (t * to_hz + off) / from_hz; return (t / from_hz) * to_hz + ((t % from_hz) * to_hz + off) / from_hz;
} }
} }
} }