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
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
//! A Rust library for parsing the SOME/IP network protocol (without payload interpretation).
//!
//! # Usage
//!
//! Add the following to your `Cargo.toml`:
//!
//! ```toml
//! [dependencies]
//! someip_parse = "0.3.0"
//! ```
//!
//! # Example
//! [examples/print_messages.rs](https://github.com/JulianSchmid/someip-parse-rs/blob/0.2.0/examples/print_messages.rs):
//! ```
//! # let mut udp_payload = Vec::<u8>::new();
//! # {
//! #     use someip_parse::*;
//! #     let header = SomeIpHeader{
//! #         message_id: 0x1234_8234,
//! #         length: SOMEIP_LEN_OFFSET_TO_PAYLOAD + 4,
//! #         request_id: 1,
//! #         interface_version: 1,
//! #         message_type: MessageType::Notification,
//! #         return_code: ReturnCode::Ok.into(),
//! #         tp_header: None
//! #     };/*
//! #     header.write_raw(&mut udp_payload).unwrap();
//! #     udp_payload.extend_from_slice(&[1,2,3,4]);*/
//! # }
//! use someip_parse::SliceIterator;
//! 
//! //trying parsing some ip messages located in a udp payload
//! for someip_message in SliceIterator::new(&udp_payload) {
//!     match someip_message {
//!         Ok(value) => {
//!             if value.is_someip_sd() {
//!                 println!("someip service discovery packet");
//!             } else {
//!                 println!("0x{:x} (service id: 0x{:x}, method/event id: 0x{:x})", 
//!                          value.message_id(), 
//!                          value.service_id(),
//!                          value.event_or_method_id());
//!             }
//!             println!("  with payload {:?}", value.payload())
//!         },
//!         Err(_) => {} //error reading a someip packet (based on size, protocol version value or message type value)
//!     }
//! }
//! ```
//! 
//! # Todo
//! * Example how to serialize someip packets
//! * SOMEIP Service Discovery Message Parsing
//! 
//! # References
//! * [AUTOSAR Foundation 1.5.0](https://www.autosar.org/standards/foundation/foundation-150/) \(contains SOMEIP Protocol Specification 1.5.0 & SOME/IP Service Discovery Protocol Specification 1.5.0\) 
//! * [SOME/IP Protocol Specification 1.3.0](https://www.autosar.org/fileadmin/user_upload/standards/foundation/1-3/AUTOSAR_PRS_SOMEIPProtocol.pdf)
//! * [SOME/IP Service Discovery Protocol Specification 1.3.0](https://www.autosar.org/fileadmin/user_upload/standards/foundation/1-3/AUTOSAR_PRS_SOMEIPServiceDiscoveryProtocol.pdf)

use std::io::{Read, Write};
use std::slice::from_raw_parts;

#[cfg(test)]
#[macro_use]
extern crate assert_matches;
#[cfg(test)]
#[macro_use]
extern crate proptest;
#[cfg(test)]
mod proptest_generators;

///The currently supported protocol version.
pub const SOMEIP_PROTOCOL_VERSION: u8 = 1;

///Offset that must be substracted from the length field to determine the length of the actual payload.
pub const SOMEIP_LEN_OFFSET_TO_PAYLOAD: u32 = 4*2; // 2x 32bits

///Maximum payload length supported by some ip. This is NOT the maximum length that is supported when
///sending packets over UDP. This constant is based on the limitation of the length field data type (uint32).
pub const SOMEIP_MAX_PAYLOAD_LEN: u32 = std::u32::MAX - SOMEIP_LEN_OFFSET_TO_PAYLOAD;

///Length of a someip header.
pub const SOMEIP_HEADER_LENGTH: usize = 4*4;

///Length of the tp header that follows a someip header if a someip packet has been flaged as tp.
pub const TP_HEADER_LENGTH: usize = 4;

///Flag in the message type field marking the package a as tp message (transporting large SOME/IP messages of UDP).
pub const SOMEIP_HEADER_MESSAGE_TYPE_TP_FLAG: u8 = 0x20;

///Message id of SOMEIP service discovery messages
pub const SOMEIP_SD_MESSAGE_ID: u32 = 0xffff_8100;

///SOMEIP header (including tp header if present).
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct SomeIpHeader {
    pub message_id: u32,
    pub length: u32,
    pub request_id: u32,
    pub interface_version: u8,
    ///Message type (does not contain the tp flag, this is determined if something is present in the tp_header field).
    pub message_type: MessageType,
    pub return_code: u8, //TODO replace with enum?
    ///Contains a tp header (Transporting large SOME/IP messages of UDP [SOME/IP-TP]).
    ///
    ///If there is a tp header a someip payload is split over multiple messages and the tp header contains the 
    ///start offset of the payload of this message relative to the completly assembled payload.
    pub tp_header: Option<TpHeader>
}

///Message types of a SOME/IP message.
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum MessageType {
    Request = 0x0,
    RequestNoReturn = 0x1,
    Notification = 0x2,
    Response = 0x80,
    Error = 0x81
}

///Return code contained in a SOME/IP header.
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub enum ReturnCode {
    Ok,// = 0x00,
    NotOk,// = 0x01,
    UnknownService,// = 0x02,
    UnknownMethod, //= 0x03
    NotReady,// = 0x04,
    NotReachable,// = 0x05,
    Timeout,// = 0x06,
    WrongProtocolVersion,// = 0x07,
    WrongInterfaceVersion,// = 0x08,
    MalformedMessage,// = 0x09,
    WrongMessageType,// = 0x0a,
    Generic(u8),
    InterfaceError(u8),
}

impl From<ReturnCode> for u8 {
    fn from(r: ReturnCode) -> u8 {
        use ReturnCode::*;
        match r {
            Ok => 0x00,
            NotOk => 0x01,
            UnknownService => 0x02,
            UnknownMethod => 0x03,
            NotReady=> 0x04,
            NotReachable => 0x05,
            Timeout => 0x06,
            WrongProtocolVersion => 0x07,
            WrongInterfaceVersion => 0x08,
            MalformedMessage => 0x09,
            WrongMessageType => 0x0a,
            Generic(value) => value,
            InterfaceError(value) => value,
        }
    }
}

impl SomeIpHeader {

    ///Returns the service id (first 16 bits of the message id)
    #[inline]
    pub fn service_id(&self) -> u16 {
        ((self.message_id & 0xffff_0000) >> 16) as u16
    }

    ///Set the servide id (first 16 bits of the message id)
    #[inline]
    pub fn set_service_id(&mut self, service_id: u16) {
        self.message_id = (self.message_id & 0x0000_ffff) | (u32::from(service_id) << 16);
    }

