From 0ab773ab7c8ee64c2377954cd2dc4e4889498e69 Mon Sep 17 00:00:00 2001 From: Ichthyostega Date: Tue, 24 Apr 2012 06:00:55 +0200 Subject: [PATCH] helper to pull all elements from an iterator, yielding the last one --- src/lib/itertools.hpp | 27 ++++++++++++++++++++++++++- tests/lib/itertools-test.cpp | 16 ++++++++++++++++ 2 files changed, 42 insertions(+), 1 deletion(-) diff --git a/src/lib/itertools.hpp b/src/lib/itertools.hpp index 12b2286cb..5c5b5f750 100644 --- a/src/lib/itertools.hpp +++ b/src/lib/itertools.hpp @@ -289,7 +289,7 @@ namespace lib { { return (cached_ && isOK_) || (cached_ = true - &&(isOK_ = predicate_(*Raw::pipe()))); + &&(isOK_ = predicate_(*Raw::pipe()))); } void @@ -540,6 +540,31 @@ namespace lib { } + template + inline typename IT::value_type + pull_last (IT iter) + { + typedef typename IT::value_type Val; + typedef wrapper::ItemWrapper Item; + + Item lastElm; + + while (iter) + { + lastElm = *iter; + ++iter; + } + + if (lastElm) + return *lastElm; + else + throw lumiera::error::State ("attempt to retrieve the last element " + "of an exhausted or empty iterator" + ,lumiera::error::LUMIERA_ERROR_ITER_EXHAUST); + } + + + /** filters away repeated values * emitted by source iterator */ template diff --git a/tests/lib/itertools-test.cpp b/tests/lib/itertools-test.cpp index 6b47a69a7..226e7376b 100644 --- a/tests/lib/itertools-test.cpp +++ b/tests/lib/itertools-test.cpp @@ -23,6 +23,7 @@ #include "lib/test/run.hpp" +#include "lib/test/test-helper.hpp" #include "lib/util.hpp" #include "lib/util-foreach.hpp" @@ -47,6 +48,8 @@ namespace test{ using std::endl; using std::rand; + using lumiera::error::LUMIERA_ERROR_ITER_EXHAUST; + namespace { // Test data @@ -110,6 +113,8 @@ namespace test{ verify_filterRepetitions(); buildTransformingIterator (source.begin()); + + verifyPullLast(source.begin()); } @@ -253,6 +258,17 @@ namespace test{ } + void + verifyPullLast(Iter const& ii) + { + Iter::value_type lastElm = pull_last (ii); + CHECK (1 == lastElm); // TestSource holds a decreasing sequence of numbers ending with 1 + + Iter emptyIterator; + CHECK (isnil (emptyIterator)); + + VERIFY_ERROR (ITER_EXHAUST, pull_last(emptyIterator) ); + } }; LAUNCHER (IterTools_test, "unit common");