Geoff Lang | 5063f55 | 2014-07-23 16:27:31 -0400 | [diff] [blame] | 1 | // |
| 2 | // Copyright (c) 2014 The ANGLE Project Authors. All rights reserved. |
| 3 | // Use of this source code is governed by a BSD-style license that can be |
| 4 | // found in the LICENSE file. |
| 5 | // |
| 6 | |
Jamie Madill | 74ba76c | 2015-02-09 10:31:23 -0500 | [diff] [blame] | 7 | #include "common/MemoryBuffer.h" |
Geoff Lang | 5063f55 | 2014-07-23 16:27:31 -0400 | [diff] [blame] | 8 | |
| 9 | #include <algorithm> |
| 10 | #include <cstdlib> |
| 11 | |
Jamie Madill | 74ba76c | 2015-02-09 10:31:23 -0500 | [diff] [blame] | 12 | #include "common/debug.h" |
| 13 | |
Geoff Lang | 5063f55 | 2014-07-23 16:27:31 -0400 | [diff] [blame] | 14 | namespace rx |
| 15 | { |
| 16 | |
| 17 | MemoryBuffer::MemoryBuffer() |
| 18 | : mSize(0), |
| 19 | mData(NULL) |
| 20 | { |
| 21 | } |
| 22 | |
| 23 | MemoryBuffer::~MemoryBuffer() |
| 24 | { |
| 25 | free(mData); |
| 26 | mData = NULL; |
| 27 | } |
| 28 | |
| 29 | bool MemoryBuffer::resize(size_t size) |
| 30 | { |
| 31 | if (size == 0) |
| 32 | { |
Jamie Madill | cc00239 | 2014-09-09 10:21:56 -0400 | [diff] [blame] | 33 | free(mData); |
| 34 | mData = NULL; |
| 35 | mSize = 0; |
Bruce Dawson | 36e8623 | 2014-12-01 16:48:23 -0500 | [diff] [blame] | 36 | return true; |
Geoff Lang | 5063f55 | 2014-07-23 16:27:31 -0400 | [diff] [blame] | 37 | } |
Bruce Dawson | 36e8623 | 2014-12-01 16:48:23 -0500 | [diff] [blame] | 38 | |
| 39 | if (size == mSize) |
Geoff Lang | 5063f55 | 2014-07-23 16:27:31 -0400 | [diff] [blame] | 40 | { |
Bruce Dawson | 36e8623 | 2014-12-01 16:48:23 -0500 | [diff] [blame] | 41 | return true; |
Geoff Lang | 5063f55 | 2014-07-23 16:27:31 -0400 | [diff] [blame] | 42 | } |
| 43 | |
Bruce Dawson | 36e8623 | 2014-12-01 16:48:23 -0500 | [diff] [blame] | 44 | // Only reallocate if the size has changed. |
| 45 | uint8_t *newMemory = reinterpret_cast<uint8_t*>(malloc(sizeof(uint8_t) * size)); |
| 46 | if (newMemory == NULL) |
| 47 | { |
| 48 | return false; |
| 49 | } |
| 50 | |
| 51 | if (mData) |
| 52 | { |
| 53 | // Copy the intersection of the old data and the new data |
| 54 | std::copy(mData, mData + std::min(mSize, size), newMemory); |
| 55 | free(mData); |
| 56 | } |
| 57 | |
| 58 | mData = newMemory; |
| 59 | mSize = size; |
| 60 | |
Geoff Lang | 5063f55 | 2014-07-23 16:27:31 -0400 | [diff] [blame] | 61 | return true; |
| 62 | } |
| 63 | |
| 64 | size_t MemoryBuffer::size() const |
| 65 | { |
| 66 | return mSize; |
| 67 | } |
| 68 | |
| 69 | const uint8_t *MemoryBuffer::data() const |
| 70 | { |
| 71 | return mData; |
| 72 | } |
| 73 | |
| 74 | uint8_t *MemoryBuffer::data() |
| 75 | { |
Jamie Madill | ee009b8 | 2014-09-19 13:17:51 -0400 | [diff] [blame] | 76 | ASSERT(mData); |
Geoff Lang | 5063f55 | 2014-07-23 16:27:31 -0400 | [diff] [blame] | 77 | return mData; |
| 78 | } |
| 79 | |
Geoff Lang | 5063f55 | 2014-07-23 16:27:31 -0400 | [diff] [blame] | 80 | } |