1 /** @file
2 
3   A brief file description
4 
5   @section license License
6 
7   Licensed to the Apache Software Foundation (ASF) under one
8   or more contributor license agreements.  See the NOTICE file
9   distributed with this work for additional information
10   regarding copyright ownership.  The ASF licenses this file
11   to you under the Apache License, Version 2.0 (the
12   "License"); you may not use this file except in compliance
13   with the License.  You may obtain a copy of the License at
14 
15       http://www.apache.org/licenses/LICENSE-2.0
16 
17   Unless required by applicable law or agreed to in writing, software
18   distributed under the License is distributed on an "AS IS" BASIS,
19   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20   See the License for the specific language governing permissions and
21   limitations under the License.
22  */
23 
24 #include "tscore/ink_platform.h"
25 #include "tscore/ink_memory.h"
26 #include "ExpandingArray.h"
27 
ExpandingArray(int initialSize,bool freeContents)28 ExpandingArray::ExpandingArray(int initialSize, bool freeContents)
29 {
30   if (initialSize < EA_MIN_SIZE) {
31     initialSize = EA_MIN_SIZE;
32   }
33 
34   internalArray = static_cast<void **>(ats_malloc(initialSize * sizeof(void *)));
35 
36   freeContentsOnDestruct = freeContents;
37   internalArraySize      = initialSize;
38   numValidValues         = 0;
39 }
40 
~ExpandingArray()41 ExpandingArray::~ExpandingArray()
42 {
43   if (freeContentsOnDestruct == true) {
44     for (int i = 0; i < numValidValues; i++) {
45       ats_free(internalArray[i]);
46     }
47   }
48   ats_free(internalArray);
49 }
50 
51 void *
operator [](int index)52 ExpandingArray::operator[](int index)
53 {
54   if (index < numValidValues) {
55     return internalArray[index];
56   } else {
57     return nullptr;
58   }
59 }
60 
61 int
addEntry(void * entry)62 ExpandingArray::addEntry(void *entry)
63 {
64   if (numValidValues == internalArraySize) {
65     // Time to increase the size of the array
66     internalArray = static_cast<void **>(ats_realloc(internalArray, 2 * sizeof(void *) * internalArraySize));
67     internalArraySize *= 2;
68   }
69 
70   internalArray[numValidValues] = entry;
71 
72   return numValidValues++;
73 }
74 
75 void
sortWithFunction(int (sortFunc)(const void *,const void *))76 ExpandingArray::sortWithFunction(int(sortFunc)(const void *, const void *))
77 {
78   qsort(internalArray, numValidValues, sizeof(void *), sortFunc);
79 }
80