Master 1 network course project
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

86 lines
2.6 KiB

* 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
#pragma once
#include <cstdlib>
#include <vector>
#include <exception>
#include "data.h"
class Bytes {
class OutOfRange : public std::exception {};
/// Exception -- thrown by operator[]
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<typename T> void insertData(T v);
template<typename T> void extractData(T& v);
std::vector<u8> data;
size_t firstIndex;