    ///Set the event id + the event bit.
    #[inline]
    pub fn set_event_id(&mut self, event_id : u16) {
        self.message_id = (self.message_id & 0xffff_0000) | u32::from(0x8000 | event_id);
    }

    ///Set the event id + the event bit to 0. Asserting method_id <= 0x7FFF (otherwise the )
    #[inline]
    pub fn set_method_id(&mut self, method_id : u16) {
        debug_assert!(method_id <= 0x7FFF);
        self.message_id = (self.message_id & 0xffff_0000) | u32::from(0x7fff & method_id);
    }

    ///Sets the event id or method id. This number mjust include the "event bit".
    #[inline]
    pub fn set_method_or_event_id(&mut self, method_id : u16) {
        self.message_id = (self.message_id & 0xffff_0000) | u32::from(method_id);
    }

    ///Returns true if the message has the message id of a some ip service discovery message.
    #[inline]
    pub fn is_someip_sd(&self) -> bool {
        SOMEIP_SD_MESSAGE_ID == self.message_id
    }

    ///Returns true if the event or notification bit in the message id is set
    #[inline]
    pub fn is_event(&self) -> bool {
        0 != self.message_id & 0x8000
    }

    ///Return the event id or method id. This number includes the "event bit".
    #[inline]
    pub fn event_or_method_id(&self) -> u16 {
        (self.message_id & 0x0000_ffff) as u16
    }

    ///Serialize the header.
    pub fn write_raw<T: Write>(&self, writer: &mut T) -> Result<(), WriteError> {
        writer.write_all(&self.base_to_bytes())?;
        if let Some(ref tp) = self.tp_header {
            tp.write(writer)?;
        }
        Ok(())
    }

    /// Returns the encoded SOMEIP header (without the TP header).
    #[inline]
    pub fn base_to_bytes(&self) -> [u8;SOMEIP_HEADER_LENGTH] {
        let message_id_be = self.message_id.to_be_bytes();
        let length_be = self.length.to_be_bytes();
        let request_id_be = self.request_id.to_be_bytes();
        [
            message_id_be[0],
            message_id_be[1],
            message_id_be[2],
            message_id_be[3],

            length_be[0],
            length_be[1],
            length_be[2],
            length_be[3],

            request_id_be[0],
            request_id_be[1],
            request_id_be[2],
            request_id_be[3],

            SOMEIP_PROTOCOL_VERSION,
            self.interface_version,
            match self.tp_header {
                Some(_) => (self.message_type.clone() as u8) | SOMEIP_HEADER_MESSAGE_TYPE_TP_FLAG,
                None => (self.message_type.clone() as u8)
            },
            self.return_code,
        ]
    }

    ///Read a header from a byte stream.
    pub fn read<T: Read>(reader: &mut T) -> Result<SomeIpHeader, ReadError> {
        use ReadError::*;

        // read the header
        let mut header_bytes : [u8;SOMEIP_HEADER_LENGTH] = [0;SOMEIP_HEADER_LENGTH];
        reader.read_exact(&mut header_bytes)?;

        // validate length
        let length = u32::from_be_bytes(
            [
                header_bytes[4],
                header_bytes[5],
                header_bytes[6],
                header_bytes[7]
            ]
        );
        if length < SOMEIP_LEN_OFFSET_TO_PAYLOAD {
            return Err(LengthFieldTooSmall(length));
        }

        // validate protocol version
        let protocol_version = header_bytes[12];
        if SOMEIP_PROTOCOL_VERSION != protocol_version {
            return Err(UnsupportedProtocolVersion(protocol_version));
        }

        // validate message type
        let message_type_raw = header_bytes[14];
        let message_type = {
            use MessageType::*;
            //check that message type is valid
            match message_type_raw & !(SOMEIP_HEADER_MESSAGE_TYPE_TP_FLAG) {
                0x0 => Request,
                0x1 => RequestNoReturn,
                0x2 => Notification,
                0x80 => Response,
                0x81 => Error,
                _ => return Err(UnknownMessageType(message_type_raw))
            }
        };

        Ok(SomeIpHeader {
            message_id: u32::from_be_bytes(
                [
                    header_bytes[0],
                    header_bytes[1],
                    header_bytes[2],
                    header_bytes[3],
                ]
            ),
            length,
            request_id: u32::from_be_bytes(
                [
                    header_bytes[8],
                    header_bytes[9],
                    header_bytes[10],
                    header_bytes[11],
                ]
            ),
            interface_version: header_bytes[13],
            message_type,
            return_code: header_bytes[15],
            //read the tp header if the flag is set
            tp_header: if 0 != message_type_raw & SOMEIP_HEADER_MESSAGE_TYPE_TP_FLAG {
                Some(TpHeader::read(reader)?)
            } else {
                None
            }
        })
    }
}

///Additional header when a packet contains a TP header (transporting large SOME/IP messages).
#[derive(Clone, Debug, Default, Eq, PartialEq)]
pub struct TpHeader {
    ///Offset of the payload relativ the start of the completly assempled payload.
    offset: u32,
    ///Flag signaling that more packets should follow
    pub more_segment: bool
}

impl TpHeader {

    ///Creates a tp header with offset 0 and the given "move_segment" flag.
    ///
    /// # Example:
    ///
    /// ```
    /// use someip_parse::TpHeader;
    /// 
    /// // create a header with the more_segement flag set
    /// let header = TpHeader::new(true);
    ///
    /// assert_eq!(0, header.offset());
    /// assert_eq!(true, header.more_segment);
    /// ```
    #[inline]
    pub fn new(more_segment: bool) -> TpHeader {
        TpHeader {
            offset: 0,
            more_segment
        }
    }

    /// Creates a tp header with the given offset & "more_segment" flag if the offset is a multiple of 16.
    /// Otherwise an TpOffsetNotMultipleOf16 error is returned.
    ///
    /// # Example:
    ///
    /// ```
    /// use someip_parse::{TpHeader, ValueError};
    /// 
    /// // create a header with offset 32 (multiple of 16) and the more_segement flag set
    /// let header = TpHeader::with_offset(32, true).unwrap();
    ///
    /// assert_eq!(32, header.offset());
    /// assert_eq!(true, header.more_segment);
    ///
    /// // try to create a header with a bad offset (non multiple of 16)
    /// let error = TpHeader::with_offset(31, false);
    ///
    /// assert_eq!(Err(ValueError::TpOffsetNotMultipleOf16(31)), error);
    /// ```
    pub fn with_offset(offset: u32, more_segment: bool) -> Result<TpHeader, ValueError> {
        use ValueError::*;
        if 0 != offset % 16 {
            Err(TpOffsetNotMultipleOf16(offset))
        } else {
            Ok(TpHeader {
                offset,
                more_segment
            })
        }
    }

