| 1 | // tMemory.cpp  |
| 2 | //  |
| 3 | // Tacent memory management API.  |
| 4 | //  |
| 5 | // Copyright (c) 2004-2006, 2017 Tristan Grimmer.  |
| 6 | // Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby  |
| 7 | // granted, provided that the above copyright notice and this permission notice appear in all copies.  |
| 8 | //  |
| 9 | // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL  |
| 10 | // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,  |
| 11 | // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN  |
| 12 | // AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR  |
| 13 | // PERFORMANCE OF THIS SOFTWARE.  |
| 14 |   |
| 15 | #include "Foundation/tMemory.h"  |
| 16 | #include "Foundation/tAssert.h"  |
| 17 |   |
| 18 |   |
| 19 | void* tMem::tMalloc(int size, int alignSize)  |
| 20 | {  |
| 21 | // This code works for both 32 and 64 bit pointers.  |
| 22 | bool isPow2 = ((alignSize < 1) || (alignSize & (alignSize-1))) ? false : true;  |
| 23 | tAssert(isPow2);  |
| 24 |   |
| 25 | uint8* rawAddr = (uint8*)malloc(size + alignSize + sizeof(int));  |
| 26 | if (!rawAddr)  |
| 27 | return nullptr;  |
| 28 |   |
| 29 | uint8* base = rawAddr + sizeof(int);  |
| 30 |   |
| 31 | // The align mask only works if alignSize is a power or 2. Essentially the '&' does a mod (%) and we find  |
| 32 | // an aligned address starting from base.  |
| 33 | int64 alignMask = alignSize - 1;  |
| 34 | uint8* alignedPtr = base + (alignSize - (int64(base) & alignMask));  |
| 35 |   |
| 36 | // We now need to write the offset in the 4 bytes before the aligned a  |
| 37 | base = alignedPtr - sizeof(int);  |
| 38 | *((int*)base) = int(alignedPtr - rawAddr);  |
| 39 |   |
| 40 | return alignedPtr;  |
| 41 | }  |
| 42 |   |
| 43 |   |
| 44 | void tMem::tFree(void* mem)  |
| 45 | {  |
| 46 | uint8* rawAddr = (uint8*)mem;  |
| 47 | int* offsetAddr = ((int*)rawAddr) - 1;  |
| 48 | rawAddr -= *offsetAddr;  |
| 49 | free(rawAddr);  |
| 50 | }  |
| 51 | |