1 /*
2 * Copyright (C) 2018 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 #include "chre/util/buffer_base.h"
18
19 #include <cstring>
20
21 #include "chre/util/container_support.h"
22
23 namespace chre {
24
~BufferBase()25 BufferBase::~BufferBase() {
26 reset();
27 }
28
wrap(void * buffer,size_t size)29 void BufferBase::wrap(void *buffer, size_t size) {
30 // If buffer is nullptr, size must also be 0.
31 CHRE_ASSERT(buffer != nullptr || size == 0);
32 reset();
33 mBuffer = buffer;
34 mSize = size;
35 }
36
copy_array(const void * buffer,size_t size,size_t elementSize)37 bool BufferBase::copy_array(const void *buffer, size_t size,
38 size_t elementSize) {
39 // If buffer is nullptr, size must also be 0.
40 CHRE_ASSERT(buffer != nullptr || size == 0);
41
42 reset();
43 bool success = (size == 0);
44 if (!success) {
45 size_t copyBytes = size * elementSize;
46 mBuffer = memoryAlloc(copyBytes);
47 if (mBuffer != nullptr) {
48 mBufferRequiresFree = true;
49 memcpy(mBuffer, buffer, copyBytes);
50 mSize = size;
51 success = true;
52 }
53 }
54
55 return success;
56 }
57
reset()58 void BufferBase::reset() {
59 if (mBufferRequiresFree) {
60 mBufferRequiresFree = false;
61 memoryFree(mBuffer);
62 }
63
64 mBuffer = nullptr;
65 mSize = 0;
66 }
67
68 } // namespace chre
69