mirror of
https://github.com/GearsProgress/Poke_Transporter_GB.git
synced 2026-03-22 01:44:36 -05:00
I found another way to optimize the rom space by implementing a custom malloc, free, realloc and calloc function. This reduces rom size by 3 KB and IWRAM usage by 1 KB. (elimination of __malloc_av). The original implementation is much more complex and larger than it needs to be. The custom malloc is implemented as a bitmap allocator. It keeps a bitmap to track which pages of the heap are allocated. Like the original allocator, it uses the free space in EWRAM after the multiboot gba rom. But unlike the original allocator, we control the size with CUSTOM_MALLOC_POOL_SIZE. The custom malloc can be disabled with USE_CUSTOM_MALLOC.
60 lines
1.7 KiB
C++
60 lines
1.7 KiB
C++
#define NANOPRINTF_IMPLEMENTATION 1
|
|
|
|
#include "libstd_replacements.h"
|
|
#include "libraries/nanoprintf/nanoprintf.h"
|
|
#include <cstdlib>
|
|
#include <stdarg.h>
|
|
#include <ctype.h>
|
|
#include "custom_malloc.h"
|
|
|
|
// recommended for a 32 bit system to have at least 33 bytes available
|
|
// source: https://cplusplus.com/reference/cstdlib/itoa/
|
|
// unfortunately itoa is not standardized, so we'll have to make do with snprintf
|
|
static char conversion_buffer[33];
|
|
|
|
const char* ptgb::to_string(int intVal)
|
|
{
|
|
npf_snprintf(conversion_buffer, sizeof(conversion_buffer), "%d", intVal);
|
|
return conversion_buffer;
|
|
}
|
|
|
|
const char* ptgb::to_string(unsigned int wordVal)
|
|
{
|
|
npf_snprintf(conversion_buffer, sizeof(conversion_buffer), "%u", wordVal);
|
|
return conversion_buffer;
|
|
}
|
|
|
|
// when compiling with -nostdlib++, we need to provide our own operator new and delete implementations
|
|
// Regular operator new
|
|
void* operator new(std::size_t size) {
|
|
void* ptr = malloc(size);
|
|
if (!ptr) {
|
|
// mimic standard behavior: throw std::bad_alloc
|
|
// but we can't use std::bad_alloc without libstdc++
|
|
// so instead we can abort or return nullptr
|
|
// You can also implement a custom exception if needed
|
|
return NULL;
|
|
}
|
|
return ptr;
|
|
}
|
|
|
|
// nothrow version
|
|
void* operator new(std::size_t size, const std::nothrow_t&) noexcept {
|
|
return malloc(size);
|
|
}
|
|
|
|
// operator delete
|
|
void operator delete(void* ptr) noexcept {
|
|
free(ptr);
|
|
}
|
|
|
|
// nothrow delete
|
|
void operator delete(void* ptr, const std::nothrow_t&) noexcept {
|
|
free(ptr);
|
|
}
|
|
|
|
// sized delete (optional, for C++14 and newer)
|
|
void operator delete(void* ptr, std::size_t size) noexcept {
|
|
(void)size;
|
|
free(ptr);
|
|
} |