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
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
use crate::protocol::{Encapsulation, Header, Identity, RequestData, ReplyData};
use crate::errors::*;
use std::convert::TryInto;
use std::collections::HashMap;
use std::hash::Hash;


pub struct IceSize {
    pub size: i32
}

// TRAITS
pub trait ToBytes {
    fn to_bytes(&self) -> Result<Vec<u8>, Box<dyn std::error::Error>>;
}

pub trait FromBytes {
    fn from_bytes(bytes: &[u8], read_bytes: &mut i32) -> Result<Self, Box<dyn std::error::Error>> where Self: Sized;
}



// BASIC ENCODING FUNCTIONS
impl ToBytes for IceSize {
    fn to_bytes(&self) -> Result<Vec<u8>, Box<dyn std::error::Error>> {
        if self.size < 255 {
            Ok(vec![self.size as u8])
        } else {
            let mut bytes = vec![255];
            bytes.extend(self.size.to_bytes()?);
            Ok(bytes)
        }    
    }
}

impl FromBytes for IceSize {
    fn from_bytes(bytes: &[u8], read_bytes: &mut i32) -> Result<Self, Box<dyn std::error::Error>>
    where Self: Sized {
        if bytes.len() < 1 {
            Err(Box::new(ProtocolError {}))
        }   
        else if bytes[0] == 255 {
            if bytes.len() < 5 {
                Err(Box::new(ProtocolError {}))
            } else {
                *read_bytes = 1;
                Ok(IceSize {
                    size: i32::from_bytes(&bytes[1..5], read_bytes)?
                })
            }
        } else {
            Ok(IceSize {
                size: u8::from_bytes(bytes, read_bytes)? as i32
            })
        }   
    }
}

impl ToBytes for str {
    fn to_bytes(&self) -> Result<Vec<u8>, Box<dyn std::error::Error>> {
        let mut bytes = IceSize{size: self.len() as i32}.to_bytes()?;
        bytes.extend(self.as_bytes());
        Ok(bytes)
    }
}

impl ToBytes for String {
    fn to_bytes(&self) -> Result<Vec<u8>, Box<dyn std::error::Error>> {
        let mut bytes = IceSize{size: self.len() as i32}.to_bytes()?;
        bytes.extend(self.as_bytes());
        Ok(bytes)
    }
}

impl FromBytes for String {
    fn from_bytes(bytes: &[u8], read_bytes: &mut i32) -> Result<Self, Box<dyn std::error::Error>>
    where Self: Sized {
        let mut read = 0;
        let size = IceSize::from_bytes(bytes, &mut read)?.size;
        let s = String::from_utf8(bytes[read as usize..read as usize + size as usize].to_vec())?;
        *read_bytes = *read_bytes + read + size;
        Ok(s)
    }
}


impl<T: ToBytes, U: ToBytes> ToBytes for HashMap<T, U> {
    fn to_bytes(&self) -> Result<Vec<u8>, Box<dyn std::error::Error>> {
        let mut bytes = IceSize{size: self.len() as i32}.to_bytes()?;
        for (key, value) in self {
            bytes.extend(key.to_bytes()?);
            bytes.extend(value.to_bytes()?);
        }
        Ok(bytes)
    }
}

impl<T: FromBytes + Eq + Hash, U: FromBytes> FromBytes for HashMap<T, U> {
    fn from_bytes(bytes: &[u8], read_bytes: &mut i32) -> Result<Self, Box<dyn std::error::Error>>
    where Self: Sized {
        let mut read = 0;
        let size = IceSize::from_bytes(bytes, &mut read)?.size;
        let mut dict: HashMap<T, U> = HashMap::new();

        for _i in 0..size {
            let key = T::from_bytes(&bytes[read as usize..bytes.len()], &mut read)?;
            let value = U::from_bytes(&bytes[read as usize..bytes.len()], &mut read)?;
            dict.insert(key, value);
        }
        *read_bytes = *read_bytes + read;
        Ok(dict)
    }
}

impl<T: ToBytes> ToBytes for Vec<T>
{
    fn to_bytes(&self) -> Result<Vec<u8>, Box<dyn std::error::Error>> {
        let mut bytes = IceSize{size: self.len() as i32}.to_bytes()?;
        for item in self {
            bytes.extend(item.to_bytes()?);
        }
        Ok(bytes)
    }
}

