mirror of
https://github.com/pocketpy/pocketpy
synced 2025-10-21 12:00:18 +00:00
Update memory.h
This commit is contained in:
parent
3c098e638f
commit
b34317e7ee
32
src/memory.h
32
src/memory.h
@ -2,15 +2,35 @@
|
||||
|
||||
#include "common.h"
|
||||
|
||||
#define MALLOC(count) malloc(count)
|
||||
#define FREE(p) free(p)
|
||||
|
||||
namespace pkpy{
|
||||
const int kMaxMemPoolSize = 512;
|
||||
static thread_local std::vector<int*> _mem_pool(kMaxMemPoolSize);
|
||||
|
||||
template<typename T>
|
||||
struct sp_deleter {
|
||||
inline static void call(int* counter){
|
||||
if constexpr(std::is_same_v<T, i64> || std::is_same_v<T, f64>){
|
||||
if(_mem_pool.size() < kMaxMemPoolSize){
|
||||
_mem_pool.push_back(counter);
|
||||
return;
|
||||
}
|
||||
}
|
||||
((T*)(counter + 1))->~T();
|
||||
FREE(counter);
|
||||
free(counter);
|
||||
}
|
||||
};
|
||||
|
||||
template<typename T>
|
||||
struct sp_allocator {
|
||||
inline static void* call(size_t size){
|
||||
if constexpr(std::is_same_v<T, i64> || std::is_same_v<T, f64>){
|
||||
if(!_mem_pool.empty()){
|
||||
int* p = _mem_pool.back();
|
||||
_mem_pool.pop_back();
|
||||
return p;
|
||||
}
|
||||
}
|
||||
return malloc(size);
|
||||
}
|
||||
};
|
||||
|
||||
@ -82,7 +102,7 @@ namespace pkpy{
|
||||
shared_ptr<T> make_shared(Args&&... args) {
|
||||
static_assert(std::is_base_of_v<T, U>, "U must be derived from T");
|
||||
static_assert(std::has_virtual_destructor_v<T>, "T must have virtual destructor");
|
||||
int* p = (int*)MALLOC(sizeof(int) + sizeof(U));
|
||||
int* p = (int*)sp_allocator<U>::call(sizeof(int) + sizeof(U));
|
||||
*p = 1;
|
||||
new(p+1) U(std::forward<Args>(args)...);
|
||||
return shared_ptr<T>(p);
|
||||
@ -90,7 +110,7 @@ namespace pkpy{
|
||||
|
||||
template <typename T, typename... Args>
|
||||
shared_ptr<T> make_shared(Args&&... args) {
|
||||
int* p = (int*)MALLOC(sizeof(int) + sizeof(T));
|
||||
int* p = (int*)sp_allocator<T>::call(sizeof(int) + sizeof(T));
|
||||
*p = 1;
|
||||
new(p+1) T(std::forward<Args>(args)...);
|
||||
return shared_ptr<T>(p);
|
||||
|
Loading…
x
Reference in New Issue
Block a user