Skip to content

Commit

Permalink
libdeng2: Convenience templates for Reader and Writer
Browse files Browse the repository at this point in the history
(De)serializing a list of objects, and reading values using a different
type than the destination (e.g., with enums).
  • Loading branch information
skyjake committed Jan 27, 2013
1 parent 8bc4460 commit 178ee98
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 0 deletions.
34 changes: 34 additions & 0 deletions doomsday/libdeng2/include/de/data/reader.h
Original file line number Diff line number Diff line change
Expand Up @@ -165,6 +165,40 @@ class DENG2_PUBLIC Reader
/// Reads a serializable object from the source buffer.
Reader &operator >> (IReadable &readable);

/**
* Reads a list of objects. ListType is expected to be an iterable
* list containing pointers to IReadable objects. The list will
* own the read instances.
*
* @param list List of objects.
*/
template <typename ObjectType, typename ListType>
Reader &readObjects(ListType &list) {
duint32 count;
*this >> count;
while(count-- > 0) {
std::auto_ptr<ObjectType> entry(new ObjectType);
*this >> *entry.get();
list.push_back(entry.release());
}
return *this;
}

/**
* Reads something from the source and converts it to another type before
* assigning to the destination. Use this for instance when reading an
* enumerated type that has been written as an integer.
*
* @param value Value to read.
*/
template <typename SerializedType, typename Type>
Reader &readAs(Type &value) {
SerializedType t;
*this >> t;
value = Type(t);
return *this;
}

/**
* Reads bytes from the source buffer until a specified delimiter value is
* encountered. The delimiter is included as part of the read data. The end
Expand Down
13 changes: 13 additions & 0 deletions doomsday/libdeng2/include/de/data/writer.h
Original file line number Diff line number Diff line change
Expand Up @@ -168,6 +168,19 @@ class DENG2_PUBLIC Writer
/// Writes a writable object into the destination buffer.
Writer &operator << (IWritable const &writable);

/**
* Writes a list of objects. ListType is expected to be an iterable
* list containing pointers to IWritable objects.
*
* @param list List of objects.
*/
template <typename ListType>
Writer &writeObjects(ListType const &list) {
*this << duint32(list.size());
DENG2_FOR_EACH_CONST(typename ListType, i, list) *this << **i;
return *this;
}

/**
* Returns the destination byte array used by the writer.
*/
Expand Down

0 comments on commit 178ee98

Please sign in to comment.