impl<T: FromBytes> FromBytes for Vec<T>
{
    fn from_bytes(bytes: &[u8], read_bytes: &mut i32) -> Result<Self, Box<dyn std::error::Error>>
    where Self: Sized {
        let mut read = 0;
        let size = IceSize::from_bytes(bytes, &mut read)?.size;
        let mut seq: Vec<T> = vec![];

        for _i in 0..size {
            seq.push(T::from_bytes(&bytes[read as usize..bytes.len()], &mut read)?);
        }
        *read_bytes = *read_bytes + read;
        Ok(seq)
    }
}

impl ToBytes for u8 {
    fn to_bytes(&self) -> Result<Vec<u8>, Box<dyn std::error::Error>> {
        Ok(vec![*self])
    }
}

impl FromBytes for u8 {
    fn from_bytes(bytes: &[u8], read_bytes: &mut i32) -> Result<Self, Box<dyn std::error::Error>>
    where Self: Sized {
        *read_bytes = *read_bytes + 1;
        Ok(bytes[0])
    }
}

impl ToBytes for i16 {
    fn to_bytes(&self) -> Result<Vec<u8>, Box<dyn std::error::Error>> {
        Ok(self.to_le_bytes().to_vec())
    }
}

impl FromBytes for i16 {
    fn from_bytes(bytes: &[u8], read_bytes: &mut i32) -> Result<Self, Box<dyn std::error::Error>>
    where Self: Sized {
        let size = std::mem::size_of::<i16>();
        if bytes.len() < size {
            return Err(Box::new(ProtocolError {}));
        }
        match bytes[0..size].try_into() {
            Ok(barray) => {
                *read_bytes = *read_bytes + size as i32;
                Ok(i16::from_le_bytes(barray))
            },
            _ => Err(Box::new(ProtocolError {}))
        }
    }
}

impl ToBytes for i32 {
    fn to_bytes(&self) -> Result<Vec<u8>, Box<dyn std::error::Error>> {
        Ok(self.to_le_bytes().to_vec())
    }
}

impl FromBytes for i32 {
    fn from_bytes(bytes: &[u8], read_bytes: &mut i32) -> Result<Self, Box<dyn std::error::Error>>
    where Self: Sized {
        let size = std::mem::size_of::<i32>();
        if bytes.len() < size {
            return Err(Box::new(ProtocolError {}));
        }
        match bytes[0..size].try_into() {
            Ok(barray) => {
                *read_bytes = *read_bytes + size as i32;
                Ok(i32::from_le_bytes(barray))
            },
            _ => Err(Box::new(ProtocolError {}))
        }
    }
}

impl ToBytes for i64 {
    fn to_bytes(&self) -> Result<Vec<u8>, Box<dyn std::error::Error>> {
        Ok(self.to_le_bytes().to_vec())
    }
}

impl FromBytes for i64 {
    fn from_bytes(bytes: &[u8], read_bytes: &mut i32) -> Result<Self, Box<dyn std::error::Error>>
    where Self: Sized {
        let size = std::mem::size_of::<i64>();
        if bytes.len() < size {
            return Err(Box::new(ProtocolError {}));
        }
        match bytes[0..size].try_into() {
            Ok(barray) => {
                *read_bytes = *read_bytes + size as i32;
                Ok(i64::from_le_bytes(barray))
            },
            _ => Err(Box::new(ProtocolError {}))
        }
    }
}

impl ToBytes for f32 {
    fn to_bytes(&self) -> Result<Vec<u8>, Box<dyn std::error::Error>> {
        Ok(self.to_le_bytes().to_vec())
    }
}

impl FromBytes for f32 {
    fn from_bytes(bytes: &[u8], read_bytes: &mut i32) -> Result<Self, Box<dyn std::error::Error>>
    where Self: Sized {
        let size = std::mem::size_of::<f32>();
        if bytes.len() < size {
            return Err(Box::new(ProtocolError {}));
        }
        match bytes[0..size].try_into() {
            Ok(barray) => {
                *read_bytes = *read_bytes + size as i32;
                Ok(f32::from_le_bytes(barray))
            },
            _ => Err(Box::new(ProtocolError {}))
        }
    }
}

