by chrisaycock · 12y ago · 0 comments
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.It is very unfortunate that C (and until recently C++) did not have a way to specify the size of enums. Basically this has resulted in crappy #defines being used for far too many years.
I always called what you did above "tagged types". A number of type systems actually work like that under the covers, objects get a type ID, and then a lookup function figures out what that type ID maps to.
It had compiler specific switches to set the size of all enums globally, which helped exactly nobody.
Data data;
memcpy(&data, raw_buffer, sizeof data);
switch(data.data_type)
// ...one is to use "--pointer_alignment=1" so that all accesses via the pointer are treated as unaligned OR
use "--no_unaligned_access" flag to tell the compiler to not knowingly generate unaligned access
A good reminder that trying to "let the types do the work" in C++ is an oxymoron.
If you're so keen on algebraic data types, there are languages much better suited to that than C++.
Variants of this comment are often seen.
For any given feature, there's going to be a language that shines in that particular area. However, choice of language rarely comes down to a specific feature. There's usually a multitude of aspects that needs to be considered - some of them aren't even technical.
Edit: I say this as someone whose primary language is Haskell
Yes, you are quite right.
However it only works when one works alone.
Usually the choice of a language is driven by what the customer requires as technology, what the team members are capable of using or willing to learn, finally what the boss allows.
struct A { Data header; ... }
struct B { Data header; ... }
union AB { Data header; A a; B b }
and then access the header field in AB. If this is syntactically the first field in each of the constituent records the result is well-defined.
This is a great solution if you need to map to a specific wire format. If you do not have that constraint and have code which uses algebraic data types a lot you should probably switch to OCaml or Haskell. There are specific optimizations to work with complex matches and for representing algebraic types in a compact and efficient way. In C++ the compiler has to work with reinterpret_casts and cannot change the representation of your data types (much). Doing the optimizations by hand is possible, but chances are that a simple-minded OCaml prototype will already perform reasonably well.
As I mentioned in a comment above, lots of on the wire binary protocols start with a type identifier byte (or word). You then have a wonderful switch statement based off of that.
Heck I had an entire inter processor communication system running based on what was essentially this very idea. The switch actually had two layers, your first byte gave you a subsystem to jump to and the second byte was the command within that subsystem.
You sent data down the wire connecting the two processors together (a UART connection in this case), read straight into a buffer, and just pop right into a switch statement. The main disadvantage is everything is set at compile time, but for a lot of uses that is a-ok.