core/units/distance.c
| Line | Branch | Exec | Source |
|---|---|---|---|
| 1 | /** | ||
| 2 | * @file distance.c | ||
| 3 | * @brief Pure distance conversions and formatting, no SDK behind them. | ||
| 4 | * | ||
| 5 | * @ingroup lib_core | ||
| 6 | */ | ||
| 7 | #include "units/distance.h" | ||
| 8 | |||
| 9 | #include <stdio.h> | ||
| 10 | |||
| 11 | 4 | const char *distance_unit(bool miles) | |
| 12 | { | ||
| 13 |
2/2✓ Branch 0 taken 2 times.
✓ Branch 1 taken 2 times.
|
4 | return miles ? "MI" : "KM"; |
| 14 | } | ||
| 15 | |||
| 16 | 6 | void distance_format_value(char *buffer, size_t size, int meters, bool miles) | |
| 17 | { | ||
| 18 |
2/2✓ Branch 0 taken 1 time.
✓ Branch 1 taken 5 times.
|
6 | if (meters < 0) |
| 19 | { | ||
| 20 | 1 | meters = 0; | |
| 21 | } | ||
| 22 | |||
| 23 | // tenths of the display unit in whole integer math so no float library gets linked in. | ||
| 24 | // a tenth of a mile is 160.9344 m so scale by 625/100584 (10000/1609344 reduced) and | ||
| 25 | // a tenth of a km is a flat 100 m. adding half the divisor rounds to the nearest tenth | ||
| 26 | // and the miles product stays inside 32 bits below about 3400 km | ||
| 27 |
2/2✓ Branch 0 taken 3 times.
✓ Branch 1 taken 3 times.
|
6 | int tenths = miles ? (meters * 625 + 50292) / 100584 : (meters + 50) / 100; |
| 28 | 6 | snprintf(buffer, size, "%d.%d", tenths / 10, tenths % 10); | |
| 29 | 6 | } | |
| 30 | |||
| 31 | 2 | void distance_format(char *buffer, size_t size, int meters, bool miles) | |
| 32 | { | ||
| 33 | char value[12]; | ||
| 34 | 2 | distance_format_value(value, sizeof(value), meters, miles); | |
| 35 | 2 | snprintf(buffer, size, "%s %s", value, distance_unit(miles)); | |
| 36 | 2 | } | |
| 37 |