impl ToBytes for f64 {
    fn to_bytes(&self) -> Result<Vec<u8>, Box<dyn std::error::Error>> {
        Ok(self.to_le_bytes().to_vec())
    }
}

impl FromBytes for f64 {
    fn from_bytes(bytes: &[u8], read_bytes: &mut i32) -> Result<Self, Box<dyn std::error::Error>>
    where Self: Sized {
        let size = std::mem::size_of::<f64>();
        if bytes.len() < size {
            return Err(Box::new(ProtocolError {}));
        }
        match bytes[0..size].try_into() {
            Ok(barray) => {
                *read_bytes = *read_bytes + size as i32;
                Ok(f64::from_le_bytes(barray))
            },
            _ => Err(Box::new(ProtocolError {}))
        }
    }
}

impl ToBytes for bool {
    fn to_bytes(&self) -> Result<Vec<u8>, Box<dyn std::error::Error>> {
        Ok(vec![if *self { 1 } else { 0 }])
    }
}

impl FromBytes for bool {
    fn from_bytes(bytes: &[u8], read_bytes: &mut i32) -> Result<Self, Box<dyn std::error::Error>>
    where Self: Sized {
        if bytes.len() < 1 {
            return Err(Box::new(ProtocolError {}));
        }
        *read_bytes = *read_bytes + 1;
        Ok(bytes[0] != 0)
    }
}


// PROTOCOL STRUCT AS/FROM BYTES
impl ToBytes for Identity {
    fn to_bytes(&self) -> Result<Vec<u8>, Box<dyn std::error::Error>>
    {
        let mut buffer: Vec<u8> = Vec::new();
        buffer.extend(self.name.to_bytes()?);
        buffer.extend(self.category.to_bytes()?);
        Ok(buffer)
    }
}

impl FromBytes for Identity {
    fn from_bytes(bytes: &[u8], read_bytes: &mut i32) -> Result<Self, Box<dyn std::error::Error>> {
        let mut read = 0;
        let name = String::from_bytes(&bytes[read as usize..bytes.len()], &mut read)?;
        let category = String::from_bytes(&bytes[read as usize..bytes.len()], &mut read)?;
        *read_bytes = *read_bytes + read;
        Ok(Identity {
            name: name,
            category: category
        })
    }
}

impl ToBytes for Encapsulation {
    fn to_bytes(&self) -> Result<Vec<u8>, Box<dyn std::error::Error>>
    {
        let mut buffer: Vec<u8> = Vec::new();
        buffer.extend(&self.size.to_le_bytes());
        buffer.push(self.major);
        buffer.push(self.minor);
        if self.data.len() > 0 {
            buffer.extend(&self.data);
        }
        Ok(buffer)
    }
}

impl FromBytes for Encapsulation {
    fn from_bytes(bytes: &[u8], read_bytes: &mut i32) -> Result<Self, Box<dyn std::error::Error>> {
        let mut read: i32 = 0;
        if bytes.len() < 6 {
            return Err(Box::new(ProtocolError {}));
        }

        let size = i32::from_bytes(&bytes[read as usize..bytes.len()], &mut read)?;
        let major = u8::from_bytes(&bytes[read as usize..bytes.len()], &mut read)?;
        let minor = u8::from_bytes(&bytes[read as usize..bytes.len()], &mut read)?;
        *read_bytes = *read_bytes + read + (bytes.len() as i32 - read);

        Ok(Encapsulation {
            size: size,
            major: major,
            minor: minor,
            data: bytes[read as usize..bytes.len()].to_vec()
        })
    }
}

impl ToBytes for RequestData {
    fn to_bytes(&self) -> Result<Vec<u8>, Box<dyn std::error::Error>>
    {
        let mut buffer: Vec<u8> = Vec::new();
        buffer.extend(self.request_id.to_bytes()?);
        buffer.extend(self.id.to_bytes()?);
        buffer.extend(self.facet.to_bytes()?);
        buffer.extend(self.operation.to_bytes()?);
        buffer.extend(self.mode.to_bytes()?);
        buffer.extend(self.context.to_bytes()?);
        buffer.extend(self.params.to_bytes()?);

        Ok(buffer)        

    }
}

