1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81
|
#include <stdexcept>
#include <memory>
#include <type_traits>
#include <iostream>
#include <iomanip>
#include <cstdint>
#include <limits>
class bytes
{
public:
typedef std::uint8_t byte_type ;
bytes(unsigned size)
: _size(size), _mem(new byte_type[size]) {}
template <typename T>
void store(unsigned index, T value,
typename std::enable_if<std::is_trivial<T>::value >::type* = 0)
{
_check(index, sizeof(T)) ;
*reinterpret_cast<T*>(&_mem[index]) = value ;
}
template <typename T>
T retrieve(unsigned index,
typename std::enable_if<std::is_trivial<T>::value >::type* = 0) const
{
_check(index, sizeof(T)) ;
return *reinterpret_cast<T*>(&_mem[index]) ;
}
unsigned size() const { return _size; }
operator byte_type*() { return _mem.get(); }
byte_type operator[](const unsigned index) const
{
_check(index, sizeof(_mem[0])) ;
return _mem[index];
}
private:
void _check( unsigned index, unsigned size ) const
{
if ( index + size > _size )
throw std::logic_error("bytes: Out of range!") ;
}
const unsigned _size ;
std::unique_ptr<byte_type[]> _mem ;
};
std::int16_t start = 0xEB90 ;
std::int16_t length = 0 ;
std::int8_t id = 2 ;
const unsigned offset[] = { 0, sizeof(start), sizeof(start)+sizeof(id) } ;
int main()
{
bytes myBytes(5) ;
try
{
myBytes.store(offset[0], start) ;
myBytes.store(offset[1], id) ;
myBytes.store(offset[2], length) ;
// myBytes.store(offset[2], 39LL) ; // exception thrown
std::cout << std::hex << myBytes.retrieve<int16_t>(offset[0]) << '\n' ;
std::cout << static_cast<int>(myBytes.retrieve<int8_t>(offset[1])) << '\n' ;
std::cout << myBytes.retrieve<int16_t>(offset[2]) << '\n' ;
}
catch(std::exception& ex)
{
std::cerr << ex.what() << '\n' ;
}
}
|