Here is an example in C++11 that implements a market-data spec line-for-line.
#pragma pack(push,1)
struct Quote {
char symbol[16];
uint16_t bid;
uint32_t bidsize;
uint16_t ask
uint32_t asksize;
};
static_assert(sizeof(Quote) == 28, "Quote size wrong");
struct Trade {
char symbol[16];
uint16_t price;
uint32_t size;
};
static_assert(sizeof(Trade) == 22, "Trade size wrong");
struct Data {
enum class DataType : char {
kTrade = 't',
kQuote = 'q'
};
uint64_t sequence_number;
DataType data_type;
union {
Quote quote;
Trade trade;
};
};
#pragma pack(pop)
Now because I've disabled padding in the structs, the types will map directly to the proper byte locations as specified by the data vendor. There is no need for me to manipulate bytes!And I can get away with a single cast:
Data* data = reinterpret_cast<Data*>(raw_buffer);
switch (data->data_type) {
case Data::DataType::kTrade: {
Trade& trade = data->trade;
std::cout << trade.symbol << ' ' << trade.price << ' '
<< trade.size << std::endl;
break;
}
case Data::DataType::kQuote: {
Quote& quote = data->quote;
std::cout << quote.symbol << ' ' << quote.bid << ' '
<< quote.ask << std::endl;
}
default:
std::cerr << "Unknown message type: "
<< static_cast<char>(data->datatype) << std::endl;
}
So now the code resembles a match statement in OCaml, but will actually compile directly onto the underlying bytes. No data marshaling or anything like that.