Skip to content

Commit

Permalink
keira: add smart memory allocator for Lua that uses PSRAM if internal…
Browse files Browse the repository at this point in the history
… RAM usage is too high
  • Loading branch information
and3rson committed Mar 11, 2024
1 parent 40e7eac commit 8c3fe35
Showing 1 changed file with 21 additions and 1 deletion.
22 changes: 21 additions & 1 deletion firmware/keira/src/apps/lua/luarunner.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -96,10 +96,30 @@ AbstractLuaRunnerApp::AbstractLuaRunnerApp(const char* appName) :
setFlags(AppFlags::APP_FLAG_FULLSCREEN);
}

void* lua_smart_alloc(void* ud, void* ptr, size_t osize, size_t nsize) {
// If there will be less than 32 KB of free RAM after reallocating, use PSRAM allocator.
(void)ud;
(void)osize;
int32_t free_mem = heap_caps_get_free_size(MALLOC_CAP_8BIT);
if (nsize) {
uint32_t caps = MALLOC_CAP_8BIT;
if (free_mem - nsize < 32 * 1024) {
// Less than 32 KB of free RAM after reallocating. Use PSRAM allocator.
caps |= MALLOC_CAP_SPIRAM;
} else {
// More than 32 KB of free RAM after reallocating. Use regular allocator.
}
return heap_caps_realloc(ptr, nsize, caps);
} else {
free(ptr);
return NULL;
}
}

void AbstractLuaRunnerApp::luaSetup(const char* dir) {
lilka::serial_log("lua: script dir: %s", dir);

L = luaL_newstate();
L = lua_newstate(lua_smart_alloc, NULL);

lilka::serial_log("lua: init libs");
luaL_openlibs(L);
Expand Down

0 comments on commit 8c3fe35

Please sign in to comment.