@@ -25,18 +25,10 @@ namespace rawrbox {
25
25
};
26
26
// ----------------
27
27
28
- enum class LengthType {
29
- UInt8 ,
30
- UInt16 ,
31
- UInt32 ,
32
- UInt64
33
- };
34
-
35
28
class Packet {
36
29
protected:
37
30
std::vector<uint8_t > buffer = {};
38
31
size_t pos = 0 ;
39
- LengthType lengthFormat = LengthType::UInt16 ;
40
32
41
33
public:
42
34
Packet () = default ;
@@ -124,15 +116,23 @@ namespace rawrbox {
124
116
}
125
117
}
126
118
127
- template <class T >
119
+ template <class T = size_t >
128
120
T readLength () {
129
- switch (this ->lengthFormat ) {
130
- case LengthType::UInt8 : return static_cast <T>(this ->read <uint8_t >());
131
- case LengthType::UInt16 : return static_cast <T>(this ->read <uint16_t >());
132
- case LengthType::UInt32 : return static_cast <T>(this ->read <uint32_t >());
133
- case LengthType::UInt64 : return static_cast <T>(this ->read <uint64_t >());
134
- default : throw std::runtime_error (" [RawrBox-Packet] Unknown lengthFormat" );
121
+ constexpr uint64_t maskNum = 0x7F ;
122
+ constexpr uint64_t maskFlag = 0x80 ;
123
+
124
+ uint64_t ret = 0 ;
125
+ uint64_t bitsReceived = 0 ;
126
+ while (true ) {
127
+ uint64_t byte = read <uint8_t >();
128
+
129
+ ret = ret | ((byte & maskNum) << bitsReceived);
130
+ bitsReceived += 7 ;
131
+
132
+ if ((byte & maskFlag) == 0 ) break ;
135
133
}
134
+
135
+ return static_cast <T>(ret);
136
136
}
137
137
138
138
virtual void read (std::string& ret);
@@ -208,21 +208,28 @@ namespace rawrbox {
208
208
209
209
void write (const std::string& obj, bool shouldWriteLength = true );
210
210
211
- template <class T >
211
+ template <class T = size_t >
212
212
void writeLength (T size) {
213
- switch (this ->lengthFormat ) {
214
- case LengthType::UInt8 : this ->write (static_cast <uint8_t >(size)); break ;
215
- case LengthType::UInt16 : this ->write (static_cast <uint16_t >(size)); break ;
216
- case LengthType::UInt32 : this ->write (static_cast <uint32_t >(size)); break ;
217
- case LengthType::UInt64 : this ->write (static_cast <uint64_t >(size)); break ;
218
- default : throw std::runtime_error (" [RawrBox-Packet] Unknown lengthFormat" );
213
+ if (size < 0 ) throw std::runtime_error (" [RawrBox-Packet] invalid length" );
214
+ if (size == 0 ) {
215
+ write <uint8_t >(0 );
216
+ return ;
217
+ }
218
+
219
+ auto remaining = static_cast <size_t >(size);
220
+ constexpr uint64_t maskNum = 0x7F ;
221
+ constexpr uint64_t maskFlag = 0x80 ;
222
+
223
+ while (remaining > 0 ) {
224
+ bool hasMore = (remaining >> 7 ) > 0 ;
225
+ write (static_cast <uint8_t >((remaining & maskNum) | (hasMore ? maskFlag : 0x00ULL )));
226
+
227
+ remaining >>= 7 ;
219
228
}
220
229
}
221
230
// -----------------
222
231
223
232
// UTILS -----
224
- void setlengthFormat (LengthType format);
225
-
226
233
bool seek (size_t offset);
227
234
bool seek (std::vector<uint8_t >::iterator offset);
228
235
0 commit comments