Deduplicate leftZeroPadding
We have two functions, leftZeroPadding, and padZeros that effectively do
the same thing. leftZeroPadding has only one usage, and padZeros is
debatably more efficient (given it doesn't need to construct an
intermediate string). Move the one usage of leftZeroPadding to
padZeros, and remove leftZeroPadding.
One minor change needs to be made to padZeros, in that it needs to
accept a long int instead of an int, given that some implementations use
long int as their duration object.
Tested: Unit tests pass. Good coverage on time functions.
Signed-off-by: Ed Tanous <edtanous@google.com>
Change-Id: Icbec45787ff940d098e18b61741b7476f4263558
diff --git a/redfish-core/include/utils/time_utils.hpp b/redfish-core/include/utils/time_utils.hpp
index 2733ba2..9b13147 100644
--- a/redfish-core/include/utils/time_utils.hpp
+++ b/redfish-core/include/utils/time_utils.hpp
@@ -30,12 +30,18 @@
constexpr intmax_t dayDuration = static_cast<intmax_t>(24 * 60 * 60);
using Days = std::chrono::duration<long long, std::ratio<dayDuration>>;
-inline void leftZeroPadding(std::string& str, const std::size_t padding)
+// Creates a string from an integer in the most efficient way possible without
+// using std::locale. Adds an exact zero pad based on the pad input parameter.
+// Does not handle negative numbers.
+inline std::string padZeros(int64_t value, size_t pad)
{
- if (str.size() < padding)
+ std::string result(pad, '0');
+ for (int64_t val = value; pad > 0; pad--)
{
- str.insert(0, padding - str.size(), '0');
+ result[pad - 1] = static_cast<char>('0' + val % 10);
+ val /= 10;
}
+ return result;
}
template <typename FromTime>
@@ -210,9 +216,8 @@
if (seconds.count() != 0 || ms.count() != 0)
{
fmt += std::to_string(seconds.count()) + ".";
- std::string msStr = std::to_string(ms.count());
- details::leftZeroPadding(msStr, 3);
- fmt += msStr + "S";
+ fmt += details::padZeros(ms.count(), 3);
+ fmt += "S";
}
return fmt;
@@ -265,20 +270,6 @@
return std::tuple<IntType, unsigned, unsigned>(y + (m <= 2), m, d);
}
-// Creates a string from an integer in the most efficient way possible without
-// using std::locale. Adds an exact zero pad based on the pad input parameter.
-// Does nt handle negative numbers.
-inline std::string padZeros(int value, size_t pad)
-{
- std::string result(pad, '0');
- for (int val = value; pad > 0; pad--)
- {
- result[pad - 1] = static_cast<char>('0' + val % 10);
- val /= 10;
- }
- return result;
-}
-
template <typename IntType, typename Period>
std::string toISO8061ExtendedStr(std::chrono::duration<IntType, Period> t)
{