    /// Returns the offset field of the tp header. The offset defines 
    #[inline]
    pub fn offset(&self) -> u32 {
        self.offset
    }

    /// Sets the field of the header and returns Ok(()) on success. Note: The value must be a multiple of 16.
    ///
    /// If the given value is not a multiple of 16, the value is not set and an error 
    /// ValueError::TpOffsetNotMultipleOf16 is returned.
    pub fn set_offset(&mut self, value: u32) -> Result<(), ValueError> {
        use ValueError::*;
        if 0 != value % 16 {
            Err(TpOffsetNotMultipleOf16(value))
        } else {
            self.offset = value;
            Ok(())
        }
    }

    /// Read a header from a byte stream.
    pub fn read<T: Read>(reader: &mut T) -> Result<TpHeader, ReadError> {
        let mut buffer = [0u8;TP_HEADER_LENGTH];
        reader.read_exact(&mut buffer)?;
        let more_segment = 0 != (buffer[3] & 0b0001u8);

        //mask out the flags
        buffer[3] &= !0b1111u8;

        Ok(TpHeader{
            offset: u32::from_be_bytes(buffer),
            more_segment
        })
    }

    /// Reads a tp header from a slice.
    pub fn read_from_slice(slice: &[u8]) -> Result<TpHeader, ReadError> {
        if slice.len() < TP_HEADER_LENGTH {
            use ReadError::*;
            Err(UnexpectedEndOfSlice(TP_HEADER_LENGTH))
        } else {
            Ok(
                // SAFETY:
                // Safe as a length check is preformed that the slice has
                // the minimum size of TP_HEADER_LENGTH.
                unsafe {
                    TpHeader::from_slice_unchecked(slice.as_ptr())
                }
            )
        }
    }

    /// Read the value from the slice without checking for the minimum length of the slice.
    ///
    /// Safety:
    ///
    /// It is required that the slice has at least the length of TP_HEADER_LENGTH (4 octets/bytes).
    /// If this is not the case undefined behavior will occur.
    #[inline]
    unsafe fn from_slice_unchecked(ptr: *const u8) -> TpHeader {
        //return result
        TpHeader{
            offset: u32::from_be_bytes(
                [
                    *ptr,
                    *ptr.add(1),
                    *ptr.add(2),
                    *ptr.add(3) & 0b1111_0000u8,
                ]
            ),
            more_segment: 0 != (*ptr.add(3) & 0b0001u8),
        }
    }
    
    /// Writes the header to the given writer.
    #[inline]
    pub fn write<T: Write>(&self, writer: &mut T) -> Result<(), WriteError> {
        writer.write_all(&self.to_bytes())?;
        Ok(())
    }

    /// Writes the header to a slice.
    #[inline]
    pub fn write_to_slice(&self, slice: &mut [u8]) -> Result<(), WriteError> {
        if slice.len() < TP_HEADER_LENGTH {
            use WriteError::*;
            Err(UnexpectedEndOfSlice(TP_HEADER_LENGTH))
        } else {
            let buffer = self.to_bytes();
            let target = &mut slice[0..4];
            target[0] = buffer[0];
            target[1] = buffer[1];
            target[2] = buffer[2];
            target[3] = buffer[3];
            Ok(())
        }
    }

    ///Writes the header to a slice without checking the slice length.
    #[inline]
    pub fn to_bytes(&self) -> [u8;4] {
        let mut result = self.offset.to_be_bytes();
        if self.more_segment {
            result[3] |= 0x1u8; 
        }
        result
    }
}

///A slice containing an some ip header & payload of that message.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct SomeIpHeaderSlice<'a> {
    ///If true a TP header is following the SOME/IP header.
    tp: bool,
    slice: &'a [u8]
}

impl<'a> SomeIpHeaderSlice<'a> {

    #[cfg(target_pointer_width = "64")] 
    pub fn from_slice(slice: &'a[u8]) -> Result<SomeIpHeaderSlice, ReadError> {
        use ReadError::*;
        //first check the length
        if slice.len() < SOMEIP_HEADER_LENGTH {
            Err(UnexpectedEndOfSlice(slice.len()))
        } else {
            //check length
            let len = {
                // SAFETY:
                // Read is save as it is checked before that the slice has at least
                // SOMEIP_HEADER_LENGTH 16 bytes.
                unsafe {
                    get_unchecked_be_u32(slice.as_ptr().add(4))
                }
            };
            if len < SOMEIP_LEN_OFFSET_TO_PAYLOAD {
                return Err(LengthFieldTooSmall(len));
            }
            //NOTE: In case you want to write a 32 bit version, a check needs to be added, so that
            //      no accidental overflow when adding the 4*2 bytes happens.
            let total_length = (len as usize) + 4*2;
            if slice.len() < total_length {
                return Err(UnexpectedEndOfSlice(slice.len()))
            }
            //check protocol version
            let protocol_version = {
                // SAFETY:
                // Read is save as it is checked before that the slice has at least
                // SOMEIP_HEADER_LENGTH 16 (4*4) bytes.
                unsafe {
                    *slice.get_unchecked(4*3)
                }
            };
            if SOMEIP_PROTOCOL_VERSION != protocol_version {
                return Err(UnsupportedProtocolVersion(protocol_version));
            }

            //check message type
            let message_type = {
                // SAFETY:
                // Read is save as it is checked before that the slice has at least
                // SOMEIP_HEADER_LENGTH 16 (4*4) bytes.
                unsafe {
                    *slice.get_unchecked(4*3 + 2)
                }
            };

            //check the length is still ok, in case of a tp flag
            let tp = 0 != message_type & SOMEIP_HEADER_MESSAGE_TYPE_TP_FLAG;
            if tp && len < SOMEIP_LEN_OFFSET_TO_PAYLOAD + 4 {
                return Err(LengthFieldTooSmall(len));
            }

            //make sure the message type is known
            match message_type & !(SOMEIP_HEADER_MESSAGE_TYPE_TP_FLAG) {
                0x0 | 0x1 | 0x2 | 0x80 | 0x81 => {},
                _ => return Err(UnknownMessageType(message_type))
            }
            
            //all good generate the slice
            Ok(SomeIpHeaderSlice {
                tp,
                // SAFETY: Check is preformed above to ensure slice has at least total length
                slice: unsafe {
                    from_raw_parts(
                        slice.as_ptr(),
                        total_length
                    )
                }
            })
        }
    }

