#define TAG "UARRAYLIST"
+/**
+ * Use this default size when initialized
+ */
+#define U_ARRAYLIST_DEFAULT_SIZE 1
+
u_arraylist_t *u_arraylist_create()
{
u_arraylist_t *list = NULL;
- if (!(list = (u_arraylist_t *) OICMalloc(sizeof(u_arraylist_t))))
+ list = (u_arraylist_t *) OICMalloc(sizeof(u_arraylist_t));
+ if (!list)
{
return NULL;
}
list->size = U_ARRAYLIST_DEFAULT_SIZE;
list->length = 0;
- if (!(list->data = (void *) OICMalloc(list->size * sizeof(void *))))
+ list->data = (void *) OICMalloc(list->size * sizeof(void *));
+ if (!list->data)
{
OIC_LOG(DEBUG, TAG, "Out of memory");
OICFree(list);
CAResult_t u_arraylist_free(u_arraylist_t **list)
{
- if (*list == NULL)
+ if (!list || !(*list))
+ {
return CA_STATUS_INVALID_PARAM;
+ }
OICFree((*list)->data);
OICFree(*list);
void *u_arraylist_get(const u_arraylist_t *list, uint32_t index)
{
- if (index >= list->length)
+ if (!list )
{
return NULL;
}
- if (list->data)
+ if ((index < list->length) && (list->data))
{
return list->data[index];
}
CAResult_t u_arraylist_add(u_arraylist_t *list, void *data)
{
- uint32_t new_size = 0;
+ if (!list)
+ {
+ return CA_STATUS_INVALID_PARAM;
+ }
if (list->size <= list->length)
{
- new_size = list->size + 1;
+ uint32_t new_size = list->size + 1;
if (!(list->data = (void **) realloc(list->data, new_size * sizeof(void *))))
{
return CA_MEMORY_ALLOC_FAILED;
}
- (void) memset(list->data + list->size, 0, (new_size - list->size) * sizeof(void *));
+ memset(list->data + list->size, 0, (new_size - list->size) * sizeof(void *));
list->size = new_size;
}
{
void *removed = NULL;
+ if (!list)
+ {
+ return NULL;
+ }
+
if (index >= list->length)
{
return NULL;
uint32_t u_arraylist_length(const u_arraylist_t *list)
{
- if (NULL == list)
+ if (!list)
{
OIC_LOG(DEBUG, TAG, "Invalid Parameter");
return 0;
return list->length;
}
-uint8_t u_arraylist_contains(const u_arraylist_t *list, void *data)
+bool u_arraylist_contains(const u_arraylist_t *list,const void *data)
{
uint32_t i = 0;
- for (i = 0; i < u_arraylist_length(list); i++)
+ if (!list)
+ {
+ return false;
+ }
+
+ uint32_t length = u_arraylist_length(list);
+
+ for (i = 0; i < length; i++)
{
if (data == u_arraylist_get(list, i))
{
- return 1;
- }
- else
- {
- continue;
+ return true;
}
}
- return 0;
+ return false;
}
+// Assumes elements are shallow (have no pointers to allocated memory)
+void u_arraylist_destroy(u_arraylist_t *list)
+{
+ if (!list)
+ {
+ return;
+ }
+ uint32_t len = u_arraylist_length(list);
+ for (uint32_t i = 0; i < len; i++)
+ {
+ OICFree(u_arraylist_get(list, i));
+ }
+ (void)u_arraylist_free(&list);
+}