lundi 25 juillet 2016

C++ buffer with elegant semantics

My C++ code needs to interface with some low level routines, which want to read or write a buffer (unsigned char []). So, I want my class to look exactly like that: no other data whatsoever. (The code is performance intensive, so I don't want a copy or rewrite, I want an in-place read and write.)

However, I'm also doing some higher level work with it, where I sort, search, etc. So I'd like higher level semantics, so that I can do things like <, which std::array handles quite well. I actually don't care which ordering it has, as long as its consistent (I only use ordering for things like searches). Since the code is high performance, I don't want to copy here; I want to do these on the same raw data that looks like a C array.

Finally, I have a few methods of my own which I'd like, most important operator string(), to cast it to strings when needed for debugging.

I know how to achieve any one of these goals. But I can't come up with any good way to achieve all of them at the same time. Nonetheless, there's nothing in compiler internals which should preclude this, and my knowledge of C++11 tells me its definitely possible.

So, to recap, a class which:

  • A fixed number of bytes (e.g. 20) // This is fixed for all instances of a class
  • Can be read (in-place!) as a C array of bytes
  • Can be written (in-place!) as a C array of bytes
  • Supports consistent comparators (<, ==, >, etc.) (the ordering is arbitrary; == means all bytes are equal)
  • Ideally enables adding other methods, such as operator string ()

Bonus points if you can achieve this:

  • Without having to rewrite all the comparators
  • With efficient 64 bit arithmetic, even if the size isn't an even multiple of 64 (e.g. assume it is 20 bytes, then a < b means a[0..8] < b[0..8] && a[8..16] < b[8..16] && a[16..20] < b[16..20]

Aucun commentaire:

Enregistrer un commentaire