1 /*
2  * Copyright 2022 Meta
3  *
4  * SPDX-License-Identifier: Apache-2.0
5  */
6 
7 #include <inttypes.h>
8 #include <limits.h>
9 #include <stdbool.h>
10 #include <stdint.h>
11 
12 #include <zephyr/sys/time_units.h>
13 #include <zephyr/ztest.h>
14 
15 /**
16  * @brief Test @ref z_tmcvt for robustness against intermediate value overflow.
17  *
18  * With input
19  * ```
20  * [t0, t1, t2] = [
21  *   UINT64_MAX / to_hz - 1,
22  *   UINT64_MAX / to_hz,
23  *   UINT64_MAX / to_hz + 1,
24  * ]
25  * ```
26  *
27  * passed through @ref z_tmcvt, we expect a linear sequence:
28  * ```
29  * [
30  *   562949953369140,
31  *   562949953399658,
32  *   562949953430175,
33  * ]
34  * ```
35  *
36  * If an overflow occurs, we see something like the following:
37  * ```
38  * [
39  *   562949953369140,
40  *   562949953399658,
41  *   8863,
42  * ]
43  * ```
44  */
ZTEST(time_units,test_z_tmcvt_for_overflow)45 ZTEST(time_units, test_z_tmcvt_for_overflow)
46 {
47 	const uint32_t from_hz = 32768UL;
48 	const uint32_t to_hz = 1000000000UL;
49 
50 	zassert_equal(562949953369140ULL,
51 		      z_tmcvt(UINT64_MAX / to_hz - 1, from_hz, to_hz, true, false, false, false));
52 	zassert_equal(562949953399658ULL,
53 		      z_tmcvt(UINT64_MAX / to_hz, from_hz, to_hz, true, false, false, false));
54 	zassert_equal(562949953430175ULL,
55 		      z_tmcvt(UINT64_MAX / to_hz + 1, from_hz, to_hz, true, false, false, false));
56 }
57