| Line | Branch | Exec | Source |
|---|---|---|---|
| 1 | // ====================================================================== | ||
| 2 | // \title format.cpp | ||
| 3 | // \author mstarch | ||
| 4 | // \brief cpp file for c-string format function as a implementation using snprintf | ||
| 5 | // ====================================================================== | ||
| 6 | #include <Fw/Types/format.hpp> | ||
| 7 | #include <cstdio> | ||
| 8 | #include <limits> | ||
| 9 | |||
| 10 | 1 | Fw::FormatStatus Fw::stringFormat(char* destination, const FwSizeType maximumSize, const char* formatString, ...) { | |
| 11 | 1 | va_list args; | |
| 12 | 1 | va_start(args, formatString); | |
| 13 | 1 | FormatStatus status = Fw::stringFormat(destination, maximumSize, formatString, args); | |
| 14 | 1 | va_end(args); | |
| 15 | 1 | return status; | |
| 16 | } | ||
| 17 | |||
| 18 | 23 | Fw::FormatStatus Fw::stringFormat(char* destination, | |
| 19 | const FwSizeType maximumSize, | ||
| 20 | const char* formatString, | ||
| 21 | va_list args) { | ||
| 22 | 23 | Fw::FormatStatus formatStatus = Fw::FormatStatus::SUCCESS; | |
| 23 | // Check destination pointer | ||
| 24 |
2/4✓ Branch 0 taken 23 times.
✗ Branch 1 not taken.
✗ Branch 2 not taken.
✓ Branch 3 taken 23 times.
|
23 | if (destination == nullptr || maximumSize == 0) { |
| 25 | ✗ | return Fw::FormatStatus::OTHER_ERROR; | |
| 26 | } | ||
| 27 | // Force null termination in error cases | ||
| 28 | 23 | destination[0] = 0; | |
| 29 | // Check format string | ||
| 30 |
1/2✗ Branch 0 not taken.
✓ Branch 1 taken 23 times.
|
23 | if (formatString == nullptr) { |
| 31 | ✗ | formatStatus = Fw::FormatStatus::INVALID_FORMAT_STRING; | |
| 32 | } | ||
| 33 | // Must allow the compiler to choose the correct type for comparison | ||
| 34 |
1/2✗ Branch 1 not taken.
✓ Branch 2 taken 23 times.
|
23 | else if (maximumSize > std::numeric_limits<size_t>::max()) { |
| 35 | ✗ | formatStatus = Fw::FormatStatus::SIZE_OVERFLOW; | |
| 36 | } else { | ||
| 37 | // Format string is intentionally a runtime parameter; suppressing static analysis warning | ||
| 38 |
1/2✗ Branch 0 not taken.
✓ Branch 1 taken 23 times.
|
23 | int needed_size = vsnprintf(destination, static_cast<size_t>(maximumSize), formatString, args); // NOLINT |
| 39 | 23 | destination[maximumSize - 1] = 0; // Force null-termination | |
| 40 |
1/2✗ Branch 0 not taken.
✓ Branch 1 taken 23 times.
|
23 | if (needed_size < 0) { |
| 41 | ✗ | formatStatus = Fw::FormatStatus::OTHER_ERROR; | |
| 42 |
1/2✗ Branch 0 not taken.
✓ Branch 1 taken 23 times.
|
23 | } else if (static_cast<FwSizeType>(needed_size) >= maximumSize) { |
| 43 | ✗ | formatStatus = Fw::FormatStatus::OVERFLOWED; | |
| 44 | } | ||
| 45 | } | ||
| 46 | 23 | return formatStatus; | |
| 47 | } | ||
| 48 |