    #[cfg(target_pointer_width = "32")] 
    pub fn from_slice(slice: &'a[u8]) -> Result<SomeIpHeaderSlice, ReadError> {
        use ReadError::*;
        //first check the length
        if slice.len() < SOMEIP_HEADER_LENGTH {
            Err(UnexpectedEndOfSlice(slice.len()))
        } else {
            //check length
            let len = {
                // SAFETY:
                // Read is save as it is checked before that the slice has at least
                // SOMEIP_HEADER_LENGTH 16 bytes.
                unsafe {
                    get_unchecked_be_u32(slice.as_ptr().add(4))
                }
            };
            if len < SOMEIP_LEN_OFFSET_TO_PAYLOAD {
                return Err(LengthFieldTooSmall(len));
            }

            //NOTE: This additional check is needed for 32 bit systems, as otherwise an overflow could potentially be happening
            const MAX_SUPPORTED_LEN: usize = std::usize::MAX - 4*2;
            let len_usize = len as usize;
            if len_usize > MAX_SUPPORTED_LEN {
                return Err(UnexpectedEndOfSlice(slice.len()));
            }

            let total_length = len_usize + 4*2;
            if slice.len() < total_length {
                return Err(UnexpectedEndOfSlice(slice.len()))
            }
            //check protocol version
            let protocol_version = {
                // SAFETY:
                // Read is save as it is checked before that the slice has at least
                // SOMEIP_HEADER_LENGTH 16 (4*4) bytes.
                unsafe {
                    *slice.get_unchecked(4*3)
                }
            };
            if SOMEIP_PROTOCOL_VERSION != protocol_version {
                return Err(UnsupportedProtocolVersion(protocol_version));
            }

            //check message type
            let message_type = {
                // SAFETY:
                // Read is save as it is checked before that the slice has at least
                // SOMEIP_HEADER_LENGTH 16 (4*4) bytes.
                unsafe {
                    *slice.get_unchecked(4*3 + 2)
                }
            };

            //check the length is still ok, in case of a tp flag
            let tp = 0 != message_type & SOMEIP_HEADER_MESSAGE_TYPE_TP_FLAG;
            if tp && len < SOMEIP_LEN_OFFSET_TO_PAYLOAD + 4 {
                return Err(LengthFieldTooSmall(len));
            }

            //make sure the message type is known
            match message_type & !(SOMEIP_HEADER_MESSAGE_TYPE_TP_FLAG) {
                0x0 | 0x1 | 0x2 | 0x80 | 0x81 => {},
                _ => return Err(UnknownMessageType(message_type))
            }
            
            //all good generate the slice
            Ok(SomeIpHeaderSlice {
                tp,
                // SAFETY: Check is preformed above to ensure slice has at least total length
                slice: unsafe {
                    from_raw_parts(
                        slice.as_ptr(),
                        total_length
                    )
                }
            })
        }
    }

    ///Return the slice that contains the someip header
    #[inline]
    pub fn slice(&self) -> &'a [u8] {
        self.slice
    }

    ///Returns the message id of the message.
    #[inline]
    pub fn message_id(&self) -> u32 {
        // SAFETY:
        // Safe as the slice length is checked to have at least a length of
        // SOMEIP_HEADER_LENGTH (16) during construction of the struct.
        unsafe {
            get_unchecked_be_u32(self.slice.as_ptr())
        }
    }

    ///Returns the service id (first 16 bits of the message id)
    #[inline]
    pub fn service_id(&self) -> u16 {
        // SAFETY:
        // Safe as the slice length is checked to have at least a length of
        // SOMEIP_HEADER_LENGTH (16) during construction of the struct.
        unsafe {
            get_unchecked_be_u16(self.slice.as_ptr())
        }
    }

    ///Returns true if the event or notification bit in the message id is set
    #[inline]
    pub fn is_event(&self) -> bool {
        // SAFETY:
        // Safe as the slice length is checked to have at least a length of
        // SOMEIP_HEADER_LENGTH (16) during construction of the struct.
        0 != unsafe {
            self.slice.get_unchecked(2)
        } & 0x80
    }

    ///Return the event id or method id. This number includes the "event bit".
    #[inline]
    pub fn event_or_method_id(&self) -> u16 {
        // SAFETY:
        // Safe as the slice length is checked to have at least a length of
        // SOMEIP_HEADER_LENGTH (16) during construction of the struct.
        unsafe {
            get_unchecked_be_u16(self.slice.as_ptr().add(2))
        }
    }

    ///Returns true if the message has the message id of a some ip service discovery message.
    #[inline]
    pub fn is_someip_sd(&self) -> bool {
        SOMEIP_SD_MESSAGE_ID == self.message_id()
    }

    /// Returns the length contained in the header. WARNING: the length paritally 
    /// contains the header and partially the payload, use the payload() method 
    /// instead if you want to access the payload slice).
    #[inline]
    pub fn length(&self) -> u32 {
        // SAFETY:
        // Safe as the slice length is checked to have at least a length of
        // SOMEIP_HEADER_LENGTH (16) during construction of the struct.
        unsafe {
            get_unchecked_be_u32(self.slice.as_ptr().add(4))
        }
    }

    ///Returns the request id of the message.
    #[inline]
    pub fn request_id(&self) -> u32 {
        // SAFETY:
        // Safe as the slice length is checked to have at least a length of
        // SOMEIP_HEADER_LENGTH (16) during construction of the struct.
        unsafe {
            get_unchecked_be_u32(self.slice.as_ptr().add(8))
        }
    }

    ///Return the value of the protocol version field of the message (must match SOMEIP_PROTOCOL_VERSION, unless something dark and unsafe is beeing done).
    #[inline]
    pub fn protocol_version(&self) -> u8 {
        debug_assert!(SOMEIP_PROTOCOL_VERSION == self.slice[12]);
        // SAFETY:
        // Safe as the slice length is checked to have at least a length of
        // SOMEIP_HEADER_LENGTH (16) during construction of the struct.
        unsafe {
            *self.slice.get_unchecked(12)
        }
    }

    ///Returns the interface version field of the message.
    #[inline]
    pub fn interface_version(&self) -> u8 {
        // SAFETY:
        // Safe as the slice length is checked to have at least a length of
        // SOMEIP_HEADER_LENGTH (16) during construction of the struct.
        unsafe {
            *self.slice.get_unchecked(13)
        }
    }

    ///Return the message type (does not contain the tp flag, use the message_type_tp method for 
    ///checking if this is a tp message).
    pub fn message_type(&self) -> MessageType {
        use MessageType::*;
        match self.message_type_raw() & !(SOMEIP_HEADER_MESSAGE_TYPE_TP_FLAG) {
            0x0 => Request,
            0x1 => RequestNoReturn,
            0x2 => Notification,
            0x80 => Response,
            0x81 => Error,
            _ => panic!("unknown message type, this should not happen as the message type gets verified during the construction of SomeIpHeaderSlice")
        }
    }

    ///Returns the raw message type value (contains the tp flag).
    #[inline]
    pub fn message_type_raw(&self) -> u8 {
        // SAFETY:
        // Safe as the slice length is checked to have at least a length of
        // SOMEIP_HEADER_LENGTH (16) during construction of the struct.
        unsafe {
            *self.slice.get_unchecked(14)
        }
    }

    ///Returns true if the tp flag in the message type is set (Transporting large SOME/IP messages of UDP [SOME/IP-TP])
    #[inline]
    pub fn is_tp(&self) -> bool {
        self.tp
    }

    ///Returns the return code of the message.
    #[inline]
    pub fn return_code(&self) -> u8 {
        // SAFETY:
        // Safe as the slice length is checked to have at least a length of
        // SOMEIP_HEADER_LENGTH (16) during construction of the struct.
        unsafe {
            *self.slice.get_unchecked(15)
        }
    }

    /// Return a slice to the payload of the someip header.
    ///
    /// If the there is tp header present the memory after the tp
    /// header is returned.
    #[inline]
    pub fn payload(&self) -> &'a [u8] {
        if self.tp {
            const OFFSET: usize = SOMEIP_HEADER_LENGTH + TP_HEADER_LENGTH;
            debug_assert!(OFFSET <= self.slice.len());
            // SAFETY:
            // Safe as it is checked in SomeipHeaderSlice::from_slice that the
            // slice has at least SOMEIP_HEADER_LENGTH + TP_HEADER_LENGTH len
            // if the tp flag is set.
            unsafe {
                from_raw_parts(
                    self.slice.as_ptr().add(OFFSET),
                    self.slice.len() - OFFSET
                )
            }
        } else {
            // SAFETY:
            // Safe as it is checked in SomeipHeaderSlice::from_slice that the
            // slice has at least SOMEIP_HEADER_LENGTH len.
            unsafe {
                from_raw_parts(
                    self.slice.as_ptr().add(SOMEIP_HEADER_LENGTH),
                    self.slice.len() - SOMEIP_HEADER_LENGTH
                )
            }
        }
    }

    ///Returns the tp header if there should be one present.
    #[inline]
    pub fn tp_header(&self) -> Option<TpHeader> {
        if self.tp {
            Some(
                // SAFETY
                // Safe as the slice len is checked to have SOMEIP_HEADER_LENGTH + TP_HEADER_LENGTH
                // length during SomeIpHeaderSlice::from_slice.
                unsafe {
                    TpHeader::from_slice_unchecked(
                        self.slice.as_ptr().add(SOMEIP_HEADER_LENGTH)
                    )
                }
            )
        } else {
            None
        }
    }

    ///Decode all the fields and copy the results to a SomeIpHeader struct
    pub fn to_header(&self) -> SomeIpHeader {
        SomeIpHeader {
            message_id: self.message_id(),
            length: self.length(),
            request_id: self.request_id(),
            interface_version: self.interface_version(),
            message_type: self.message_type(),
            return_code: self.return_code(),
            tp_header: self.tp_header(),
        }
    }
}

