2022-07-05 17:49:45 +02:00
|
|
|
#ifdef HAVE_DYN_MEM_ALLOC
|
2022-05-16 10:59:20 +02:00
|
|
|
|
2022-05-02 15:29:02 +02:00
|
|
|
#include <stdlib.h>
|
|
|
|
|
#include <string.h>
|
|
|
|
|
#include <stdio.h>
|
|
|
|
|
#include "mem.h"
|
|
|
|
|
#include "mem_utils.h"
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* Format an unsigned number up to 32-bit into memory into an ASCII string.
|
|
|
|
|
*
|
|
|
|
|
* @param[in] value Value to write in memory
|
2022-04-26 18:15:53 +02:00
|
|
|
* @param[out] length number of characters written to memory
|
2022-05-02 15:29:02 +02:00
|
|
|
*
|
2022-05-05 15:21:39 +02:00
|
|
|
* @return pointer to memory area or \ref NULL if the allocation failed
|
2022-05-02 15:29:02 +02:00
|
|
|
*/
|
2022-07-19 11:49:18 +02:00
|
|
|
char *mem_alloc_and_format_uint(uint32_t value, uint8_t *const length) {
|
|
|
|
|
char *mem_ptr;
|
|
|
|
|
uint32_t value_copy;
|
|
|
|
|
uint8_t size;
|
2022-05-02 15:29:02 +02:00
|
|
|
|
2022-07-19 11:49:18 +02:00
|
|
|
size = 1; // minimum size, even if 0
|
2022-04-26 18:15:53 +02:00
|
|
|
value_copy = value;
|
2022-07-19 11:49:18 +02:00
|
|
|
while (value_copy >= 10) {
|
2022-04-26 18:15:53 +02:00
|
|
|
value_copy /= 10;
|
|
|
|
|
size += 1;
|
|
|
|
|
}
|
|
|
|
|
// +1 for the null character
|
2022-07-19 11:49:18 +02:00
|
|
|
if ((mem_ptr = mem_alloc(sizeof(char) * (size + 1)))) {
|
2022-06-29 14:08:08 +02:00
|
|
|
snprintf(mem_ptr, (size + 1), "%u", value);
|
2022-07-19 11:49:18 +02:00
|
|
|
mem_dealloc(sizeof(char)); // to skip the null character
|
|
|
|
|
if (length != NULL) {
|
2022-05-04 11:27:51 +02:00
|
|
|
*length = size;
|
|
|
|
|
}
|
2022-04-26 18:15:53 +02:00
|
|
|
}
|
|
|
|
|
return mem_ptr;
|
2022-05-02 15:29:02 +02:00
|
|
|
}
|
2022-05-05 15:21:39 +02:00
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* Allocate and align, required when dealing with pointers of multi-bytes data
|
|
|
|
|
* like structures that will be dereferenced at runtime.
|
|
|
|
|
*
|
|
|
|
|
* @param[in] size the size of the data we want to allocate in memory
|
|
|
|
|
* @param[in] alignment the byte alignment needed
|
|
|
|
|
*
|
|
|
|
|
* @return pointer to the memory area, \ref NULL if the allocation failed
|
|
|
|
|
*/
|
2022-07-19 11:49:18 +02:00
|
|
|
void *mem_alloc_and_align(size_t size, size_t alignment) {
|
|
|
|
|
uint8_t align_diff = (uintptr_t) mem_alloc(0) % alignment;
|
2022-05-05 15:21:39 +02:00
|
|
|
|
2022-07-19 11:49:18 +02:00
|
|
|
if (align_diff > 0) // alignment needed
|
2022-05-05 15:21:39 +02:00
|
|
|
{
|
2022-07-19 11:49:18 +02:00
|
|
|
if (mem_alloc(alignment - align_diff) == NULL) {
|
2022-05-05 15:21:39 +02:00
|
|
|
return NULL;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
return mem_alloc(size);
|
|
|
|
|
}
|
2022-05-16 10:59:20 +02:00
|
|
|
|
2022-07-19 11:49:18 +02:00
|
|
|
#endif // HAVE_DYN_MEM_ALLOC
|