#include "pip.h"

//! [struct]
// 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;
}
//! [struct]
//! [write]
// 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 ...
//! [write]
//! [read]
// 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;
//! [read]

//! [write_new]
PIByteArray & operator<<(PIByteArray & s, const S & value) {
	PIChunkStream cs;
	cs.add(1, value.i).add(2, value.f).add(3, value.s);
	s << cs.data();
	return s;
}
//! [write_new]
//! [read_new]
PIByteArray & operator>>(PIByteArray & s, S & value) {
	PIChunkStream cs;
	if (!cs.extract(s)) return s;
	cs.readAll();
	cs.get(1, value.i).get(2, value.f).get(3, value.s);
	return s;
}
//! [read_new]
