blob: ede0644cbcae69a34ef26008f1cffdd3cb803db7 [file] [log] [blame]
The Android Open Source Projectd245d1d2008-10-21 07:00:00 -07001/*
2 * Copyright (C) 2005 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//
18// Sortable array of strings. STL-ish, but STL-free.
19//
20#ifndef _LIBS_UTILS_STRING_ARRAY_H
21#define _LIBS_UTILS_STRING_ARRAY_H
22
23#include <stdlib.h>
24#include <string.h>
25
26namespace android {
27
28//
29// An expanding array of strings. Add, get, sort, delete.
30//
31class StringArray {
32public:
33 StringArray()
34 : mMax(0), mCurrent(0), mArray(NULL)
35 {}
36 virtual ~StringArray() {
37 for (int i = 0; i < mCurrent; i++)
38 delete[] mArray[i];
39 delete[] mArray;
40 }
41
42 //
43 // Add a string. A copy of the string is made.
44 //
45 bool push_back(const char* str) {
46 if (mCurrent >= mMax) {
47 char** tmp;
48
49 if (mMax == 0)
50 mMax = 16; // initial storage
51 else
52 mMax *= 2;
53
54 tmp = new char*[mMax];
55 if (tmp == NULL)
56 return false;
57
58 memcpy(tmp, mArray, mCurrent * sizeof(char*));
59 delete[] mArray;
60 mArray = tmp;
61 }
62
63 int len = strlen(str);
64 mArray[mCurrent] = new char[len+1];
65 memcpy(mArray[mCurrent], str, len+1);
66 mCurrent++;
67
68 return true;
69 }
70
71 //
72 // Delete an entry.
73 //
74 void erase(int idx) {
75 if (idx < 0 || idx >= mCurrent)
76 return;
77 delete[] mArray[idx];
78 if (idx < mCurrent-1) {
79 memmove(&mArray[idx], &mArray[idx+1],
80 (mCurrent-1 - idx) * sizeof(char*));
81 }
82 mCurrent--;
83 }
84
85 //
86 // Sort the array.
87 //
88 void sort(int (*compare)(const void*, const void*)) {
89 qsort(mArray, mCurrent, sizeof(char*), compare);
90 }
91
92 //
93 // Pass this to the sort routine to do an ascending alphabetical sort.
94 //
95 static int cmpAscendingAlpha(const void* pstr1, const void* pstr2) {
96 return strcmp(*(const char**)pstr1, *(const char**)pstr2);
97 }
98
99 //
100 // Get the #of items in the array.
101 //
102 inline int size(void) const { return mCurrent; }
103
104 //
105 // Return entry N.
106 // [should use operator[] here]
107 //
108 const char* getEntry(int idx) const {
109 if (idx < 0 || idx >= mCurrent)
110 return NULL;
111 return mArray[idx];
112 }
113
114private:
115 int mMax;
116 int mCurrent;
117 char** mArray;
118};
119
120}; // namespace android
121
122#endif // _LIBS_UTILS_STRING_ARRAY_H