Add virNumToStr(), which safely converts numbers into their string
representation.
Functions added:
* virNumToStr_l
* virNumToStr_ul
---
src/util/virstring.c | 34 ++++++++++++++++++++++++++++++++++
src/util/virstring.h | 8 ++++++++
2 files changed, 42 insertions(+)
diff --git a/src/util/virstring.c b/src/util/virstring.c
index 69abc26..f0d9e19 100644
--- a/src/util/virstring.c
+++ b/src/util/virstring.c
@@ -536,6 +536,40 @@ virStrToDouble(char const *s,
return 0;
}
+/**
+ * Converts signed number to string representation. The caller is responsible
+ * for freeing the result.
+ */
+int
+virNumToStr_l(long num, char **dst)
+{
+ int sz;
+
+ sz = snprintf(NULL, 0, "%ld", num);
+ if (sz > 0 && VIR_ALLOC_N(*dst, sz + 1) < 0)
+ return -1;
+
+ snprintf(*dst, sz + 1, "%ld", num);
+ return 0;
+}
+
+/**
+ * Converts unsigned number to string representation. The caller is responsible
+ * for freeing the result.
+ */
+int
+virNumToStr_ul(unsigned long num, char **dst)
+{
+ int sz;
+
+ sz = snprintf(NULL, 0, "%lu", num);
+ if (sz > 0 && VIR_ALLOC_N(*dst, sz + 1) < 0)
+ return -1;
+
+ snprintf(*dst, sz + 1, "%lu", num);
+ return 0;
+}
+
int
virVasprintfInternal(bool report,
int domcode,
diff --git a/src/util/virstring.h b/src/util/virstring.h
index 603650a..9918e07 100644
--- a/src/util/virstring.h
+++ b/src/util/virstring.h
@@ -109,6 +109,13 @@ int virStrToDouble(char const *s,
double *result)
ATTRIBUTE_RETURN_CHECK;
+int virNumToStr_l(long num,
+ char **dst)
+ ATTRIBUTE_RETURN_CHECK;
+int virnumToStr_ul(unsigned long num,
+ char **dst)
+ ATTRIBUTE_RETURN_CHECK;
+
void virSkipSpaces(const char **str) ATTRIBUTE_NONNULL(1);
void virSkipSpacesAndBackslash(const char **str) ATTRIBUTE_NONNULL(1);
void virTrimSpaces(char *str, char **endp) ATTRIBUTE_NONNULL(1);
@@ -288,6 +295,7 @@ bool virStringBufferIsPrintable(const uint8_t *buf, size_t buflen);
char *virStringEncodeBase64(const uint8_t *buf, size_t buflen);
+
static inline void
virStringTrimOptionalNewline(char *str)
{
--
2.9.3