From 540c792324fb9d5c9ed259985db68c41c07313c0 Mon Sep 17 00:00:00 2001 From: =?utf8?q?=EB=B0=95=EC=A2=85=ED=98=84/=EB=8F=99=EC=9E=91=EC=A0=9C?= =?utf8?q?=EC=96=B4Lab=28SR=29/Staff=20Engineer/=EC=82=BC=EC=84=B1?= =?utf8?q?=EC=A0=84=EC=9E=90?= Date: Thu, 26 Jul 2018 08:16:15 +0900 Subject: [PATCH] [coco] Implement 'insertBefore' (#805) This commit implements 'insertBefore' method in DLinkedList::Node trait. Signed-off-by: Jonghyun Park --- contrib/coco/core/include/coco/ADT/DLinkedList.h | 28 ++++++++++++++++++++++++ contrib/coco/core/src/ADT/DLinkedList.test.cpp | 28 ++++++++++++++++++++++++ 2 files changed, 56 insertions(+) diff --git a/contrib/coco/core/include/coco/ADT/DLinkedList.h b/contrib/coco/core/include/coco/ADT/DLinkedList.h index bf19fe9..f29951f 100644 --- a/contrib/coco/core/include/coco/ADT/DLinkedList.h +++ b/contrib/coco/core/include/coco/ADT/DLinkedList.h @@ -119,6 +119,34 @@ template struct DLinkedList virtual Head *head(void) const = 0; public: + void insertBefore(Child *next) + { + assert(next != nullptr); + assert(next->head() != nullptr); + + assert(_prev == nullptr); + assert(_next == nullptr); + + // REQUIRE Child should inheir Node class + auto curr = reinterpret_cast(this); + + // Update the link of the current node + _prev = next->prev(); + _next = next; + + if (auto prev = next->prev()) + { + prev->_next = curr; + } + next->_prev = curr; + + // Update parent-child relation + assert(parent() == nullptr); + next->head()->enlist(curr); + assert(parent() == next->parent()); + } + + public: void insertAfter(Child *prev) { assert(prev != nullptr); diff --git a/contrib/coco/core/src/ADT/DLinkedList.test.cpp b/contrib/coco/core/src/ADT/DLinkedList.test.cpp index 8459df3..8138cce 100644 --- a/contrib/coco/core/src/ADT/DLinkedList.test.cpp +++ b/contrib/coco/core/src/ADT/DLinkedList.test.cpp @@ -86,3 +86,31 @@ TEST(ADT_DLINKED_LINK, insert_two_elements) delete parent; delete link; } + +TEST(ADT_DLINKED_LINK, insertBefore) +{ + auto link = new coco::PtrLink<::Child, ::Parent>{}; + auto parent = new ::Parent{link}; + + auto child_1 = new ::Child{link}; + auto child_2 = new ::Child{link}; + + parent->children()->append(child_1); + child_2->insertBefore(child_1); + + ASSERT_EQ(child_2->parent(), parent); + ASSERT_EQ(child_2->prev(), nullptr); + ASSERT_EQ(child_2->next(), child_1); + + ASSERT_EQ(child_1->parent(), parent); + ASSERT_EQ(child_1->prev(), child_2); + ASSERT_EQ(child_1->next(), nullptr); + + ASSERT_EQ(parent->children()->head(), child_2); + ASSERT_EQ(parent->children()->tail(), child_1); + + delete child_2; + delete child_1; + delete parent; + delete link; +} -- 2.7.4