]> git.stg.codes - stg.git/blob - stglibs/sgcp.lib/include/stg/sgcp_proto.h
Introduced SGCP library.
[stg.git] / stglibs / sgcp.lib / include / stg / sgcp_proto.h
1 #ifndef __STG_SGCP_PROTO_H__
2 #define __STG_SGCP_PROTO_H__
3
4 /*
5  *    This program is free software; you can redistribute it and/or modify
6  *    it under the terms of the GNU General Public License as published by
7  *    the Free Software Foundation; either version 2 of the License, or
8  *    (at your option) any later version.
9  *
10  *    This program is distributed in the hope that it will be useful,
11  *    but WITHOUT ANY WARRANTY; without even the implied warranty of
12  *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  *    GNU General Public License for more details.
14  *
15  *    You should have received a copy of the GNU General Public License
16  *    along with this program; if not, write to the Free Software
17  *    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
18  */
19
20 /*
21  *    Author : Maxim Mamontov <faust@stargazer.dp.ua>
22  */
23
24 #include "sgcp_types.h" // TransportType
25 #include "sgcp_utils.h" // hton/ntoh
26
27 #include "stg/os_int.h"
28
29 #include <string>
30 #include <vector>
31 #include <stdexcept>
32
33 namespace STG
34 {
35 namespace SGCP
36 {
37
38 class TransportProto;
39
40 class Proto
41 {
42     public:
43         struct Error : public std::runtime_error
44         {
45             Error(const std::string& mesage);
46             Error();
47         };
48
49         Proto(TransportType transport, const std::string& key);
50         ~Proto();
51
52         void connect(const std::string& address, uint16_t port);
53
54         void writeAllBuf(const void* buf, size_t size);
55         void readAllBuf(void* buf, size_t size);
56
57         template <typename T>
58         void writeAll(const T& value);
59
60         template <typename T>
61         T readAll();
62
63     private:
64         TransportProto* m_transport;
65 };
66
67 template <>
68 inline
69 void Proto::writeAll<uint64_t>(const uint64_t& value)
70 {
71     uint64_t temp = hton(value);
72     writeAllBuf(&temp, sizeof(temp));
73 }
74
75 template <>
76 inline
77 void Proto::writeAll<std::string>(const std::string& value)
78 {
79     uint64_t size = hton(value.size());
80     writeAllBuf(&size, sizeof(size));
81     writeAllBuf(value.c_str(), value.size());
82 }
83
84 template <>
85 inline
86 uint64_t Proto::readAll<uint64_t>()
87 {
88     uint64_t temp = 0;
89     readAllBuf(&temp, sizeof(temp));
90     return ntoh(temp);
91 }
92
93 template <>
94 inline
95 std::string Proto::readAll<std::string>()
96 {
97     uint64_t size = 0;
98     readAllBuf(&size, sizeof(size));
99     size = ntoh(size);
100     std::vector<char> res(size);
101     readAllBuf(res.data(), res.size());
102     return res.data();
103 }
104
105 } // namespace SGCP
106 } // namespace STG
107
108 #endif