MINOR: tools: add a float-to-ascii conversion function
We already had ultoa_r() and friends but nothing to emit inline floats.
This is now done with ftoa_r() and F2A/F2H. Note that the latter both use
the itoa_str[] as temporary storage and that the HTML format currently is
the exact same as the ASCII one. The trailing zeroes are always timmed so
these outputs are usable in user-visible output.
diff --git a/include/haproxy/tools.h b/include/haproxy/tools.h
index 948207a..37609ca 100644
--- a/include/haproxy/tools.h
+++ b/include/haproxy/tools.h
@@ -75,6 +75,7 @@
extern char *sltoa_r(long n, char *buffer, int size);
extern const char *ulltoh_r(unsigned long long n, char *buffer, int size);
size_t flt_trim(char *buffer, size_t num_start, size_t len);
+char *ftoa_r(double n, char *buffer, int size);
static inline const char *ultoa(unsigned long n)
{
return ultoa_r(n, itoa_str[0], sizeof(itoa_str[0]));
@@ -161,6 +162,32 @@
* function call (eg: printf), shared with the other similar functions making
* use of itoa_str[].
*/
+static inline const char *F2A(double n)
+{
+ const char *ret = ftoa_r(n, itoa_str[itoa_idx], sizeof(itoa_str[0]));
+ if (++itoa_idx >= NB_ITOA_STR)
+ itoa_idx = 0;
+ return ret;
+}
+
+/* returns a locally allocated string containing the HTML representation of
+ * the number 'n' in decimal. Up to NB_ITOA_STR calls may be used in the same
+ * function call (eg: printf), shared with the other similar functions making
+ * use of itoa_str[].
+ */
+static inline const char *F2H(double n)
+{
+ const char *ret = ftoa_r(n, itoa_str[itoa_idx], sizeof(itoa_str[0]));
+ if (++itoa_idx >= NB_ITOA_STR)
+ itoa_idx = 0;
+ return ret;
+}
+
+/* returns a locally allocated string containing the ASCII representation of
+ * the number 'n' in decimal. Up to NB_ITOA_STR calls may be used in the same
+ * function call (eg: printf), shared with the other similar functions making
+ * use of itoa_str[].
+ */
static inline const char *LIM2A(unsigned long n, const char *alt)
{
const char *ret = limit_r(n, itoa_str[itoa_idx], sizeof(itoa_str[0]), alt);
diff --git a/src/tools.c b/src/tools.c
index e94fed7..de5dfa8 100644
--- a/src/tools.c
+++ b/src/tools.c
@@ -568,6 +568,17 @@
return trim - buffer;
}
+/*
+ * This function simply returns a locally allocated string containing
+ * the ascii representation for number 'n' in decimal with useless trailing
+ * zeroes trimmed.
+ */
+char *ftoa_r(double n, char *buffer, int size)
+{
+ flt_trim(buffer, 0, snprintf(buffer, size, "%f", n));
+ return buffer;
+}
+
/* returns a locally allocated string containing the quoted encoding of the
* input string. The output may be truncated to QSTR_SIZE chars, but it is
* guaranteed that the string will always be properly terminated. Quotes are