# PIP: PIChunkStream Class Reference

PIChunkStream Class Reference

Class for binary serialization. More...

## Public Member Functions

| PIChunkStream (const PIByteArray &data)
| Contructs stream for read from "data".
| PIChunkStream (PIByteArray *data=0)
| Contructs stream for read or write to/from "data", or empty stream for write.
PIByteArray | data () const
| Returns internal buffer with written data.
bool | atEnd () const
| Returns if there is end of stream.
int | read ()
| Read one chunk from stream and returns its ID.
int | getID ()
| Returns last readed chunk ID.
template<typename T >
T | getData () const
| Returns value of last readed chunk.

## Static Public Member Functions

template<typename T >
static Chunk< T > | chunk (int id, const T &data)
| Returns chunk with ID "id" and value "data" for write to stream.

## Detailed Description

Class for binary serialization.

# Synopsis

This class provides very handly mechanism to store and restore values to and from PIByteArray. The main advantage of using this class is that your binary data become independent from order and collection of your values.

# Mechanism

PIChunkStream works with items called "chunk". Chunk is an ID and any value that can be stored and restored to PIByteArray with stream operators << and >>. You can place chunks to stream and read chunks from stream.

To construct PIChunkStream for writing data use any constructor. Empty constructor creates internal empty buffer that can be accessed by function data(). Non-empty constructor works with given byte array.

To read chunks from byte array use function read() that returns ID of next chunk. Then you can get value of this chunk with function getData(), but you should definitely know type of this value. You can read from byte array while atEnd() if false.

# Example

Prepare your structs to work with PIChunkStream

// Your struct
struct S {
int i;
float f;
PIString s;
};
// Operators
PIByteArray & operator <<(PIByteArray & b, const S & s) {b << s.i << s.f << s.s; return b;}
PIByteArray & operator >>(PIByteArray & b, S & s) {b >> s.i >> s.f >> s.s; return b;}

Writing to PIChunkStream

// Write chunk stream
S s;
s.i = 99;
s.f = 0.01;
s.s = "SSS";
PIVector<float> f;
f << -1. << 2.5 << 11.;
// write some data to empty stream
PIChunkStream cs;
cs << cs.chunk(1, int(10))
<< cs.chunk(2, PIString("text"))
<< cs.chunk(4, f)
<< cs.chunk(3, s);
// now you can take cs.data() and send or place it somewhere ...

Reading from PIChunkStream

// create stream for read, cs from upper code
PIByteArray ba(cs.data());
PIChunkStream cs2(ba);
int i(0);
PIString str;
S s;
PIVector<float> f;
// read from stream
while (!cs2.atEnd()) {
switch (cs2.read()) {
case 1: i = cs2.getData<int>(); break;
case 2: str = cs2.getData<PIString>(); break;
case 3: s = cs2.getData<S>(); break;
case 4: f = cs2.getData<PIVector<float> >(); break;
}
}
piCout << i << str << f << s.i << s.f << s.s;