M1-nw-project/Bytes.h

82 lines
2.5 KiB
C
Raw Normal View History

2016-11-18 10:56:51 +01:00
/***************************************************************************
* By Théophile Bastian, 2017
* M1 Network course project at ENS Cachan, Juliusz Chroboczek.
* License: WTFPL v2 <http://www.wtfpl.net/>
**************************************************************************/
/***************************************************************************
* Reused from a former project, by Théophile Bastian & Nathanaël Courant
* git@github.com:tobast/sysres-pikern.git
**************************************************************************/
#pragma once
#include <cstdlib>
#include <vector>
#include <exception>
#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);
2016-11-20 00:14:40 +01:00
Bytes& operator<<(u64 v);
2016-11-18 10:56:51 +01:00
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);
2016-11-20 00:14:40 +01:00
Bytes& operator>>(u64& v);
2016-11-18 10:56:51 +01:00
Bytes& operator>>(char& c);
/// Extracts the given data type from the vector. Returns *this to
/// allow chaining.
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<typename T> void insertData(T v);
template<typename T> void extractData(T& v);
private:
std::vector<u8> data;
size_t firstIndex;
};