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.
This commit is contained in:
Willy Tarreau 2021-05-08 07:35:00 +02:00
parent 56d1d8dab0
commit ae03d26eea
2 changed files with 38 additions and 0 deletions

View File

@ -75,6 +75,7 @@ extern char *lltoa_r(long long int n, char *buffer, int size);
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]));
@ -156,6 +157,32 @@ static inline const char *U2H(unsigned long long n)
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 *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

View File

@ -568,6 +568,17 @@ size_t flt_trim(char *buffer, size_t num_start, size_t len)
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