impl FromBytes for RequestData {
    fn from_bytes(bytes: &[u8], read_bytes: &mut i32) -> Result<Self, Box<dyn std::error::Error>> {
        let mut read = 0;
        let request_id = i32::from_bytes(bytes, &mut read)?;
        let id = Identity::from_bytes(&bytes[read as usize..bytes.len()], &mut read)?;
        let facet = Vec::from_bytes(&bytes[read as usize..bytes.len()], &mut read)?;
        let operation = String::from_bytes(&bytes[read as usize..bytes.len()], &mut read)?;
        let mode = u8::from_bytes(&bytes[read as usize..bytes.len()], &mut read)?;
        let context = HashMap::from_bytes(&bytes[read as usize..bytes.len()], &mut read)?;
        let encapsulation = Encapsulation::from_bytes(&bytes[read as usize..bytes.len()], &mut read)?;
        *read_bytes = *read_bytes + read;

        Ok(RequestData {
            request_id: request_id,
            id: id,
            facet: facet,
            operation: operation,
            mode: mode,
            context: context,
            params: encapsulation
        })
    }
}


impl ToBytes for ReplyData {
    fn to_bytes(&self) -> Result<Vec<u8>, Box<dyn std::error::Error>>
    {
        let mut buffer: Vec<u8> = Vec::new();
        buffer.extend(self.request_id.to_bytes()?);
        buffer.extend(self.status.to_bytes()?);
        buffer.extend(self.body.to_bytes()?);

        Ok(buffer)
    }
}

impl FromBytes for ReplyData {
    fn from_bytes(bytes: &[u8], read_bytes: &mut i32) -> Result<Self, Box<dyn std::error::Error>> {
        let mut read: i32 = 0;
        if bytes.len() < 11 {
            return Err(Box::new(ProtocolError {}));
        }

        let request_id = i32::from_bytes(&bytes[read as usize..bytes.len()], &mut read)?;
        let status = u8::from_bytes(&bytes[read as usize..bytes.len()], &mut read)?;
        match status {
            0 | 1 => {
                let encapsulation = Encapsulation::from_bytes(&bytes[read as usize..bytes.len()], &mut read)?;
                *read_bytes = *read_bytes + read;
                Ok(ReplyData {
                    request_id: request_id,
                    status: status,
                    body: encapsulation
                })
            }
            // 1 => {
            //     Err(Error::EncapsulatedUserException(Encapsulation::from_bytes(&bytes[read as usize..bytes.len()], &mut read)?))
            // }
            7 => {
                Err(Box::new(
                    RemoteException { 
                        cause: String::from_bytes(&bytes[read as usize..bytes.len()], &mut read)?
                    }
                ))
            }
            _ => Err(Box::new(ProtocolError {}))
        }
    }
}

impl ToBytes for Header {
    fn to_bytes(&self) -> Result<Vec<u8>, Box<dyn std::error::Error>>
    {
        let mut buffer: Vec<u8> = Vec::new();
        buffer.extend(self.magic.as_bytes());
        buffer.extend(self.protocol_major.to_bytes()?);
        buffer.extend(self.protocol_minor.to_bytes()?);
        buffer.extend(self.encoding_major.to_bytes()?);
        buffer.extend(self.encoding_minor.to_bytes()?);
        buffer.extend(self.message_type.to_bytes()?);
        buffer.extend(self.compression_status.to_bytes()?);
        buffer.extend(&self.message_size.to_le_bytes());

        Ok(buffer)
    }
}