///Allows iterating over the someip messages in a udp or tcp payload.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct SliceIterator<'a> {
    slice: &'a [u8]
}

impl<'a> SliceIterator<'a> {
    pub fn new(slice: &'a [u8]) -> SliceIterator<'a> {
        SliceIterator {
            slice
        }
    }
}

impl<'a> Iterator for SliceIterator<'a> {
    type Item = Result<SomeIpHeaderSlice<'a>, ReadError>;

    fn next(&mut self) -> Option<Result<SomeIpHeaderSlice<'a>, ReadError>> {
        if !self.slice.is_empty() {
            //parse
            let result = SomeIpHeaderSlice::from_slice(self.slice);

            //move the slice depending on the result
            match &result {
                Err(_) => {
                    //error => move the slice to an len = 0 position so that the iterator ends
                    let len = self.slice.len();
                    self.slice = &self.slice[len..];
                }
                Ok(ref value) => {
                    //by the length just taken by the slice
                    self.slice = &self.slice[value.slice().len()..];
                }
            }

            //return parse result
            Some(result)
        } else {
            None
        }
    }
}

impl Default for SomeIpHeader {
    fn default() -> SomeIpHeader {
        SomeIpHeader{
            message_id: 0,
            length: SOMEIP_LEN_OFFSET_TO_PAYLOAD,
            request_id: 0,
            interface_version: 0,
            message_type: MessageType::Request,
            return_code: 0,
            tp_header: None
        }
    }
}

///Errors that can occur when reading someip headers.
#[derive(Debug)]
pub enum ReadError {
    IoError(std::io::Error),
    ///The slice length was not large enough to contain the header.
    UnexpectedEndOfSlice(usize),
    ///Error when the protocol version field contains a version that is not supported by this library (aka != SOMEIP_PROTOCOL_VERSION)
    UnsupportedProtocolVersion(u8),
    ///Error returned when a someip header has a value in the length field that is smaller then the rest of someip header itself (8 bytes).
    LengthFieldTooSmall(u32),
    ///Error when the message type field contains an unknown value
    UnknownMessageType(u8)
}

impl From<std::io::Error> for ReadError {
    fn from(err: std::io::Error) -> ReadError {
        ReadError::IoError(err)
    }
}

///Errors that can occur when serializing a someip & tp header.
#[derive(Debug)]
pub enum WriteError {
    IoError(std::io::Error),
    ///The slice length was not large enough to write the header.
    UnexpectedEndOfSlice(usize)
}

impl From<std::io::Error> for WriteError {
    fn from(err: std::io::Error) -> WriteError {
        WriteError::IoError(err)
    }
}

///Range errors in fields of the someip & tp header struct. These can occur when serializing or modifying an error.
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum ValueError {
    /// Payload length is too long as 8 bytes for the header have to be added.
    LengthTooLarge(u32),

    /// Offset of the tp header is not a multiple of 16.
    ///
    /// PRS_SOMEIP_00724: The Offset field shall transport the upper 28 bits of a 
    /// uint32. The lower 4 bits shall be always interpreted as 0.
    /// Note: This means that the offset field can only transport offset values 
    /// that are multiples of 16 bytes.
    TpOffsetNotMultipleOf16(u32)
}

/// Helper function for reading big endian u32 values from a ptr unchecked.
///
/// # Safety
///
/// It is in the responsibility of the caller to ensure there are at least 4
/// bytes accessable via the ptr. If this is not the case undefined behavior
/// will be triggered.
#[inline]
unsafe fn get_unchecked_be_u32(ptr: *const u8) -> u32 {
    u32::from_be_bytes(
        [
            *ptr,
            *ptr.add(1),
            *ptr.add(2),
            *ptr.add(3)
        ]
    )
}

