Skip to content

Commit

Permalink
Make VectorFormatter support stateful formatters
Browse files Browse the repository at this point in the history
  • Loading branch information
ryanofsky authored and furszy committed Jul 3, 2021
1 parent 4e2afad commit fd29a50
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 7 deletions.
9 changes: 7 additions & 2 deletions src/prevector.h
Original file line number Diff line number Diff line change
Expand Up @@ -422,15 +422,20 @@ class prevector {
return first;
}

void push_back(const T& value) {
template<typename... Args>
void emplace_back(Args&&... args) {
size_type new_size = size() + 1;
if (capacity() < new_size) {
change_capacity(new_size + (new_size >> 1));
}
new(item_ptr(size())) T(value);
new(item_ptr(size())) T(std::forward<Args>(args)...);
_size++;
}

void push_back(const T& value) {
emplace_back(value);
}

void pop_back() {
erase(end() - 1, end());
}
Expand Down
11 changes: 6 additions & 5 deletions src/serialize.h
Original file line number Diff line number Diff line change
Expand Up @@ -643,23 +643,25 @@ BigEndian<I> WrapBigEndian(I& n) { return BigEndian<I>(n); }
* as a vector of VarInt-encoded integers.
*
* V is not required to be an std::vector type. It works for any class that
* exposes a value_type, size, reserve, push_back, and const iterators.
* exposes a value_type, size, reserve, emplace_back, back, and const iterators.
*/
template<class Formatter>
struct VectorFormatter
{
template<typename Stream, typename V>
void Ser(Stream& s, const V& v)
{
Formatter formatter;
WriteCompactSize(s, v.size());
for (const typename V::value_type& elem : v) {
s << Using<Formatter>(elem);
formatter.Ser(s, elem);
}
}

template<typename Stream, typename V>
void Unser(Stream& s, V& v)
{
Formatter formatter;
v.clear();
size_t size = ReadCompactSize(s);
size_t allocated = 0;
Expand All @@ -671,9 +673,8 @@ struct VectorFormatter
allocated = std::min(size, allocated + MAX_VECTOR_ALLOCATE / sizeof(typename V::value_type));
v.reserve(allocated);
while (v.size() < allocated) {
typename V::value_type val;
s >> Using<Formatter>(val);
v.push_back(std::move(val));
v.emplace_back();
formatter.Unser(s, v.back());
}
}
};
Expand Down

0 comments on commit fd29a50

Please sign in to comment.