impl FromBytes for Header {
    fn from_bytes(bytes: &[u8], read_bytes: &mut i32) -> Result<Self, Box<dyn std::error::Error>> {
        if bytes.len() < 14 {
            return Err(Box::new(ProtocolError {}));
        }

        let magic = String::from_utf8(bytes[0..4].to_vec())?;
        if magic != "IceP" {
            return Err(Box::new(ProtocolError {}));
        }        
        let mut read: i32 = 4;
        let protocol_major = u8::from_bytes(&bytes[read as usize..bytes.len()], &mut read)?;
        let protocol_minor = u8::from_bytes(&bytes[read as usize..bytes.len()], &mut read)?;
        let encoding_major = u8::from_bytes(&bytes[read as usize..bytes.len()], &mut read)?;
        let encoding_minor = u8::from_bytes(&bytes[read as usize..bytes.len()], &mut read)?;
        let message_type = u8::from_bytes(&bytes[read as usize..bytes.len()], &mut read)?;
        let comression_status = u8::from_bytes(&bytes[read as usize..bytes.len()], &mut read)?;
        let message_size = i32::from_bytes(&bytes[read as usize..bytes.len()], &mut read)?;
        *read_bytes = *read_bytes + read;

        Ok(Header {
            magic: magic,
            protocol_major: protocol_major,
            protocol_minor: protocol_minor,
            encoding_major: encoding_major,
            encoding_minor: encoding_minor,
            message_type: message_type,
            compression_status: comression_status,
            message_size: message_size
        })
    }
}

impl<T: ToBytes> ToBytes for Option<T> {
    fn to_bytes(&self) -> Result<Vec<u8>, Box<dyn std::error::Error>> {
        let mut bytes = Vec::new();
        match self {
            Some(value) => { 
                bytes.extend((11 as u8).to_bytes()?);
                bytes.extend(value.to_bytes()?);
            }
            None => {}
        }
        Ok(bytes)
    }
}

impl<T: FromBytes> FromBytes for Option<T> {
    fn from_bytes(bytes: &[u8], read_bytes: &mut i32) -> Result<Self, Box<dyn std::error::Error>> {
        if bytes.len() > 0 {
            let mut read: i32 = 0;
            let _flag = u8::from_bytes(&bytes[read as usize..bytes.len()], &mut read)?;
            let result = Some(T::from_bytes(&bytes[read as usize..bytes.len()], &mut read)?);
            *read_bytes = *read_bytes + read;
            Ok(result)
        } else {
            Ok(None)
        }
    }
}

#[cfg(test)]
mod test {
    use super::*;

    #[test]
    fn test_size_encoding() {
        let mut read_bytes = 0;
        let encoded = IceSize{size: 10}.to_bytes().expect("Could not encode size");
        let decoded = IceSize::from_bytes(&encoded, &mut read_bytes).expect("Could not decode size").size;
        assert_eq!(10, decoded);
        assert_eq!(1, read_bytes);

        read_bytes = 0;
        let encoded = IceSize{size: 500}.to_bytes().expect("Could not encode size");
        let decoded = IceSize::from_bytes(&encoded, &mut read_bytes).expect("Could not decode size").size;
        assert_eq!(500, decoded);
        assert_eq!(5, read_bytes);
    }

    #[test]
    fn test_string_encoding() {
        let mut read_bytes = 0;
        let encoded = "Hello".to_bytes().expect("Cannot necode test string");
        let decoded = String::from_bytes(&encoded, &mut read_bytes).expect("Cannot decode test string");
        assert_eq!("Hello", decoded);
        assert_eq!(6, read_bytes);
    }

    #[test]
    fn test_dict_encoding() {
        let mut read_bytes = 0;
        let mut dict = HashMap::new();
        dict.insert(String::from("Hello"), String::from("World"));

        let encoded = dict.to_bytes().expect("Cannot encode test dict");
        let decoded: HashMap<String, String> = HashMap::from_bytes(&encoded, &mut read_bytes).expect("Cannot decode test dict");
        assert!(decoded.contains_key("Hello"));
        assert_eq!("World", decoded.get("Hello").unwrap_or(&String::from("")));
    }

    #[test]
    fn test_string_seq_encoding() {
        let mut read_bytes = 0;
        let seq = vec![String::from("Hello"), String::from("World")];
        let encoded = seq.to_bytes().expect("Cannot encode test dict");
        let decoded: Vec<String> = Vec::from_bytes(&encoded, &mut read_bytes).expect("Cannot decode test dict");
        assert_eq!(2, decoded.len());
        assert_eq!(seq, decoded);
    }

    #[test]
    fn test_short_encoding() {
        let mut read_bytes = 0;
        let value: i16 = 3;
        let encoded = value.to_bytes().expect("Cannot encode test short");
        let decoded = i16::from_bytes(&encoded, &mut read_bytes).expect("Cannot decode test short");
        assert_eq!(value, decoded);
    }

