浏览代码

Add EthernetRepr type

Andrew Cann 7 年之前
父节点
当前提交
17e8001ade
共有 2 个文件被更改,包括 33 次插入1 次删除
  1. 31 0
      src/wire/ethernet.rs
  2. 2 1
      src/wire/mod.rs

+ 31 - 0
src/wire/ethernet.rs

@@ -241,6 +241,37 @@ impl<T: AsRef<[u8]>> PrettyPrint for Frame<T> {
     }
 }
 
+/// A high-level representation of an Internet Protocol version 4 packet header.
+#[derive(Debug, PartialEq, Eq, Clone, Copy)]
+pub struct Repr {
+    pub src_addr:    Address,
+    pub dst_addr:    Address,
+    pub ethertype:   EtherType,
+}
+
+impl Repr {
+    /// Parse an Ethernet II frame and return a high-level representation.
+    pub fn parse<T: AsRef<[u8]> + ?Sized>(frame: &Frame<&T>) -> Result<Repr> {
+        frame.check_len()?;
+        Ok(Repr {
+            src_addr: frame.src_addr(),
+            dst_addr: frame.dst_addr(),
+            ethertype: frame.ethertype(),
+        })
+    }
+
+    /// Return the length of a header that will be emitted from this high-level representation.
+    pub fn buffer_len(&self) -> usize {
+        field::PAYLOAD.start
+    }
+
+    /// Emit a high-level representation into an Ethernet II frame.
+    pub fn emit<T: AsRef<[u8]> + AsMut<[u8]>>(&self, frame: &mut Frame<T>) {
+        frame.set_src_addr(self.src_addr);
+        frame.set_dst_addr(self.dst_addr);
+        frame.set_ethertype(self.ethertype);
+    }
+}
 
 #[cfg(test)]
 mod test {

+ 2 - 1
src/wire/mod.rs

@@ -104,7 +104,8 @@ pub use self::pretty_print::PrettyPrinter;
 
 pub use self::ethernet::{EtherType as EthernetProtocol,
                          Address as EthernetAddress,
-                         Frame as EthernetFrame};
+                         Frame as EthernetFrame,
+                         Repr as EthernetRepr};
 
 #[cfg(feature = "proto-ipv4")]
 pub use self::arp::{Hardware as ArpHardware,