returnBuffer.cpp
Engine/source/console/returnBuffer.cpp
Detailed Description
1 2//----------------------------------------------------------------------------- 3// Copyright (c) 2012 GarageGames, LLC 4// 5// Permission is hereby granted, free of charge, to any person obtaining a copy 6// of this software and associated documentation files (the "Software"), to 7// deal in the Software without restriction, including without limitation the 8// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or 9// sell copies of the Software, and to permit persons to whom the Software is 10// furnished to do so, subject to the following conditions: 11// 12// The above copyright notice and this permission notice shall be included in 13// all copies or substantial portions of the Software. 14// 15// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING 20// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS 21// IN THE SOFTWARE. 22//----------------------------------------------------------------------------- 23 24#include "returnBuffer.h" 25 26ReturnBuffer::ReturnBuffer() 27{ 28 mBuffer = nullptr; 29 mBufferSize = 0; 30 mStart = 0; 31 32 //Decent starting alloc of ~1 page = 4kb 33 ensureSize(4 * 1024); 34} 35 36ReturnBuffer::~ReturnBuffer() 37{ 38 if (mBuffer) 39 { 40 dFree(mBuffer); 41 } 42} 43 44void ReturnBuffer::ensureSize(U32 newSize) 45{ 46 //Round up to nearest multiple of 16 bytes 47 if (newSize & 0xF) 48 { 49 newSize = (newSize & ~0xF) + 0x10; 50 } 51 if (mBuffer == NULL) 52 { 53 //First alloc 54 mBuffer = (char *)dMalloc(newSize * sizeof(char)); 55 mBufferSize = newSize; 56 } 57 else if (mBufferSize < newSize) 58 { 59 //Just use the expected size 60 mBuffer = (char *)dRealloc(mBuffer, newSize * sizeof(char)); 61 mBufferSize = newSize; 62 } 63} 64 65char *ReturnBuffer::getBuffer(U32 size, U32 alignment) 66{ 67 ensureSize(size); 68 69 //Align the start if necessary 70 if (mStart % alignment != 0) 71 { 72 mStart += alignment - (mStart % alignment); 73 } 74 75 if (size + mStart > mBufferSize) 76 { 77 //Restart 78 mStart = 0; 79 } 80 char *buffer = mBuffer + mStart; 81 mStart += size; 82 83 return buffer; 84} 85