/*************************************************************************** * By Théophile Bastian, 2017 * M1 Network course project at ENS Cachan, Juliusz Chroboczek. * License: WTFPL v2 **************************************************************************/ /*************************************************************************** * Reused from a former project, by Théophile Bastian & Nathanaël Courant * git@github.com:tobast/sysres-pikern.git **************************************************************************/ #pragma once #include #include #include #include "data.h" class Bytes { public: class OutOfRange : public std::exception {}; /// Exception -- thrown by operator[] Bytes(); Bytes(const void* buff, size_t len); /// Initializes the object with [buff], reading [len] bytes. u8& operator[](const size_t pos); u8 operator[](const size_t pos) const; /// Accesses the [pos]th element. Throws OutOfRange if pos >= size() u16 ushortAt(const size_t pos) const; /// Accesses the 16 bits unsigned integet at position [pos]. /// Throws OutOfRange if [pos+15] >= size(). size_t size() const; /// Returns the number of chars in the object. Bytes& operator<<(char v); Bytes& operator<<(u8 v); Bytes& operator<<(u16 v); Bytes& operator<<(u32 v); Bytes& operator<<(u64 v); Bytes& operator<<(const Bytes& v); Bytes& operator<<(const char* str); /// Appends the given data to the vector. Returns *this to allow /// chaining. Bytes& operator>>(u8& v); Bytes& operator>>(u16& v); Bytes& operator>>(u32& v); Bytes& operator>>(u64& v); Bytes& operator>>(char& c); /// Extracts the given data type from the vector. Returns *this to /// allow chaining. Bytes extract(size_t len); /** Extracts the first `len` bytes and returns them. Throws * `OutOfRange` if `len` > `size()`. */ void operator=(const Bytes& oth); /// Copies the given Bytes object into its own data. Bytes sub(size_t beg, size_t len) const; /// Extracts a sub-bytes, beginning at character [beg], containing /// [len] chars. If [beg+len] >= [size()], throws OutOfRange. void writeToBuffer(void* buff, unsigned maxLen=0) const; /// Writes the contents of this array in the buffer [buff]. /// The user must provide a buffer of at least [size()] bytes. /// If [maxLen] != 0, writes at most [maxLen] bytes to buff. void hexdump(Bytes& dest) const; /// Dumps the packet to [dest] in hexadecimal form. private: //meth template void insertData(T v); template void extractData(T& v); private: std::vector data; size_t firstIndex; };