/// Helper function for reading big endian u16 values from a ptr unchecked.
///
/// # Safety
///
/// It is in the responsibility of the caller to ensure there are at least 2
/// bytes accessable via the ptr. If this is not the case undefined behavior
/// will be triggered.
#[inline]
unsafe fn get_unchecked_be_u16(ptr: *const u8) -> u16 {
    u16::from_be_bytes(
        [
            *ptr,
            *ptr.add(1),
        ]
    )
}

#[cfg(test)]
mod tests_return_code {

    proptest! {
        #[test]
        fn into_u8(generic_error in 0x0bu8..0x20,
                   interface_error in 0x20u8..0x5F)
        {
            use ReturnCode::*;
            let values = [
                (Ok, 0x00),
                (NotOk, 0x01),
                (UnknownService, 0x02),
                (UnknownMethod, 0x03),
                (NotReady, 0x04),
                (NotReachable, 0x05),
                (Timeout, 0x06),
                (WrongProtocolVersion, 0x07),
                (WrongInterfaceVersion, 0x08),
                (MalformedMessage, 0x09),
                (WrongMessageType, 0x0a),
                (Generic(generic_error), generic_error),
                (InterfaceError(interface_error), interface_error),
            ];
            for (ref input, ref expected) in values.iter() {
                let result: u8 = (*input).into();
                assert_eq!(*expected, result);
            }
        }
    }
}

#[cfg(test)]
mod tests_someip_header {
    use super::*;
    use super::proptest_generators::*;
    use proptest::prelude::*;
    use std::io::Cursor;
    use MessageType::*;
    use ReadError::*;

