Skip to content

Commit 9b801d0

Browse files
committed
Add optimized CSizeComputer serializers
To get the advantages of faster GetSerializeSize() implementations back that were removed in "Make GetSerializeSize a wrapper on top of CSizeComputer", reintroduce them in the few places in the form of a specialized Serialize() implementation. This actually gets us in a better state than before, as these even get used when they're invoked indirectly in the serialization of another object. backports bitcoin/bitcoin@25a211a
1 parent 0035a54 commit 9b801d0

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed

src/serialize.h

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -155,6 +155,8 @@ inline float ser_uint32_to_float(uint32_t y)
155155
// i.e. anything that supports .read(char*, size_t) and .write(char*, size_t)
156156
//
157157

158+
class CSizeComputer;
159+
158160
enum {
159161
// primary actions
160162
SER_NETWORK = (1 << 0),
@@ -278,6 +280,8 @@ inline unsigned int GetSizeOfCompactSize(uint64_t nSize)
278280
return sizeof(unsigned char) + sizeof(uint64_t);
279281
}
280282

283+
inline void WriteCompactSize(CSizeComputer& os, uint64_t nSize);
284+
281285
template <typename Stream>
282286
void WriteCompactSize(Stream& os, uint64_t nSize)
283287
{
@@ -358,6 +362,9 @@ inline unsigned int GetSizeOfVarInt(I n)
358362
return nRet;
359363
}
360364

365+
template<typename I>
366+
inline void WriteVarInt(CSizeComputer& os, I n);
367+
361368
template <typename Stream, typename I>
362369
void WriteVarInt(Stream& os, I n)
363370
{
@@ -825,6 +832,18 @@ inline void SerReadWrite(Stream& s, T& obj, CSerActionUnserialize ser_action)
825832
}
826833

827834

835+
836+
/* ::GetSerializeSize implementations
837+
*
838+
* Computing the serialized size of objects is done through a special stream
839+
* object of type CSizeComputer, which only records the number of bytes written
840+
* to it.
841+
*
842+
* If your Serialize or SerializationOp method has non-trivial overhead for
843+
* serialization, it may be worthwhile to implement a specialized version for
844+
* CSizeComputer, which uses the s.seek() method to record bytes that would
845+
* be written instead.
846+
*/
828847
class CSizeComputer
829848
{
830849
protected:
@@ -863,6 +882,17 @@ class CSizeComputer
863882
int GetType() const { return nType; }
864883
};
865884

885+
template<typename I>
886+
inline void WriteVarInt(CSizeComputer &s, I n)
887+
{
888+
s.seek(GetSizeOfVarInt<I>(n));
889+
}
890+
891+
inline void WriteCompactSize(CSizeComputer &s, uint64_t nSize)
892+
{
893+
s.seek(GetSizeOfCompactSize(nSize));
894+
}
895+
866896
template <typename T>
867897
size_t GetSerializeSize(const T& t, int nType, int nVersion = 0)
868898
{

0 commit comments

Comments
 (0)