Small refactoring to the format uint memory utils function

This commit is contained in:
Alexandre Paillier
2022-04-26 18:15:53 +02:00
parent 149e20cd11
commit 01ba4fb41f
4 changed files with 30 additions and 16 deletions

View File

@@ -29,8 +29,7 @@ static bool format_field_type_array_levels_string(const void *lvl_ptr, uint8_t l
case ARRAY_DYNAMIC:
break;
case ARRAY_FIXED_SIZE:
// max value = 255, 3 characters max
mem_alloc_and_format_uint(array_size, 3);
mem_alloc_and_format_uint(array_size, NULL);
break;
default:
// should not be in here :^)
@@ -81,8 +80,7 @@ static bool format_field_string(const void *field_ptr)
// should not be in here :^)
break;
}
// max value = 256, 3 characters max
mem_alloc_and_format_uint(field_size, 3);
mem_alloc_and_format_uint(field_size, NULL);
}
// field type array levels

View File

@@ -2,6 +2,7 @@
#define ENCODE_TYPE_H_
#include <stdint.h>
#include <stdbool.h>
const char *encode_type(const void *const structs_array,
const char *const struct_name,

View File

@@ -24,20 +24,34 @@ char *mem_alloc_and_copy_char(char c)
* Format an unsigned number up to 32-bit into memory into an ASCII string.
*
* @param[in] value Value to write in memory
* @param[in] max_chars Maximum number of characters that could be written
* @param[out] length number of characters written to memory
*
* @return how many characters have been written in memory, 0 in case of an allocation error
* @return pointer to memory area or \ref NULL if the allocated failed
*/
uint8_t mem_alloc_and_format_uint(uint32_t value, const uint8_t max_chars)
char *mem_alloc_and_format_uint(uint32_t value,
uint8_t *const length)
{
char *ptr;
uint8_t written_chars;
char *mem_ptr;
uint32_t value_copy;
uint8_t size;
if ((ptr = mem_alloc(sizeof(char) * max_chars)) == NULL)
size = 1; // minimum size, even if 0
value_copy = value;
while (value_copy >= 10)
{
value_copy /= 10;
size += 1;
}
// +1 for the null character
if ((mem_ptr = mem_alloc(sizeof(char) * (size + 1))) == NULL)
{
return 0;
}
written_chars = sprintf(ptr, "%u", value);
mem_dealloc(max_chars - written_chars); // in case it ended up being less
return written_chars;
snprintf(mem_ptr, (size + 1), "%u", value);
mem_dealloc(sizeof(char)); // to skip the null character
if (length != NULL)
{
*length = size;
}
return mem_ptr;
}

View File

@@ -4,8 +4,9 @@
#include <stdint.h>
#include <stdbool.h>
char *mem_alloc_and_copy_char(char c);
void *mem_alloc_and_copy(const void *data, size_t size);
uint8_t mem_alloc_and_format_uint(uint32_t value, const uint8_t max_chars);
char *mem_alloc_and_copy_char(char c);
void *mem_alloc_and_copy(const void *data, size_t size);
char *mem_alloc_and_format_uint(uint32_t value,
uint8_t *const written_chars);
#endif // MEM_UTILS_H_