    #[test]
    fn test_int_encoding() {
        let mut read_bytes = 0;
        let value: i32 = 3;
        let encoded = value.to_bytes().expect("Cannot encode test int");
        let decoded = i32::from_bytes(&encoded, &mut read_bytes).expect("Cannot decode test int");
        assert_eq!(value, decoded);
    }

    #[test]
    fn test_long_encoding() {
        let mut read_bytes = 0;
        let value: i64 = 3;
        let encoded = value.to_bytes().expect("Cannot encode test long");
        let decoded = i64::from_bytes(&encoded, &mut read_bytes).expect("Cannot decode test long");
        assert_eq!(value, decoded);
    }

    #[test]
    fn test_float_encoding() {
        let mut read_bytes = 0;
        let value: f32 = 3.14;
        let encoded = value.to_bytes().expect("Cannot encode test float");
        let decoded = f32::from_bytes(&encoded, &mut read_bytes).expect("Cannot decode test float");
        assert_eq!(value, decoded);
    }

    #[test]
    fn test_double_encoding() {
        let mut read_bytes = 0;
        let value: f64 = 3.14;
        let encoded = value.to_bytes().expect("Cannot encode test double");
        let decoded = f64::from_bytes(&encoded, &mut read_bytes).expect("Cannot decode double long");
        assert_eq!(value, decoded);
    }

    #[test]
    fn test_bool_encoding() {
        let mut read_bytes = 0;
        let value = true;
        let encoded = value.to_bytes().expect("Cannot encode test bool");
        let decoded = bool::from_bytes(&encoded, &mut read_bytes).expect("Cannot decode test bool");
        assert_eq!(value, decoded);
    }

    #[test]
    fn test_identity_ecoding() {
        let mut read_bytes = 0;
        let id = Identity {
            name: String::from("Hello"),
            category: String::from(""),
        };
        let bytes = id.to_bytes().expect("Cannot encode test identity");
        let decoded = Identity::from_bytes(&bytes, &mut read_bytes).expect("Cannot decode test identity");
        assert_eq!(7, read_bytes);
        assert_eq!(id.name, decoded.name);
        assert_eq!(id.category, decoded.category);
    }

    #[test]
    fn test_header_ecoding() {
        let mut read_bytes = 0;
        let header = Header::new(0, 14);
        let bytes = header.to_bytes().expect("Cannot encode test header");
        let decoded = Header::from_bytes(&bytes, &mut read_bytes).expect("Cannot decode test header");
        assert_eq!(14, read_bytes);
        assert_eq!(header.magic, decoded.magic);
        assert_eq!(header.message_size, decoded.message_size);
        assert_eq!(header.message_type, decoded.message_type);
        assert_eq!(header.magic, decoded.magic);
    }

    #[test]
    fn test_request_ecoding() {
        let mut read_bytes = 0;
        let request = RequestData {
            request_id: 1,
            id: Identity {
                name: String::from("Test"),
                category: String::from(""),
            },
            facet: vec![],
            operation: String::from("Op"),
            mode: 0,
            context: HashMap::new(),
            params: Encapsulation::empty()
        };
        let bytes = request.to_bytes().expect("Cannot encode test request");
        let decoded = RequestData::from_bytes(&bytes, &mut read_bytes).expect("Cannot decode test request");
        assert_eq!(22, read_bytes);
        assert_eq!(request.request_id, decoded.request_id);
        assert_eq!(request.id.name, decoded.id.name);
        assert_eq!(request.facet, decoded.facet);
        assert_eq!(request.operation, decoded.operation);
        assert_eq!(request.mode, decoded.mode);
        assert_eq!(request.context, decoded.context);
    }

    #[test]
    fn test_reply_encoding() {
        let mut read_bytes = 0;
        let reply = ReplyData {
            request_id: 1,
            status: 0,
            body: Encapsulation::empty()
        };
        let bytes = reply.to_bytes().expect("Cannot encode test reply");
        let decoded = ReplyData::from_bytes(&bytes, &mut read_bytes).expect("Cannot decode test reply");        
        assert_eq!(11, read_bytes);
        assert_eq!(reply.request_id, decoded.request_id);
        assert_eq!(reply.status, decoded.status);
    }
}