    const MESSAGE_TYPE_VALUES: &'static [MessageType;5] = &[
        Request,
        RequestNoReturn,
        Notification,
        Response,
        Error
    ];

    const MESSAGE_TYPE_VALUES_RAW: &'static [u8;10] = &[
        Request as u8,
        RequestNoReturn as u8,
        Notification as u8,
        Response as u8,
        Error as u8,
        Request as u8 | SOMEIP_HEADER_MESSAGE_TYPE_TP_FLAG,
        RequestNoReturn as u8 | SOMEIP_HEADER_MESSAGE_TYPE_TP_FLAG,
        Notification as u8 | SOMEIP_HEADER_MESSAGE_TYPE_TP_FLAG,
        Response as u8 | SOMEIP_HEADER_MESSAGE_TYPE_TP_FLAG,
        Error as u8 | SOMEIP_HEADER_MESSAGE_TYPE_TP_FLAG,
    ];

    #[test]
    fn default() {
        let header: SomeIpHeader = Default::default();
        assert_eq!(0, header.message_id);
        assert_eq!(SOMEIP_LEN_OFFSET_TO_PAYLOAD, header.length);
        assert_eq!(0, header.request_id);
        assert_eq!(0, header.interface_version);
        assert_eq!(MessageType::Request, header.message_type);
        assert_eq!(None, header.tp_header);
        assert_eq!(0, header.return_code);
    }

    proptest! {
        #[test]
        fn write_read(ref input_base in someip_header_any()) {
            for message_type in MESSAGE_TYPE_VALUES {
                let input = {
                    let mut value = input_base.clone();
                    value.message_type = message_type.clone();
                    value
                };
                let mut buffer = Vec::new();
                input.write_raw(&mut buffer).unwrap();

                //read the header
                let mut cursor = Cursor::new(&buffer);
                let result = SomeIpHeader::read(&mut cursor).unwrap();
                assert_eq!(input, result);

                //check that a too smal cursor results in an io error
                {
                    let buffer_len = buffer.len();
                    assert_matches!(SomeIpHeader::read(&mut Cursor::new(&buffer[..buffer_len-1])), Err(IoError(_)));
                }
            }
        }
    }

    proptest! {
        #[test]
        fn from_slice(length in SOMEIP_LEN_OFFSET_TO_PAYLOAD..1234,
                      ref input_base in someip_header_any(),
                      add in 0usize..15) {
            for message_type in MESSAGE_TYPE_VALUES {
                //calculate the length based on if there tp header is present
                let length = if input_base.tp_header.is_some() {
                    length + TP_HEADER_LENGTH as u32
                } else {
                    length
                };

                let input = {
                    let mut value = input_base.clone();
                    value.length = length;
                    value.message_type = message_type.clone();
                    value
                };

                let mut buffer = Vec::new();
                input.write_raw(&mut buffer).unwrap();

                //add some payload
                let expected_length = 
                    length as usize
                    + (SOMEIP_HEADER_LENGTH - SOMEIP_LEN_OFFSET_TO_PAYLOAD as usize);
                buffer.resize(expected_length + add, 0);

                //from_slice
                let slice = SomeIpHeaderSlice::from_slice(&buffer[..]).unwrap();
                assert_eq!(input.message_id, slice.message_id());
                assert_eq!(input.length, slice.length());
                assert_eq!(input.request_id, slice.request_id());
                assert_eq!(SOMEIP_PROTOCOL_VERSION, slice.protocol_version());
                assert_eq!(input.interface_version, slice.interface_version());
                assert_eq!(input.message_type, slice.message_type());
                assert_eq!(input.tp_header, slice.tp_header());
                assert_eq!(input.tp_header.is_some(), slice.is_tp());
                assert_eq!(input.return_code, slice.return_code());
                assert_eq!(&buffer[(
                    if input.tp_header.is_some() {
                        SOMEIP_HEADER_LENGTH + TP_HEADER_LENGTH
                    } else {
                        SOMEIP_HEADER_LENGTH
                    }
                )..expected_length], slice.payload());

                //internal slice checking
                assert_eq!(&buffer[..expected_length], slice.slice());
                assert_eq!(&buffer[..expected_length], slice.slice);

                //to_header
                assert_eq!(input, slice.to_header());

                //check that a too small slice triggers an error
                use ReadError::*;
                assert_matches!(SomeIpHeaderSlice::from_slice(&buffer[..expected_length-1]), Err(UnexpectedEndOfSlice(_)));
                assert_matches!(SomeIpHeaderSlice::from_slice(&buffer[..1]), Err(UnexpectedEndOfSlice(_)));
            }
        }
    }

    proptest! {
        #[test]
        fn unknown_message_type(length in SOMEIP_LEN_OFFSET_TO_PAYLOAD..1234,
                                ref input_base in someip_header_any(),
                                message_type in any::<u8>().prop_filter("message type must be unknown",
                               |v| !MESSAGE_TYPE_VALUES_RAW.iter().any(|&x| (v == &x || 
                                                                             (SOMEIP_HEADER_MESSAGE_TYPE_TP_FLAG | v) == x)))
            )
        {
            //add the tp header length in case the tp flag is set
            let length = if 0 != (SOMEIP_HEADER_MESSAGE_TYPE_TP_FLAG & message_type) {
                length + 4
            } else {
                length
            };

            let input = {
                let mut value = input_base.clone();
                value.length = length;
                value
            };

            //serialize to buffer
            let mut buffer = Vec::new();
            input.write_raw(&mut buffer).unwrap();

            //add some payload
            let expected_length = length as usize + (SOMEIP_HEADER_LENGTH - SOMEIP_LEN_OFFSET_TO_PAYLOAD as usize);
            buffer.resize(expected_length, 0);

            //insert the invalid message type
            buffer[14] = message_type;

            //check that deserialization triggers an error
            assert_matches!(SomeIpHeader::read(&mut Cursor::new(&buffer)), Err(UnknownMessageType(_)));
            assert_matches!(SomeIpHeaderSlice::from_slice(&buffer), Err(UnknownMessageType(_)));
        }
    }

    proptest! {
        #[test]
        #[should_panic]
        fn unknown_message_type_slice_getter(message_type in any::<u8>().prop_filter("message type must be unknown",
                               |v| !MESSAGE_TYPE_VALUES_RAW.iter().any(|&x| v == &x)))
        {
            //serialize to buffer
            let buffer: [u8;16] = {
                let mut value = [0;16];
                value[14] = message_type;
                value
            };

            //create the type
            let slice = SomeIpHeaderSlice {
                tp: false,
                slice: &buffer
            };

            //trigger the panic
            slice.message_type();
        }
    }

    #[test]
    fn read_unsupported_protocol_version() {
        let mut buffer = Vec::new();
        SomeIpHeader::default().write_raw(&mut buffer).unwrap();
        //set the protocol to an unsupported version
        buffer[4*3] = 0;
        let mut cursor = Cursor::new(&buffer);
        let result = SomeIpHeader::read(&mut cursor);
        assert_matches!(result, Err(ReadError::UnsupportedProtocolVersion(0)));
        assert_matches!(SomeIpHeaderSlice::from_slice(&buffer[..]), Err(ReadError::UnsupportedProtocolVersion(0)));
    }

    #[test]
    fn read_too_small_length_field() {
        //0
        {
            let mut buffer = Vec::new();
            SomeIpHeader::default().write_raw(&mut buffer).unwrap();
            //set the length to 0
            {
                buffer[4] = 0;
                buffer[5] = 0;
                buffer[6] = 0;
                buffer[7] = 0;
            }
            let mut cursor = Cursor::new(&buffer);
            let result = SomeIpHeader::read(&mut cursor);
            assert_matches!(result, Err(ReadError::LengthFieldTooSmall(0)));
            //check the from_slice method
            assert_matches!(SomeIpHeaderSlice::from_slice(&buffer[..]), Err(ReadError::LengthFieldTooSmall(0)));
        }
        //SOMEIP_LEN_OFFSET_TO_PAYLOAD - 1
        {
            let mut buffer = Vec::new();
            SomeIpHeader::default().write_raw(&mut buffer).unwrap();
            //set the length to SOMEIP_LEN_OFFSET_TO_PAYLOAD - 1
            const TOO_SMALL: u32 = SOMEIP_LEN_OFFSET_TO_PAYLOAD - 1;
            {
                let length_be = TOO_SMALL.to_be_bytes();
                buffer[4] = length_be[0];
                buffer[5] = length_be[1];
                buffer[6] = length_be[2];
                buffer[7] = length_be[3];
            }
            let mut cursor = Cursor::new(&buffer);
            let result = SomeIpHeader::read(&mut cursor);
            assert_matches!(result, Err(ReadError::LengthFieldTooSmall(TOO_SMALL)));
            assert_matches!(SomeIpHeaderSlice::from_slice(&buffer[..]), Err(ReadError::LengthFieldTooSmall(TOO_SMALL)));
        }
    }

    proptest! {
        #[test]
        fn service_id(packet in someip_header_with_payload_any(),
                      service_id in 0x0u16..std::u16::MAX)
        {
            let mut header = packet.0.clone();
            header.set_service_id(service_id);
            assert_eq!(service_id, header.service_id());

            //serialize and check the slice methods
            let mut buffer = Vec::new();
            header.write_raw(&mut buffer).unwrap();
            buffer.write(&packet.1[..]).unwrap();
            let slice = SomeIpHeaderSlice::from_slice(&buffer[..]).unwrap();

            assert_eq!(service_id, slice.service_id());
        }
    }

    proptest! {
        #[test]
        fn set_get_method_id(packet in someip_header_with_payload_any(),
                             method_id in 0u16..0x7fff)
        {
            let mut header = packet.0.clone();
            header.set_method_id(method_id);

            assert_eq!(method_id, header.event_or_method_id());
            assert_eq!(false, header.is_event());

            //serialize and check the slice methods
            let mut buffer = Vec::new();
            header.write_raw(&mut buffer).unwrap();
            buffer.write(&packet.1[..]).unwrap();
            let slice = SomeIpHeaderSlice::from_slice(&buffer[..]).unwrap();

            assert_eq!(false, slice.is_event());
            assert_eq!(method_id, slice.event_or_method_id());
        }
    }

    proptest! {
        #[test]
        fn set_get_event_id(packet in someip_header_with_payload_any(),
                            event_id in 0x8000u16..std::u16::MAX)
        {
            let mut header = packet.0.clone();
            header.set_event_id(event_id);

            let id_with_bit = event_id | 0x8000;

            assert_eq!(id_with_bit, header.event_or_method_id());
            assert_eq!(true, header.is_event());

            //serialize and check the slice methods
            let mut buffer = Vec::new();
            header.write_raw(&mut buffer).unwrap();
            buffer.write(&packet.1[..]).unwrap();
            let slice = SomeIpHeaderSlice::from_slice(&buffer[..]).unwrap();

            assert_eq!(true, slice.is_event());
            assert_eq!(id_with_bit, slice.event_or_method_id());
        }
    }

    proptest! {
        #[test]
        fn set_method_or_event_id(packet in someip_header_with_payload_any(),
                                  id in 0x0u16..std::u16::MAX)
        {
            let mut header = packet.0.clone();
            header.set_method_or_event_id(id);

            assert_eq!(id, header.event_or_method_id());
            assert_eq!(id > 0x8000, header.is_event());

            //serialize and check the slice methods
            let mut buffer = Vec::new();
            header.write_raw(&mut buffer).unwrap();
            buffer.write(&packet.1[..]).unwrap();
            let slice = SomeIpHeaderSlice::from_slice(&buffer[..]).unwrap();

            assert_eq!(id > 0x8000, slice.is_event());
            assert_eq!(id, slice.event_or_method_id());
        }
    }

    proptest! {
        #[test]
        fn is_someip_sd(packet in someip_header_with_payload_any())
        {
            const SD_MESSAGE_ID: u32 = 0xFFFF8100;

            let mut header = packet.0.clone();
            header.message_id = SD_MESSAGE_ID;

            assert_eq!(true, header.is_someip_sd());
            assert_eq!(packet.0.message_id == SD_MESSAGE_ID, packet.0.is_someip_sd());

            //serialize and check the slice methods
            //some ip sd packet
            {
                let mut buffer = Vec::new();
                header.write_raw(&mut buffer).unwrap();
                buffer.write(&packet.1[..]).unwrap();
                let slice = SomeIpHeaderSlice::from_slice(&buffer[..]).unwrap();

                assert_eq!(true, slice.is_someip_sd());
            }
            //random packet
            {
                let mut buffer = Vec::new();
                packet.0.write_raw(&mut buffer).unwrap();
                buffer.write(&packet.1[..]).unwrap();
                let slice = SomeIpHeaderSlice::from_slice(&buffer[..]).unwrap();

                assert_eq!(packet.0.message_id == SD_MESSAGE_ID, slice.is_someip_sd());
            }
        }
    }
}

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

    #[test]
    fn from_io_error() {
        assert_matches!(
            WriteError::from(std::io::Error::new(std::io::ErrorKind::Other, "oh no!")),
            WriteError::IoError(_)
        );
    }

    #[test]
    fn debug_write() {
        //ReadError
        {
            use ReadError::*;
            for value in [
                IoError(std::io::Error::new(std::io::ErrorKind::Other, "oh no!")),
                UnexpectedEndOfSlice(0),
                UnsupportedProtocolVersion(0),
                LengthFieldTooSmall(0),
                UnknownMessageType(0),
            ].iter() {
                println!("{:?}", value);
            }
        }
        //WriteError
        {
            use WriteError::*;
            for value in [
                IoError(std::io::Error::new(std::io::ErrorKind::Other, "oh no!")),
                UnexpectedEndOfSlice(0)
            ].iter() {
                println!("{:?}", value);
            }
        }
        //ValueError
        {
            use ValueError::*;
            for value in [
                LengthTooLarge(0),
                TpOffsetNotMultipleOf16(0)
            ].iter() {
                println!("{:?}", value);
            }
        }
        //SomeIpHeaderSlice
        {
            let buffer: [u8;SOMEIP_HEADER_LENGTH] = [0;SOMEIP_HEADER_LENGTH];
            println!("{:?}", SomeIpHeaderSlice{ tp:false, slice: &buffer[..]});
        }
    }
}

