add a function to swap elements in a u_arraylist 51/26851/2
authorJozef Kralik <jozef.kralik@kistler.com>
Thu, 30 Aug 2018 07:27:40 +0000 (09:27 +0200)
committerJozef Kralik <jozef.kralik@kistler.com>
Thu, 6 Sep 2018 10:29:29 +0000 (12:29 +0200)
- u_arraylist_swap provides swap of elements in a array list

Bug: https://jira.iotivity.org/browse/IOT-3075
Bug: https://jira.iotivity.org/browse/IOT-3059
Change-Id: Iead0efa96b95f026b6a5b20731c8069f688c9483
Signed-off-by: Jozef Kralik <jozef.kralik@kistler.com>
resource/csdk/connectivity/common/inc/uarraylist.h
resource/csdk/connectivity/common/src/uarraylist.c
resource/csdk/connectivity/test/uarraylist_test.cpp

index c44829e..0f44e76 100644 (file)
@@ -113,6 +113,15 @@ bool u_arraylist_add(u_arraylist_t *list, void *data);
  */
 void *u_arraylist_remove(u_arraylist_t *list, size_t index);
 
+/**
+ * Swap elements in the array list.
+ * @param[in] list        pointer of array list.
+ * @param[in] index1      first index of array list.
+ * @param[in] index2      second index of array list.
+ * @return true if success, false otherwise.
+ */
+bool u_arraylist_swap(u_arraylist_t *list, size_t index1, size_t index2);
+
 /**
  * Returns the length of the array list.
  * @param[in] list       pointer of array list.
index 8e60b8e..039eab6 100644 (file)
@@ -242,3 +242,15 @@ void u_arraylist_destroy(u_arraylist_t *list)
     }
     (void)u_arraylist_free(&list);
 }
+
+bool u_arraylist_swap(u_arraylist_t *list, size_t index1, size_t index2)
+{
+    if (!list || index1 >= list->length || index2 >= list->length)
+    {
+        return false;
+    }
+    void* tmp = list->data[index1];
+    list->data[index1] = list->data[index2];
+    list->data[index2] = tmp;
+    return true;
+}
\ No newline at end of file
index 4a37b6c..c4510e2 100644 (file)
@@ -277,3 +277,34 @@ TEST_F(UArrayListF, Thrash)
         ASSERT_EQ(PAD_SIZE, u_arraylist_length(list));
     }
 }
+
+TEST_F(UArrayListF, Swap)
+{
+    ASSERT_EQ(static_cast<size_t>(0), u_arraylist_length(list));
+
+    int dummy = 0;
+    bool rc = u_arraylist_add(list, &dummy);
+    ASSERT_TRUE(rc);
+
+    ASSERT_EQ(static_cast<size_t>(1), u_arraylist_length(list));
+
+    int dumm2 = 1;
+    rc = u_arraylist_add(list, &dumm2);
+    ASSERT_TRUE(rc);
+
+    ASSERT_EQ(static_cast<size_t>(2), u_arraylist_length(list));
+
+    rc = u_arraylist_swap(list, 0, 1);
+    ASSERT_TRUE(rc);
+
+    void *value1 = u_arraylist_get(list, 0);
+    ASSERT_TRUE(value1 != NULL);
+    ASSERT_EQ(&dumm2, value1);
+
+    void *value2 = u_arraylist_get(list, 1);
+    ASSERT_TRUE(value2 != NULL);
+    ASSERT_EQ(&dummy, value2);
+
+    rc = u_arraylist_swap(list, 1, 2);
+    ASSERT_FALSE(rc);
+}