char* MemoryPool::Allocate(size_t bytes){ assert(bytes > 0); char* result; if (bytes <= _memory_remain){ result = _alloc_ptr; _alloc_ptr += bytes; _memory_remain -= bytes; }else{ // We waste the remaining space in the current block. result = AllocateFallback(bytes); _memory_remain = _block_size - bytes; _alloc_ptr = result + bytes; } return result; }
char* Arena::AllocateAligned(size_t bytes) { const int align = (sizeof(void*) > 8) ? sizeof(void*) : 8; assert((align & (align-1)) == 0); // Pointer size should be a power of 2 size_t current_mod = reinterpret_cast<uintptr_t>(alloc_ptr_) & (align-1); size_t slop = (current_mod == 0 ? 0 : align - current_mod); size_t needed = bytes + slop; char* result; if (needed <= alloc_bytes_remaining_) { result = alloc_ptr_ + slop; alloc_ptr_ += needed; alloc_bytes_remaining_ -= needed; } else { // AllocateFallback always returned aligned memory result = AllocateFallback(bytes); } assert((reinterpret_cast<uintptr_t>(result) & (align-1)) == 0); return result; }
char* MemoryPool::AllocateAligned(size_t bytes){ const int align = (sizeof(void*) > 8) ? sizeof(void*) : 8; // Pointer size should be a power of 2 assert((align & (align-1)) == 0); //当align为power of 2时alloc_ptr_除以align的余数实际就是alloc_ptr_ & (align-1) size_t cur_mod = reinterpret_cast<uintptr_t>(_alloc_ptr) & (align - 1); size_t slop = (cur_mod == 0 ? 0 : align - cur_mod); size_t mem_need = bytes + slop; char *result; if (mem_need <= _memory_remain){ result = _alloc_ptr + slop; _alloc_ptr += mem_need; _memory_remain -= mem_need; }else{ // We waste the remaining space in the current block. result = AllocateFallback(bytes); _memory_remain = _block_size - bytes; _alloc_ptr = result + bytes; } return result; }