1 /******************************************************************
3 * Copyright 2014 Samsung Electronics All Rights Reserved.
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
11 * http://www.apache.org/licenses/LICENSE-2.0
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
19 ******************************************************************/
23 #include "uarraylist.h"
25 #include "oic_malloc.h"
27 #define TAG "UARRAYLIST"
30 * Use this default size when initialized
32 #define U_ARRAYLIST_DEFAULT_SIZE 1
34 u_arraylist_t *u_arraylist_create()
36 u_arraylist_t *list = NULL;
38 list = (u_arraylist_t *) OICMalloc(sizeof(u_arraylist_t));
44 list->size = U_ARRAYLIST_DEFAULT_SIZE;
47 list->data = (void *) OICMalloc(list->size * sizeof(void *));
50 OIC_LOG(DEBUG, TAG, "Out of memory");
57 void u_arraylist_free(u_arraylist_t **list)
59 if (!list || !(*list))
64 OICFree((*list)->data);
70 void *u_arraylist_get(const u_arraylist_t *list, uint32_t index)
77 if ((index < list->length) && (list->data))
79 return list->data[index];
85 bool u_arraylist_add(u_arraylist_t *list, void *data)
92 if (list->size <= list->length)
94 uint32_t new_size = list->size + 1;
95 if (!(list->data = (void **) realloc(list->data, new_size * sizeof(void *))))
97 OIC_LOG(ERROR, TAG, "Failed to re-allocation memory");
101 memset(list->data + list->size, 0, (new_size - list->size) * sizeof(void *));
102 list->size = new_size;
105 list->data[list->length] = data;
111 void *u_arraylist_remove(u_arraylist_t *list, uint32_t index)
113 void *removed = NULL;
120 if (index >= list->length)
125 removed = list->data[index];
127 if (index < list->length - 1)
129 memmove(&list->data[index], &list->data[index + 1],
130 (list->length - index - 1) * sizeof(void *));
136 // check minimum size.
137 list->size = (list->size <= U_ARRAYLIST_DEFAULT_SIZE) ? U_ARRAYLIST_DEFAULT_SIZE : list->size;
139 if (!(list->data = (void **) realloc(list->data, list->size * sizeof(void *))))
147 uint32_t u_arraylist_length(const u_arraylist_t *list)
151 OIC_LOG(DEBUG, TAG, "Invalid Parameter");
157 bool u_arraylist_contains(const u_arraylist_t *list,const void *data)
166 uint32_t length = u_arraylist_length(list);
168 for (i = 0; i < length; i++)
170 if (data == u_arraylist_get(list, i))
179 // Assumes elements are shallow (have no pointers to allocated memory)
180 void u_arraylist_destroy(u_arraylist_t *list)
186 uint32_t len = u_arraylist_length(list);
187 for (uint32_t i = 0; i < len; i++)
189 OICFree(u_arraylist_get(list, i));
191 (void)u_arraylist_free(&list);