Implement LinkedList::visit()

(cherry picked from commit a492605849)

Change-Id: I59554be45c910bfe33494016595a5ade9daad230
This commit is contained in:
Dmitriy Ivanov 2014-09-02 09:45:40 -07:00
parent ff01f6fcce
commit 4466bd72fb
2 changed files with 56 additions and 9 deletions

View file

@ -86,10 +86,21 @@ class LinkedList {
}
template<typename F>
void for_each(F&& action) {
for (LinkedListEntry<T>* e = head_; e != nullptr; e = e->next) {
action(e->element);
void for_each(F action) {
visit([&] (T* si) {
action(si);
return true;
});
}
template<typename F>
bool visit(F action) {
for (LinkedListEntry<T>* e = head_; e != nullptr; e = e->next) {
if (!action(e->element)) {
return false;
}
}
return true;
}
template<typename F>

View file

@ -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());
}