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/dynamic_vector_base.h"
18
19 #include <cstdint>
20 #include <cstring>
21
22 #include "chre/util/container_support.h"
23
24 namespace chre {
25
DynamicVectorBase(DynamicVectorBase && other)26 DynamicVectorBase::DynamicVectorBase(DynamicVectorBase&& other)
27 : mData(other.mData),
28 mSize(other.mSize),
29 mCapacity(other.mCapacity) {
30 other.mData = nullptr;
31 other.mSize = 0;
32 other.mCapacity = 0;
33 }
34
doReserve(size_t newCapacity,size_t elementSize)35 bool DynamicVectorBase::doReserve(size_t newCapacity, size_t elementSize) {
36 bool success = (newCapacity <= mCapacity);
37 if (!success) {
38 void *newData = memoryAlloc(newCapacity * elementSize);
39 if (newData != nullptr) {
40 memcpy(newData, mData, mSize * elementSize);
41 memoryFree(mData);
42 mData = newData;
43 mCapacity = newCapacity;
44 success = true;
45 }
46 }
47
48 return success;
49 }
50
doPrepareForPush(size_t elementSize)51 bool DynamicVectorBase::doPrepareForPush(size_t elementSize) {
52 return doReserve(getNextGrowthCapacity(), elementSize);
53 }
54
getNextGrowthCapacity() const55 size_t DynamicVectorBase::getNextGrowthCapacity() const {
56 size_t newCapacity;
57 if (mCapacity == 0) {
58 newCapacity = 1;
59 } else if (mSize == mCapacity) {
60 newCapacity = mCapacity * 2;
61 } else {
62 newCapacity = mCapacity;
63 }
64
65 return newCapacity;
66 }
67
doErase(size_t index,size_t elementSize)68 void DynamicVectorBase::doErase(size_t index, size_t elementSize) {
69 mSize--;
70 size_t moveAmount = (mSize - index) * elementSize;
71 memmove(static_cast<uint8_t *>(mData) + (index * elementSize),
72 static_cast<uint8_t *>(mData) + ((index + 1) * elementSize),
73 moveAmount);
74 }
75
doPushBack(const void * element,size_t elementSize)76 bool DynamicVectorBase::doPushBack(const void *element, size_t elementSize) {
77 bool spaceAvailable = doPrepareForPush(elementSize);
78 if (spaceAvailable) {
79 memcpy(static_cast<uint8_t *>(mData) + (mSize * elementSize),
80 element, elementSize);
81 mSize++;
82 }
83
84 return spaceAvailable;
85 }
86
87 } // namespace chre
88