HiveBrain v1.2.0
Get Started
← Back to all entries
patterncppMinor

Plain type serializer design

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
typedesignserializerplain

Problem

I am designing a class to store primitive types into byte buffer using predefined byte order. I am not going to use Boost.Serialization because I am working with plain types only and I need predefined binary structure without versions and things like that.

Here is draft of the design:

```
#ifndef SERIALIZER_H_
#define SERIALIZER_H_

/**
* @file
*
* Set of byte-order independent value serializers.
* New serializers can be added with template class specialization.
*
*/

#include "types.hpp"

/**
* Serializer generic interface.
*/
template
struct serializer
{
/**
* Parses value from raw bytes.
*
* @param from byte buffer parse value from
*/
static ValueType parse(uint8_t *from);

/**
* Writes value to raw byte buffer.
*
* @param value value to write
* @param dest destination buffer
*/
static void write(ValueType value, uint8_t *dest);
};

/**
* Serializer specialization for single byte.
*/
template<>
struct serializer
{
static uint8_t parse(uint8_t *from)
{
return *from;
}
static void write(const uint8_t value, uint8_t *to)
{
*to = value;
}
};

/**
* Serializer specialization for 2-byte number.
*/
template<>
struct serializer
{
static uint16_t parse(uint8_t *from)
{
return (uint16_t)from[0] > 8);
to[1] = value & 0xff;
}
};

/**
* Serializer specialization for 4-byte number.
*/
template<>
struct serializer
{
static uint32_t parse(uint8_t *from)
{
return from[0] ::write(value >> 16, to);
serializer::write(value & 0xffff, to + 2);
}
};

/**
* Serializer specialization for 8-byte number.
*/
template<>
struct serializer
{
static uint64_t parse(uint8_t *from)
{
const uint32_t high = serializer::parse(from);
const uint32_t low = serializer::parse(from + 4);
return ((uint64_t) high ::write(value >> 32, to);
serializer::write(value & 0xffffffff, to + 4);
}
};

Solution

Here are my comments, some months later:

  • You don't need a destructor to your packet class. The class does not seem to own anything.



  • There is no mention in your packet class of the size (or the end) of the buffer. No check of size either. (consequently)



  • In your `operator

Context

StackExchange Code Review Q#20621, answer score: 2

Revisions (0)

No revisions yet.