Last active
August 29, 2015 13:57
-
-
Save mntone/9520506 to your computer and use it in GitHub Desktop.
バイトストリームを容易に扱うための ibytestream。MIT ライセンスで。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#pragma once | |
#include <istream> | |
namespace mntone { namespace utility { | |
class ibytestream | |
: std::basic_istream<uint8_t> | |
{ | |
public: | |
using baseistream = std::basic_istream<uint8_t>; | |
uint8_t readuint8() | |
{ | |
uint8_t ret( 0 ); | |
baseistream::read( &ret, 1 ); | |
return ret; | |
} | |
uint16_t readuint16be() | |
{ | |
uint16_t ret( 0 ); | |
{ | |
std::array<uint8_t, 2> buf; | |
baseistream::read( buf.data(), 2 ); | |
convert_big_endian( buf, &ret ); | |
} | |
return ret; | |
} | |
uint16_t readuint16le() | |
{ | |
uint16_t ret( 0 ); | |
{ | |
std::array<uint8_t, 2> buf; | |
baseistream::read( buf.data(), 2 ); | |
convert_little_endian( buf, &ret ); | |
} | |
return ret; | |
} | |
uint16_t readuint16() | |
{ | |
return readuint16le(); | |
} | |
uint32_t readuint24be() | |
{ | |
uint32_t ret( 0 ); | |
{ | |
std::array<uint8_t, 3> buf; | |
baseistream::read( buf.data(), 3 ); | |
convert_big_endian( buf, &ret ); | |
} | |
return ret; | |
} | |
uint32_t readuint24le() | |
{ | |
uint32_t ret( 0 ); | |
{ | |
std::array<uint8_t, 3> buf; | |
baseistream::read( buf.data(), 3 ); | |
convert_little_endian( buf, &ret ); | |
} | |
return ret; | |
} | |
uint32_t readuint24() | |
{ | |
return readuint24le(); | |
} | |
uint32_t readuint32be() | |
{ | |
uint32_t ret( 0 ); | |
{ | |
std::array<uint8_t, 4> buf; | |
baseistream::read( buf.data(), 4 ); | |
convert_big_endian( buf, &ret ); | |
} | |
return ret; | |
} | |
uint32_t readuint32le() | |
{ | |
uint32_t ret( 0 ); | |
{ | |
std::array<uint8_t, 4> buf; | |
baseistream::read( buf.data(), 4 ); | |
convert_little_endian( buf, &ret ); | |
} | |
return ret; | |
} | |
uint32_t readuint32() | |
{ | |
return readuint32le(); | |
} | |
private: | |
template<size_t T> | |
void convert_big_endian( std::array<uint8_t, T> data, void* const dest ) | |
{ | |
auto ptr = reinterpret_cast<const uint8*>( first ) + size; | |
auto pdest = reinterpret_cast<uint8*>( dest ); | |
for( ; first != ptr; ++pdest ) | |
{ | |
*pdest = *--ptr; | |
} | |
} | |
template<size_t T> | |
void convert_little_endian( std::array<uint8_t, T> data, void* const dest ) | |
{ | |
memcpy( dest, first, size ); | |
} | |
}; | |
} } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment