1/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */
2/* If you are missing that file, acquire a complete release at teeworlds.com. */
3#ifndef ENGINE_SHARED_PACKER_H
4#define ENGINE_SHARED_PACKER_H
5
6#include <cstddef>
7
8/**
9 * Abstract packer implementation. Subclasses must supply the buffer.
10 */
11class CAbstractPacker
12{
13private:
14 unsigned char *const m_pBuffer;
15 const size_t m_BufferSize;
16 unsigned char *m_pCurrent;
17 unsigned char *m_pEnd;
18 bool m_Error;
19
20protected:
21 CAbstractPacker(unsigned char *pBuffer, size_t Size);
22
23public:
24 void Reset();
25 void AddInt(int i);
26 void AddString(const char *pStr, int Limit = 0, bool AllowTruncation = true);
27 void AddRaw(const void *pData, int Size);
28
29 int Size() const { return (int)(m_pCurrent - m_pBuffer); }
30 const unsigned char *Data() const { return m_pBuffer; }
31 bool Error() const { return m_Error; }
32};
33
34/**
35 * Default packer with buffer for networking.
36 */
37class CPacker : public CAbstractPacker
38{
39public:
40 enum
41 {
42 PACKER_BUFFER_SIZE = 1024 * 2
43 };
44 CPacker() :
45 CAbstractPacker(m_aBuffer, sizeof(m_aBuffer))
46 {
47 }
48
49private:
50 unsigned char m_aBuffer[PACKER_BUFFER_SIZE];
51};
52
53class CUnpacker
54{
55 const unsigned char *m_pStart;
56 const unsigned char *m_pCurrent;
57 const unsigned char *m_pEnd;
58 bool m_Error;
59
60public:
61 enum
62 {
63 SANITIZE = 1,
64 SANITIZE_CC = 2,
65 SKIP_START_WHITESPACES = 4
66 };
67
68 void Reset(const void *pData, int Size);
69 int GetInt();
70 int GetIntOrDefault(int Default);
71 int GetUncompressedInt();
72 int GetUncompressedIntOrDefault(int Default);
73 const char *GetString(int SanitizeType = SANITIZE);
74 const unsigned char *GetRaw(int Size);
75 bool Error() const { return m_Error; }
76
77 int CompleteSize() const { return m_pEnd - m_pStart; }
78 const unsigned char *CompleteData() const { return m_pStart; }
79};
80
81#endif
82