From a4926058496c1c24c00ac07e42d45048dac7c487 Mon Sep 17 00:00:00 2001 From: Dmitriy Ivanov Date: Tue, 2 Sep 2014 09:45:40 -0700 Subject: [PATCH] Implement LinkedList::visit() Change-Id: Ibd9d133dddf1f2e6e65660e3cd2dacafcc0c84d9 --- linker/linked_list.h | 15 ++++++++-- linker/tests/linked_list_test.cpp | 50 ++++++++++++++++++++++++++----- 2 files changed, 56 insertions(+), 9 deletions(-) diff --git a/linker/linked_list.h b/linker/linked_list.h index 14fe1e58d..5fbdc8ffb 100644 --- a/linker/linked_list.h +++ b/linker/linked_list.h @@ -86,10 +86,21 @@ class LinkedList { } template - void for_each(F&& action) { + void for_each(F action) { + visit([&] (T* si) { + action(si); + return true; + }); + } + + template + bool visit(F action) { for (LinkedListEntry* e = head_; e != nullptr; e = e->next) { - action(e->element); + if (!action(e->element)) { + return false; + } } + return true; } template diff --git a/linker/tests/linked_list_test.cpp b/linker/tests/linked_list_test.cpp index 0483b8412..a555edb33 100644 --- a/linker/tests/linked_list_test.cpp +++ b/linker/tests/linked_list_test.cpp @@ -151,15 +151,15 @@ TEST(linked_list, copy_to_array) { memset(buf, 0, sizeof(buf)); ASSERT_EQ(4U, list.size()); ASSERT_EQ(2U, list.copy_to_array(buf, 2)); - ASSERT_EQ('a', *buf[0]); - ASSERT_EQ('b', *buf[1]); + ASSERT_STREQ("a", buf[0]); + ASSERT_STREQ("b", buf[1]); ASSERT_EQ(nullptr, buf[2]); ASSERT_EQ(4U, list.copy_to_array(buf, max_size)); - ASSERT_EQ('a', *buf[0]); - ASSERT_EQ('b', *buf[1]); - ASSERT_EQ('c', *buf[2]); - ASSERT_EQ('d', *buf[3]); + ASSERT_STREQ("a", buf[0]); + ASSERT_STREQ("b", buf[1]); + ASSERT_STREQ("c", buf[2]); + ASSERT_STREQ("d", buf[3]); ASSERT_EQ(nullptr, buf[4]); memset(buf, 0, sizeof(buf)); @@ -168,7 +168,7 @@ TEST(linked_list, copy_to_array) { }); ASSERT_EQ(1U, list.size()); ASSERT_EQ(1U, list.copy_to_array(buf, max_size)); - ASSERT_EQ('c', *buf[0]); + ASSERT_STREQ("c", buf[0]); ASSERT_EQ(nullptr, buf[1]); memset(buf, 0, sizeof(buf)); @@ -182,3 +182,39 @@ TEST(linked_list, copy_to_array) { ASSERT_EQ(nullptr, buf[0]); } +TEST(linked_list, test_visit) { + test_list_t list; + list.push_back("a"); + list.push_back("b"); + list.push_back("c"); + list.push_back("d"); + + int visits = 0; + std::stringstream ss; + bool result = list.visit([&](const char* c) { + ++visits; + ss << c; + return true; + }); + + ASSERT_TRUE(result); + ASSERT_EQ(4, visits); + ASSERT_EQ("abcd", ss.str()); + + visits = 0; + ss.str(std::string()); + + result = list.visit([&](const char* c) { + if (++visits == 3) { + return false; + } + + ss << c; + return true; + }); + + ASSERT_TRUE(!result); + ASSERT_EQ(3, visits); + ASSERT_EQ("ab", ss.str()); +} +