#[cfg(test)]
mod tests_tp_header {

    use super::*;
    use proptest_generators::*;
    use proptest::prelude::*;

    proptest! {
        #[test]
        fn new(more_segment in any::<bool>()) {
            let result = TpHeader::new(more_segment);

            assert_eq!(result.offset, 0);
            assert_eq!(result.offset(), 0);
            assert_eq!(result.more_segment, more_segment);
        }
    }

    proptest! {
        #[test]
        fn with_offset(
            offset in any::<u32>().prop_filter("must be multiple of 16", |v| 0 == v % 16),
            more_segment in any::<bool>()
        ) {
            let result = TpHeader::with_offset(offset, more_segment).unwrap();

            assert_eq!(result.offset, offset);
            assert_eq!(result.more_segment, more_segment);
        }
    }
    
    proptest! {
        #[test]
        fn with_offset_error(
            offset in any::<u32>().prop_filter("must not be multiple of 16", |v| 0 != v % 16),
            more_segment in any::<bool>()
        ) {
            let result = TpHeader::with_offset(offset, more_segment);
            assert_eq!(Err(ValueError::TpOffsetNotMultipleOf16(offset)), result);
        }
    }

    proptest! {
        #[test]
        fn set_offset(
            offset in any::<u32>().prop_filter("must be multiple of 16", |v| 0 == v % 16)
        ) {
            let mut header: TpHeader = Default::default();
            assert_eq!(Ok(()), header.set_offset(offset));
            assert_eq!(header.offset, offset);
        }
    }
    
    proptest! {
        #[test]
        fn set_offset_error(
            offset in any::<u32>().prop_filter("must not be multiple of 16", |v| 0 != v % 16)
        ) {
            let mut header: TpHeader = Default::default();
            assert_eq!(Err(ValueError::TpOffsetNotMultipleOf16(offset)), header.set_offset(offset));
            assert_eq!(0, header.offset);
        }
    }

    proptest! {
        #[test]
        fn write_and_read_to_slice(
            header in someip_tp_any()
        ) {
            //non error case
            {
                //serialize
                let mut buffer: [u8;TP_HEADER_LENGTH] = [0;TP_HEADER_LENGTH];
                header.write_to_slice(&mut buffer).unwrap();

                //deserialize
                let result = TpHeader::read_from_slice(&buffer).unwrap();
                assert_eq!(header, result);
            }

            //error
            {
                //write_to_slice
                let mut buffer: [u8;TP_HEADER_LENGTH] = [0;TP_HEADER_LENGTH];
                assert_matches!(header.write_to_slice(&mut buffer[..TP_HEADER_LENGTH-1]), Err(WriteError::UnexpectedEndOfSlice(_)));

                //read_from_slice
                assert_matches!(TpHeader::read_from_slice(&buffer[..TP_HEADER_LENGTH-1]), Err(ReadError::UnexpectedEndOfSlice(_)));
            }
        }
    }
}

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

    proptest! {
        #[test]
        fn iterator(expected in proptest::collection::vec(someip_header_with_payload_any(), 0..5))
        {
            //serialize
            let mut buffer = Vec::new();
            for (message, payload) in expected.iter() {
                message.write_raw(&mut buffer).unwrap();
                buffer.write(&payload[..]).unwrap();
            }

            //read message with iterator
            let actual = SliceIterator::new(&buffer[..]).fold(
                Vec::with_capacity(expected.len()), 
                |mut acc, x| {
                    let x_unwraped = x.unwrap();
                    acc.push((
                        x_unwraped.to_header(),
                        {
                            let mut vec = Vec::with_capacity(x_unwraped.payload().len());
                            vec.extend_from_slice(x_unwraped.payload());
                            vec
                        })
                    );
                    acc
                });
            assert_eq!(expected, actual);
        }

    }

    proptest! {
        #[test]
        fn iterator_error(packet in someip_header_with_payload_any()) {
            //serialize
            let mut buffer = Vec::new();
            packet.0.write_raw(&mut buffer).unwrap();
            buffer.write(&packet.1[..]).unwrap();

            //generate iterator
            let len = buffer.len();
            let mut iterator = SliceIterator::new(&buffer[..len-1]);

            //check that an error is generated
            assert_matches!(iterator.next(), Some(Err(ReadError::UnexpectedEndOfSlice(_))));
            assert_matches!(iterator.next(), None);
            assert_matches!(iterator.next(), None);
        }
    }
}