Skip to content

Commit

Permalink
Refactor|libcore|Record: Trying out C++11 for listing subrecords
Browse files Browse the repository at this point in the history
One can use a lambda function to filter out the list of subrecords.
  • Loading branch information
skyjake committed Aug 4, 2014
1 parent 1f0455e commit a1d7289
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 11 deletions.
11 changes: 11 additions & 0 deletions doomsday/libcore/include/de/data/record.h
Expand Up @@ -31,6 +31,7 @@
#include <QMap>
#include <QList>
#include <QRegExp>
#include <functional>

namespace de {

Expand Down Expand Up @@ -388,6 +389,16 @@ class DENG2_PUBLIC Record
*/
Subrecords subrecords() const;

/**
* Collects a map of all subrecords that fulfill a given predicate.
*
* @param filter Inclusion predicate: returns @c true, if the subrecord is to be
* included in the collection.
*
* @return Map of subrecords.
*/
Subrecords subrecords(std::function<bool (Record const &)> filter) const;

/**
* Creates a text representation of the record. Each variable name is
* prefixed with @a prefix.
Expand Down
28 changes: 17 additions & 11 deletions doomsday/libcore/src/data/record.cpp
Expand Up @@ -33,6 +33,7 @@
#include "de/String"

#include <QTextStream>
#include <functional>

namespace de {

Expand Down Expand Up @@ -129,21 +130,21 @@ DENG2_PIMPL(Record)
return value && value->record() && value->hasOwnership();
}

/*
bool isOwnedSubrecord(Variable const &var) const
{
RecordValue const *value = var.value().maybeAs<RecordValue>();
return value && value->record() && value->hasOwnership();
}*/

Record::Subrecords listSubrecords() const
Record::Subrecords listSubrecords(std::function<bool (Record const &)> filter) const
{
Subrecords subs;
DENG2_FOR_EACH_CONST(Members, i, members)
{
if(isSubrecord(*i.value()))
Variable const &member = *i.value();
if(isSubrecord(member))
{
subs.insert(i.key(), i.value()->value().as<RecordValue>().record());
Record *rec = member.value().as<RecordValue>().record();
DENG2_ASSERT(rec != 0); // subrecords are owned, so cannot have been deleted

// Must pass the filter.
if(!filter(*rec)) continue;

subs.insert(i.key(), rec);
}
}
return subs;
Expand Down Expand Up @@ -552,7 +553,12 @@ Record::Members const &Record::members() const

Record::Subrecords Record::subrecords() const
{
return d->listSubrecords();
return d->listSubrecords([] (Record const &) { return true; /* unfiltered */ });
}

Record::Subrecords Record::subrecords(std::function<bool (Record const &)> filter) const
{
return d->listSubrecords([&] (Record const &rec) { return filter(rec); });
}

String Record::asText(String const &prefix, List *lines) const
Expand Down

0 comments on commit a1d7289

Please sign in to comment.