| 46 | }; |
| 47 | |
| 48 | void* Allocate(HContext context, uint32_t size) |
| 49 | { |
| 50 | uint32_t allocation_size = DM_ALIGN(sizeof(uint16_t) + size, BLOCK_ALLOCATION_ALIGNEMENT); |
| 51 | if (allocation_size > BLOCK_ALLOCATION_THRESHOLD) |
| 52 | { |
| 53 | uint16_t* res = (uint16_t*)malloc(sizeof(uint16_t) + size); |
| 54 | *res = MAX_BLOCK_COUNT; |
| 55 | return &res[1]; |
| 56 | } |
| 57 | uint16_t first_free = MAX_BLOCK_COUNT; |
| 58 | for (uint16_t block_index = 0; block_index < MAX_BLOCK_COUNT; ++block_index) |
| 59 | { |
| 60 | Block* block = context->m_Blocks[block_index]; |
| 61 | if (block == 0x0) |
| 62 | { |
| 63 | first_free = (first_free == MAX_BLOCK_COUNT) ? block_index : first_free; |
| 64 | continue; |
| 65 | } |
| 66 | BlockData* block_data = &context->m_BlockDatas[block_index]; |
| 67 | if (block_data->m_LowWaterMark >= allocation_size) |
| 68 | { |
| 69 | block_data->m_LowWaterMark -= allocation_size; |
| 70 | block_data->m_AllocationCount++; |
| 71 | uint16_t* ptr = (uint16_t*)&block->m_Data[block_data->m_LowWaterMark]; |
| 72 | *ptr = block_index; |
| 73 | return &ptr[1]; |
| 74 | } |
| 75 | if (block_data->m_HighWaterMark + allocation_size <= BLOCK_SIZE) |
| 76 | { |
| 77 | block_data->m_AllocationCount++; |
| 78 | uint16_t* ptr = (uint16_t*)&block->m_Data[block_data->m_HighWaterMark]; |
| 79 | block_data->m_HighWaterMark += allocation_size; |
| 80 | *ptr = block_index; |
| 81 | return &ptr[1]; |
| 82 | } |
| 83 | } |
| 84 | if (first_free != MAX_BLOCK_COUNT) |
| 85 | { |
| 86 | Block* block = new Block; |
| 87 | BlockData* block_data = &context->m_BlockDatas[first_free]; |
| 88 | block_data->m_AllocationCount = 1; |
| 89 | block_data->m_LowWaterMark = 0; |
| 90 | block_data->m_HighWaterMark = allocation_size; |
| 91 | uint16_t* ptr = (uint16_t*)&block->m_Data[0]; |
| 92 | *ptr = first_free; |
| 93 | context->m_Blocks[first_free] = block; |
| 94 | return &ptr[1]; |
| 95 | } |
| 96 | uint16_t* res = (uint16_t*)malloc(sizeof(uint16_t) + size); |
| 97 | *res = MAX_BLOCK_COUNT; |
| 98 | return &res[1]; |
| 99 | } |
| 100 | |
| 101 | void Free(HContext context, void* data, uint32_t size) |
| 102 | { |