forked from kafka-rust/kafka-rust
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcodecs.rs
418 lines (354 loc) · 10.7 KB
/
codecs.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
use std::default::Default;
use std::io::{Read, Write};
use crate::error::{Error, Result};
use byteorder::{BigEndian, ReadBytesExt, WriteBytesExt};
// Helper macro to safely convert an usize expression into a signed
// integer. If the conversion is not possible the macro issues a
// `CodecError`, otherwise returns the expression
// in the requested target type.
macro_rules! try_usize_to_int {
// ~ $ttype should actually be a 'ty' ... but rust complains for
// some reason :/
($value:expr, $ttype:ident) => {{
let maxv = $ttype::max_value();
let x: usize = $value;
if (x as u64) <= (maxv as u64) {
x as $ttype
} else {
return Err(Error::CodecError);
}
}};
}
pub trait ToByte {
fn encode<T: Write>(&self, buffer: &mut T) -> Result<()>;
}
impl<'a, T: ToByte + 'a + ?Sized> ToByte for &'a T {
fn encode<W: Write>(&self, buffer: &mut W) -> Result<()> {
(*self).encode(buffer)
}
}
impl ToByte for i8 {
fn encode<T: Write>(&self, buffer: &mut T) -> Result<()> {
buffer.write_i8(*self).map_err(From::from)
}
}
impl ToByte for i16 {
fn encode<T: Write>(&self, buffer: &mut T) -> Result<()> {
buffer.write_i16::<BigEndian>(*self).map_err(From::from)
}
}
impl ToByte for i32 {
fn encode<T: Write>(&self, buffer: &mut T) -> Result<()> {
buffer.write_i32::<BigEndian>(*self).map_err(From::from)
}
}
impl ToByte for i64 {
fn encode<T: Write>(&self, buffer: &mut T) -> Result<()> {
buffer.write_i64::<BigEndian>(*self).map_err(From::from)
}
}
impl ToByte for str {
fn encode<T: Write>(&self, buffer: &mut T) -> Result<()> {
let l = try_usize_to_int!(self.len(), i16);
buffer.write_i16::<BigEndian>(l)?;
buffer.write_all(self.as_bytes()).map_err(From::from)
}
}
#[test]
fn test_string_too_long() {
use std::str;
let s = vec![b'a'; i16::max_value() as usize + 1];
let s = unsafe { str::from_utf8_unchecked(&s) };
let mut buf = Vec::new();
assert!(s.encode(&mut buf).is_err());
assert!(buf.is_empty());
}
impl<V: ToByte> ToByte for [V] {
fn encode<T: Write>(&self, buffer: &mut T) -> Result<()> {
encode_as_array(buffer, self, |buffer, x| x.encode(buffer))
}
}
impl ToByte for [u8] {
fn encode<T: Write>(&self, buffer: &mut T) -> Result<()> {
let l = try_usize_to_int!(self.len(), i32);
buffer.write_i32::<BigEndian>(l)?;
buffer.write_all(self).map_err(From::from)
}
}
// ~ this allows to render a slice of various types (typically &str
// and String) as strings
pub struct AsStrings<'a, T>(pub &'a [T]);
impl<'a, T: AsRef<str> + 'a> ToByte for AsStrings<'a, T> {
fn encode<W: Write>(&self, buffer: &mut W) -> Result<()> {
encode_as_array(buffer, self.0, |buffer, x| x.as_ref().encode(buffer))
}
}
/// ~ Renders the length of `xs` to `buffer` as the start of a
/// protocol array and then for each element of `xs` invokes `f`
/// assuming that function will render the element to the buffer.
pub fn encode_as_array<T, F, W>(buffer: &mut W, xs: &[T], mut f: F) -> Result<()>
where
F: FnMut(&mut W, &T) -> Result<()>,
W: Write,
{
let l = try_usize_to_int!(xs.len(), i32);
buffer.write_i32::<BigEndian>(l)?;
for x in xs {
f(buffer, x)?;
}
Ok(())
}
// --------------------------------------------------------------------
pub trait FromByte {
type R: Default + FromByte;
fn decode<T: Read>(&mut self, buffer: &mut T) -> Result<()>;
fn decode_new<T: Read>(buffer: &mut T) -> Result<Self::R> {
let mut temp: Self::R = Default::default();
match temp.decode(buffer) {
Ok(_) => Ok(temp),
Err(e) => Err(e),
}
}
}
macro_rules! dec_helper {
($val: expr, $dest:expr) => {{
match $val {
Ok(val) => {
*$dest = val;
Ok(())
}
Err(e) => Err(From::from(e)),
}
}};
}
macro_rules! decode {
($src:expr, $dest:expr) => {{
dec_helper!($src.read_i8(), $dest)
}};
($src:expr, $method:ident, $dest:expr) => {{
dec_helper!($src.$method::<BigEndian>(), $dest)
}};
}
impl FromByte for i8 {
type R = i8;
fn decode<T: Read>(&mut self, buffer: &mut T) -> Result<()> {
decode!(buffer, self)
}
}
impl FromByte for i16 {
type R = i16;
fn decode<T: Read>(&mut self, buffer: &mut T) -> Result<()> {
decode!(buffer, read_i16, self)
}
}
impl FromByte for i32 {
type R = i32;
fn decode<T: Read>(&mut self, buffer: &mut T) -> Result<()> {
decode!(buffer, read_i32, self)
}
}
impl FromByte for i64 {
type R = i64;
fn decode<T: Read>(&mut self, buffer: &mut T) -> Result<()> {
decode!(buffer, read_i64, self)
}
}
impl FromByte for String {
type R = String;
fn decode<T: Read>(&mut self, buffer: &mut T) -> Result<()> {
let mut length: i16 = 0;
if let Err(e) = decode!(buffer, read_i16, &mut length) {
return Err(e);
}
if length <= 0 {
return Ok(());
}
self.reserve(length as usize);
let _ = buffer.take(length as u64).read_to_string(self);
if self.len() != length as usize {
return Err(Error::UnexpectedEOF);
}
Ok(())
}
}
impl<V: FromByte + Default> FromByte for Vec<V> {
type R = Vec<V>;
fn decode<T: Read>(&mut self, buffer: &mut T) -> Result<()> {
let mut length: i32 = 0;
if let Err(e) = decode!(buffer, read_i32, &mut length) {
return Err(e);
}
if length <= 0 {
return Ok(());
}
self.reserve(length as usize);
for _ in 0..length {
let mut e: V = Default::default();
e.decode(buffer)?;
self.push(e);
}
Ok(())
}
}
impl FromByte for Vec<u8> {
type R = Vec<u8>;
fn decode<T: Read>(&mut self, buffer: &mut T) -> Result<()> {
let mut length: i32 = 0;
match decode!(buffer, read_i32, &mut length) {
Ok(_) => {}
Err(e) => return Err(e),
}
if length <= 0 {
return Ok(());
}
self.reserve(length as usize);
match buffer.take(length as u64).read_to_end(self) {
Ok(size) => {
if size < length as usize {
Err(Error::UnexpectedEOF)
} else {
Ok(())
}
}
Err(e) => Err(From::from(e)),
}
}
}
#[test]
fn codec_i8() {
use std::io::Cursor;
let mut buf = vec![];
let orig: i8 = 5;
// Encode into buffer
orig.encode(&mut buf).unwrap();
assert_eq!(buf, [5]);
// Read from buffer into existing variable
let mut dec1: i8 = 0;
dec1.decode(&mut Cursor::new(&buf[..])).unwrap();
assert_eq!(dec1, orig);
// Read from buffer into new variable
let dec2 = i8::decode_new(&mut Cursor::new(&buf[..])).unwrap();
assert_eq!(dec2, orig);
}
#[test]
fn codec_i16() {
use std::io::Cursor;
let mut buf = vec![];
let orig: i16 = 5;
// Encode into buffer
orig.encode(&mut buf).unwrap();
assert_eq!(buf, [0, 5]);
// Read from buffer into existing variable
let mut dec1: i16 = 0;
dec1.decode(&mut Cursor::new(&buf[..])).unwrap();
assert_eq!(dec1, orig);
// Read from buffer into new variable
let dec2 = i16::decode_new(&mut Cursor::new(&buf[..])).unwrap();
assert_eq!(dec2, orig);
}
#[test]
fn codec_32() {
use std::io::Cursor;
let mut buf = vec![];
let orig: i32 = 5;
// Encode into buffer
orig.encode(&mut buf).unwrap();
assert_eq!(buf, [0, 0, 0, 5]);
// Read from buffer into existing variable
let mut dec1: i32 = 0;
dec1.decode(&mut Cursor::new(&buf[..])).unwrap();
assert_eq!(dec1, orig);
// Read from buffer into new variable
let dec2 = i32::decode_new(&mut Cursor::new(&buf[..])).unwrap();
assert_eq!(dec2, orig);
}
#[test]
fn codec_i64() {
use std::io::Cursor;
let mut buf = vec![];
let orig: i64 = 5;
// Encode into buffer
orig.encode(&mut buf).unwrap();
assert_eq!(buf, [0, 0, 0, 0, 0, 0, 0, 5]);
// Read from buffer into existing variable
let mut dec1: i64 = 0;
dec1.decode(&mut Cursor::new(&buf[..])).unwrap();
assert_eq!(dec1, orig);
// Read from buffer into new variable
let dec2 = i64::decode_new(&mut Cursor::new(&buf[..])).unwrap();
assert_eq!(dec2, orig);
}
#[test]
fn codec_string() {
use std::io::Cursor;
let mut buf = vec![];
let orig = "test".to_owned();
// Encode into buffer
orig.encode(&mut buf).unwrap();
assert_eq!(buf, [0, 4, 116, 101, 115, 116]);
// Read from buffer into existing variable
let mut dec1 = String::new();
dec1.decode(&mut Cursor::new(&buf[..])).unwrap();
assert_eq!(dec1, orig);
// Read from buffer into new variable
let dec2 = String::decode_new(&mut Cursor::new(&buf[..])).unwrap();
assert_eq!(dec2, orig);
}
#[test]
fn codec_vec_u8() {
use std::io::Cursor;
let mut buf = vec![];
let orig: Vec<u8> = vec![1, 2, 3];
// Encode into buffer
orig.encode(&mut buf).unwrap();
assert_eq!(buf, [0, 0, 0, 3, 1, 2, 3]);
// Read from buffer into existing variable
let mut dec1: Vec<u8> = vec![];
dec1.decode(&mut Cursor::new(&buf[..])).unwrap();
assert_eq!(dec1, orig);
// Read from buffer into new variable
let dec2 = Vec::<u8>::decode_new(&mut Cursor::new(&buf[..])).unwrap();
assert_eq!(dec2, orig);
}
#[test]
fn codec_as_strings() {
macro_rules! enc_dec_cmp {
($orig:expr) => {{
use std::io::Cursor;
let orig = $orig;
// Encode into buffer
let mut buf = Vec::new();
AsStrings(&orig).encode(&mut buf).unwrap();
assert_eq!(
buf,
[0, 0, 0, 2, 0, 3, b'a', b'b', b'c', 0, 4, b'd', b'e', b'f', b'g']
);
// Decode from buffer into existing value
{
let mut dec: Vec<String> = Vec::new();
dec.decode(&mut Cursor::new(&buf[..])).unwrap();
assert_eq!(dec, orig);
}
// Read from buffer into new variable
{
let dec = Vec::<String>::decode_new(&mut Cursor::new(&buf[..])).unwrap();
assert_eq!(dec, orig);
}
}};
}
{
// slice of &str
let orig: &[&str] = &["abc", "defg"];
enc_dec_cmp!(orig);
}
{
// vec of &str
let orig: Vec<&str> = vec!["abc", "defg"];
enc_dec_cmp!(orig);
}
{
// vec of String
let orig: Vec<String> = vec!["abc".to_owned(), "defg".to_owned()];
enc_dec_cmp!(orig);
}
}