GUACAMOLE-1686: Add convenience function for converting integer to string.

This commit is contained in:
Virtually Nick 2023-12-28 13:59:20 -05:00
parent 2c796593b2
commit 69a616ceca
2 changed files with 33 additions and 0 deletions

View File

@ -29,6 +29,24 @@
#include <stddef.h>
#include <string.h>
/**
* Convert the provided unsigned integer into a string, returning the number of
* characters written into the destination string, or a negative value if an
* error occurs.
*
* @param dest
* The destination string to copy the data into, which should already be
* allocated and at a size that can handle the string representation of the
* inteer.
*
* @param integer
* The unsigned integer to convert to a string.
*
* @return
* The number of characters written into the dest string.
*/
int guac_itoa(char* restrict dest, unsigned int integer);
/**
* Copies a limited number of bytes from the given source string to the given
* destination buffer. The resulting buffer will always be null-terminated,

View File

@ -22,6 +22,7 @@
#include "guacamole/mem.h"
#include <stddef.h>
#include <stdio.h>
#include <string.h>
/**
@ -44,6 +45,20 @@
*/
#define REMAINING(n, length) (((n) < (length)) ? 0 : ((n) - (length)))
int guac_itoa(char* restrict dest, unsigned int integer) {
/* Determine size of string. */
int str_size = snprintf(dest, 0, "%i", integer);
/* If an error occurs, just return that and skip the conversion. */
if (str_size < 0)
return str_size;
/* Do the conversion and return. */
return snprintf(dest, (str_size + 1), "%i", integer);
}
size_t guac_strlcpy(char* restrict dest, const char* restrict src, size_t n) {
#ifdef HAVE_STRLCPY