Skip to content

Instantly share code, notes, and snippets.

@mpapierski
Last active December 19, 2015 10:59
Show Gist options
  • Save mpapierski/5944513 to your computer and use it in GitHub Desktop.
Save mpapierski/5944513 to your computer and use it in GitHub Desktop.
#include <stdexcept>
#include <boost/type_traits.hpp>
#include <boost/utility/enable_if.hpp>
class binstream
{
public:
struct str
{
inline str(char * & output, std::size_t length)
: output_(output)
, length_(length)
{
}
char * & output_;
std::size_t length_;
};
struct skip
{
inline skip(std::size_t length)
: length_(length)
{
}
std::size_t length_;
};
binstream(char * begin, char * end);
template <typename T>
inline typename boost::enable_if<boost::is_arithmetic<T>, binstream &>::type operator>>(T & out)
{
if (data_ + sizeof(T) > end_)
throw std::range_error("reading data out of bounds of binary stream");
out = *reinterpret_cast<T *>(data_);
data_ += sizeof(T);
return *this;
}
inline binstream & operator>>(str s)
{
if (data_ + s.length_ > end_)
throw std::range_error("reading data out of bounds of binary stream");
s.output_ = data_;
data_ += s.length_;
return *this;
}
inline binstream & operator>>(skip s)
{
if (data_ + s.length_ > end_)
throw std::range_error("reading data out of bounds of binary stream");
data_ += s.length_;
return *this;
}
private:
char * begin_;
char * end_;
char * data_;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment