Files
app-ethereum/src_common/mem.c

66 lines
1.5 KiB
C
Raw Normal View History

2022-10-05 10:21:52 +02:00
/**
* Dynamic allocator that uses a fixed-length buffer that is hopefully big enough
*
* The two functions alloc & dealloc use the buffer as a simple stack.
* Especially useful when an unpredictable amount of data will be received and have to be stored
* during the transaction but discarded right after.
*/
#ifdef HAVE_DYN_MEM_ALLOC
2022-05-02 14:41:00 +02:00
#include <stdint.h>
#include "mem.h"
2022-09-01 10:18:41 +02:00
#define SIZE_MEM_BUFFER 8192
2022-07-19 11:49:18 +02:00
static uint8_t mem_buffer[SIZE_MEM_BUFFER];
static size_t mem_idx;
2022-05-02 14:41:00 +02:00
/**
* Initializes the memory buffer index
*/
2022-07-19 11:49:18 +02:00
void mem_init(void) {
2022-05-02 14:41:00 +02:00
mem_idx = 0;
}
/**
* Resets the memory buffer index
*/
2022-07-19 11:49:18 +02:00
void mem_reset(void) {
2022-05-02 14:41:00 +02:00
mem_init();
}
/**
2022-10-05 10:21:52 +02:00
* Allocates (push) a chunk of the memory buffer of a given size.
*
2022-05-02 14:41:00 +02:00
* Checks to see if there are enough space left in the memory buffer, returns
* the current location in the memory buffer and moves the index accordingly.
*
* @param[in] size Requested allocation size in bytes
* @return Allocated memory pointer; \ref NULL if not enough space left.
*/
2022-07-19 11:49:18 +02:00
void *mem_alloc(size_t size) {
if ((mem_idx + size) > SIZE_MEM_BUFFER) // Buffer exceeded
2022-05-02 14:41:00 +02:00
{
return NULL;
}
mem_idx += size;
return &mem_buffer[mem_idx - size];
}
/**
2022-10-05 10:21:52 +02:00
* De-allocates (pop) a chunk of memory buffer by a given size.
2022-05-02 14:41:00 +02:00
*
* @param[in] size Requested deallocation size in bytes
*/
2022-07-19 11:49:18 +02:00
void mem_dealloc(size_t size) {
if (size > mem_idx) // More than is already allocated
2022-05-02 14:41:00 +02:00
{
mem_idx = 0;
2022-07-19 11:49:18 +02:00
} else {
2022-05-02 14:41:00 +02:00
mem_idx -= size;
}
}
2022-07-19 11:49:18 +02:00
#endif // HAVE_DYN_MEM_ALLOC