FIXME: use memory page, and use best fit malloc strategy TODO: �ijɸ�����Ҫ�ֽ��������ڴ�أ���һ��ʼ����������ڴ�أ��ֳɶ������ʽ��С���ڴ�أ�
| 373 | // FIXME: use memory page, and use best fit malloc strategy |
| 374 | // TODO: �ijɸ�����Ҫ�ֽ��������ڴ�أ���һ��ʼ����������ڴ�أ��ֳɶ������ʽ��С���ڴ�أ� |
| 375 | void *lua_malloc(lua_State *L, size_t size) |
| 376 | { |
| 377 | size = align8(size); |
| 378 | if (size > LUA_MALLOC_TOTAL_SIZE) |
| 379 | { |
| 380 | thinkyoung::lua::lib::notify_lua_state_stop(L); |
| 381 | return nullptr; |
| 382 | } |
| 383 | if (L->malloced_buffers->size() < 1) |
| 384 | { |
| 385 | auto offset = L->malloc_pos; |
| 386 | void *p = (void*)((intptr_t)(L->malloc_buffer) + offset); |
| 387 | L->malloc_pos += size; |
| 388 | L->malloced_buffers->push_back(std::make_pair(offset, size)); |
| 389 | return p; |
| 390 | } |
| 391 | std::pair<ptrdiff_t, ptrdiff_t> last_pair; |
| 392 | auto begin = L->malloced_buffers->begin(); |
| 393 | for (auto it = begin; it != L->malloced_buffers->end(); ++it) |
| 394 | { |
| 395 | if (it == begin) |
| 396 | { |
| 397 | if (it->first > (ptrdiff_t)size) |
| 398 | { |
| 399 | // can alloc memory before first block |
| 400 | ptrdiff_t offset = 0; |
| 401 | void *p = L->malloc_buffer; |
| 402 | L->malloced_buffers->insert(L->malloced_buffers->begin(), std::make_pair(offset, size)); |
| 403 | return p; |
| 404 | } |
| 405 | last_pair = *it; |
| 406 | continue; |
| 407 | } |
| 408 | if (it->first >= last_pair.first + last_pair.second + (ptrdiff_t)size) |
| 409 | { |
| 410 | ptrdiff_t offset = last_pair.first + last_pair.second; |
| 411 | void *p = (void*)((intptr_t)(L->malloc_buffer) + offset); |
| 412 | L->malloced_buffers->insert(it, std::make_pair(offset, size)); |
| 413 | return p; |
| 414 | } |
| 415 | last_pair = *it; |
| 416 | } |
| 417 | if (L->malloc_pos + size > LUA_MALLOC_TOTAL_SIZE) |
| 418 | { |
| 419 | thinkyoung::lua::lib::notify_lua_state_stop(L); |
| 420 | return nullptr; |
| 421 | } |
| 422 | ptrdiff_t offset = L->malloc_pos; |
| 423 | void *p = (void*)((intptr_t)(L->malloc_buffer) + offset); |
| 424 | L->malloced_buffers->push_back(std::make_pair(offset, size)); |
| 425 | L->malloc_pos += size; |
| 426 | return p; |
| 427 | } |
| 428 | |
| 429 | void *lua_calloc(lua_State *L, size_t element_count, size_t element_size) |
| 430 | { |
no test coverage detected