1 use crate::*; 2 3 /// Payload together with an identifier the type of content. 4 #[derive(Debug, Clone, Eq, PartialEq, Hash, PartialOrd, Ord)] 5 pub enum PayloadSlice<'a> { 6 /// Payload with it's type identified by an ether type number 7 /// (e.g. after an ethernet II or vlan header). 8 Ether(EtherPayloadSlice<'a>), 9 /// Payload with is's type identified by an ip number (e.g. 10 /// after an IP header or after an) 11 Ip(IpPayloadSlice<'a>), 12 /// UDP payload. 13 Udp(&'a [u8]), 14 /// TCP payload. 15 Tcp(&'a [u8]), 16 /// Payload part of an ICMP V4 message. Check [`crate::Icmpv4Type`] 17 /// for a description what will be part of the payload. 18 Icmpv4(&'a [u8]), 19 /// Payload part of an ICMP V4 message. Check [`crate::Icmpv6Type`] 20 /// for a description what will be part of the payload. 21 Icmpv6(&'a [u8]), 22 } 23 24 impl<'a> PayloadSlice<'a> { slice(&self) -> &'a [u8]25 pub fn slice(&self) -> &'a [u8] { 26 match self { 27 PayloadSlice::Ether(s) => s.payload, 28 PayloadSlice::Ip(s) => s.payload, 29 PayloadSlice::Udp(s) => s, 30 PayloadSlice::Tcp(s) => s, 31 PayloadSlice::Icmpv4(s) => s, 32 PayloadSlice::Icmpv6(s) => s, 33 } 34 } 35 } 36 37 #[cfg(test)] 38 mod test { 39 use super::*; 40 use alloc::format; 41 42 #[test] debug()43 fn debug() { 44 assert_eq!( 45 format!("Udp({:?})", &[0u8; 0]), 46 format!("{:?}", PayloadSlice::Udp(&[])) 47 ); 48 } 49 50 #[test] clone_eq_hash_ord()51 fn clone_eq_hash_ord() { 52 let s = PayloadSlice::Udp(&[]); 53 assert_eq!(s.clone(), s); 54 55 use std::collections::hash_map::DefaultHasher; 56 use std::hash::{Hash, Hasher}; 57 58 let a_hash = { 59 let mut hasher = DefaultHasher::new(); 60 s.hash(&mut hasher); 61 hasher.finish() 62 }; 63 let b_hash = { 64 let mut hasher = DefaultHasher::new(); 65 s.clone().hash(&mut hasher); 66 hasher.finish() 67 }; 68 assert_eq!(a_hash, b_hash); 69 70 use std::cmp::Ordering; 71 assert_eq!(s.clone().cmp(&s), Ordering::Equal); 72 assert_eq!(s.clone().partial_cmp(&s), Some(Ordering::Equal)); 73 } 74 75 #[test] slice()76 fn slice() { 77 let payload = [1, 2, 3, 4]; 78 79 use PayloadSlice::*; 80 assert_eq!( 81 Ether(EtherPayloadSlice { 82 ether_type: EtherType::IPV4, 83 payload: &payload 84 }) 85 .slice(), 86 &payload 87 ); 88 assert_eq!( 89 Ip(IpPayloadSlice { 90 ip_number: IpNumber::IPV4, 91 fragmented: false, 92 len_source: LenSource::Slice, 93 payload: &payload 94 }) 95 .slice(), 96 &payload 97 ); 98 assert_eq!(Udp(&payload).slice(), &payload); 99 assert_eq!(Tcp(&payload).slice(), &payload); 100 assert_eq!(Icmpv4(&payload).slice(), &payload); 101 assert_eq!(Icmpv6(&payload).slice(), &payload); 102 } 103 } 104