I have the following problem:
- I have a class template where each instance represents an array of values (type of values is the template argument, of course).
- each instance has a name and that name is stored in the instance itself and in a
static std::map
Something along the lines:
#include <cstddef>
#include <string>
#include <map>
template <class T> class block {
private:
T *ptr;
std::string name;
std::size_t size;
static std::map<std::string, block<T>&> blocks;
public:
block(std::string _name, T *_ptr, std::size_t _size)
: name(_name)
, ptr(_ptr)
, size(_size)
{
blocks[_name] = this;
}
virtual ~block() {}
static block<T> &find(std::string key) {
return blocks[key];
}
};
Now I have the following problem:
write a function that, given the block name, an index and a unsigned char []
, should fill a single element element in the right block taking as many bytes "as needed".
Signature of such a function (or member) should be something like:
void set_element(std::string block_name, int index, void *source);
Is there a clean way to do this?
Ideally the only prerequisite should be there actually are enough bytes in the pointed array (I can add a std::size_t available_bytes
to function signature to actually check and throw
an error if there aren't enough bytes available).
If useful: reason why I need this is the I receive "unstructured" data from network and that's a byte stream I need to parse piece by piece.
To be more precise: the input stream i get is composed by a sequence of:
- a "C string" (null-terminated) representing the block name
- a single byte representing the index (0..255)
- "element" binary representation
There may be multiple "blocks" stick back-to-back in the input stream so it would be useful to have a return value stating either the number of bytes used or a pointer to first unused.
It's assumed binary data it comes from a compatible architecture and thus it is a correct representation.
The block name implicitly gives the size and characteristics of the element.
Incoming data is not supposed to be aligned; OTOH array pointed in block::ptr is supposed to be correctly aligned so I can access it with normal pointer arithmetic.
Note: the above example code is not good because it will produce separate blocks
for different template arguments while I need all names to be thrown in the same bag; I assume I will need to implement a parent class, but it's unclear exactly how to do it: I will update if I come to it.