blob: e7a3fb4a2b7073eee68ae230b098b8a83409e147 [file] [log] [blame]
Geoff Lang5063f552014-07-23 16:27:31 -04001//
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 Madill74ba76c2015-02-09 10:31:23 -05007#include "common/MemoryBuffer.h"
Geoff Lang5063f552014-07-23 16:27:31 -04008
9#include <algorithm>
10#include <cstdlib>
11
Jamie Madill74ba76c2015-02-09 10:31:23 -050012#include "common/debug.h"
13
Geoff Lang5063f552014-07-23 16:27:31 -040014namespace rx
15{
16
17MemoryBuffer::MemoryBuffer()
18 : mSize(0),
19 mData(NULL)
20{
21}
22
23MemoryBuffer::~MemoryBuffer()
24{
25 free(mData);
26 mData = NULL;
27}
28
29bool MemoryBuffer::resize(size_t size)
30{
31 if (size == 0)
32 {
Jamie Madillcc002392014-09-09 10:21:56 -040033 free(mData);
34 mData = NULL;
35 mSize = 0;
Bruce Dawson36e86232014-12-01 16:48:23 -050036 return true;
Geoff Lang5063f552014-07-23 16:27:31 -040037 }
Bruce Dawson36e86232014-12-01 16:48:23 -050038
39 if (size == mSize)
Geoff Lang5063f552014-07-23 16:27:31 -040040 {
Bruce Dawson36e86232014-12-01 16:48:23 -050041 return true;
Geoff Lang5063f552014-07-23 16:27:31 -040042 }
43
Bruce Dawson36e86232014-12-01 16:48:23 -050044 // 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 Lang5063f552014-07-23 16:27:31 -040061 return true;
62}
63
64size_t MemoryBuffer::size() const
65{
66 return mSize;
67}
68
69const uint8_t *MemoryBuffer::data() const
70{
71 return mData;
72}
73
74uint8_t *MemoryBuffer::data()
75{
Jamie Madillee009b82014-09-19 13:17:51 -040076 ASSERT(mData);
Geoff Lang5063f552014-07-23 16:27:31 -040077 return mData;
78}
79
Geoff Lang5063f552014-07-23 16:27:31 -040080}