Blob Blame Raw
#ifndef COMMON_H
#define COMMON_H


enum {
	PACKET_SIZE     = 1024,
	PACKETS_COUNT   = 8*PACKET_SIZE,
	TCP_BUFFER_SIZE = PACKET_SIZE*PACKETS_COUNT,
};

enum : unsigned short {
	CMD_SHIFT   = 12,
	CMD_MASK    = (unsigned short)(0xffff << CMD_SHIFT),
	SIZE_MASK   = (unsigned short)(~CMD_MASK),
	
	CMD_DATA    = 0,
	CMD_TERM    = 1,
	CMD_CONFIRM = 2,
};



typedef unsigned long long Time;


inline bool cycleLequal(unsigned int a, unsigned int b)
	{ return (b - a) <= 0x7fffffff; }
inline bool cycleLess(unsigned int a, unsigned int b)
	{ return !cycleLequal(b, a); }
inline bool timeLequal(Time a, Time b)
	{ return (b - a) <= 0x7fffffffffffffffull; }
inline bool timeLess(Time a, Time b)
	{ return !timeLequal(b, a); }



class Address {
public:
	union {
		struct { unsigned int ipUInt; };
		struct { unsigned char ip[4]; };
	};
	unsigned short port;
	inline Address(): ipUInt(), port() { }
	inline bool operator<(const Address &other) const {
		return ipUInt < other.ipUInt ? true
		     : other.ipUInt < ipUInt ? false
		     : port < other.port;
	}
	
	void print() const;
};


class ConnId {
public:
	Address address;
	unsigned int id;
	inline ConnId(): id() { }
	inline bool operator<(const ConnId &other) const {
		return address < other.address ? true
				: other.address < address ? false
				: id < other.id;
	}
};


struct __attribute__((__packed__)) Packet {
	unsigned int connId;
	unsigned int index;
	unsigned short cmdSize;
	unsigned char payload[PACKET_SIZE];
	
	enum { HEADER_SIZE = ((Packet*)nullptr)->payload - nullptr; };
	
	inline Packet():
		connId(), index(), cmdSize(), payload() { }
		
	inline int getSize() const
		{ return cmdSize & SIZE_MASK; }
	inline int getCommand() const
		{ return cmdSize >> CMD_SHIFT; }
	
	inline init(
		unsigned int connId,
		unsigned int index,
		unsigned short cmd,
		unsigned short size )
	{
		this->connId = connId;
		this->index = index;
		this->cmd = cmd;
		this->size = size;
	}
};


#endif