Skip to content

IO Stream

Hantao Sun edited this page Dec 16, 2019 · 3 revisions

Interview

IO-Stream is a series of functions for serialization and deserialization of class on IO. It supports basic types, std::pair, std::vector, std::map, and std::string. If a customized class or struct to be streamed by IO-Stream, there must overwrite Serialize functions. For example:

class CBlock
{
    friend class xengine::CStream;

public:
    uint16 nVersion;
    uint16 nType;
    uint32 nTimeStamp;
    uint256 hashPrev;
    uint256 hashMerkle;
    std::vector<uint8> vchProof;
    CTransaction txMint;
    std::vector<CTransaction> vtx;
    std::vector<uint8> vchSig;
    
protected:
    template <typename O>
    void Serialize(xengine::CStream& s, O& opt)
    {
        s.Serialize(nVersion, opt);
        s.Serialize(nType, opt);
        s.Serialize(nTimeStamp, opt);
        s.Serialize(hashPrev, opt);
        s.Serialize(hashMerkle, opt);
        s.Serialize(vchProof, opt);
        s.Serialize(txMint, opt);
        s.Serialize(vtx, opt);
        s.Serialize(vchSig, opt);
    }

basic types

If t is the variable, there will be called std::iostream::write((const char*)&t, sizeof(t)) or std::iostream::read((char*)&t, sizeof(t))

std::pair

Serialize or deserialize its key and value. If they are not a basic type, recursively the rules.

std::vector, std::map, std::string

  • First, serialize or deserialize the length of the variable. Its rules follow:
    • If length < 0xFD, the length is one byte of its value.
    • If length <= 0xFFFF, the length is one byte flag 0xFD and two bytes of its value.
    • If length <= 0xFFFFFFFF, the length is one byte flag 0xFE and four bytes of its value.
    • If length > 0xFFFFFFFF, the length is one byte flag 0xFF and eight bytes of its value.\
  • Then, serialize or deserialize every item of std::vector, std::map, std::string
    • For a vector, if the item is not a basic type, recursively the rules.
    • For a map, every item is std::pair, the rule is the same as std::pair.
    • For a string, every item is char with basic type.

uint256, uint224

uint256 is a customized struct to simulate a 32-byte number by 32-byte char array. And uint224 is 28-byte.

uint256 is used for many data, like block hash, txid and so on.

Its IO-Stream rule is std::iostream::write(array, sizeof(array)) and std::iostream::read(array, sizeof(array)).

Clone this wiki locally