sharksforarms / deku

Declarative binary reading and writing: bit-level, symmetric, serialization/deserialization
Apache License 2.0
1.14k stars 55 forks source link

`from_bytes` not working for passing a ctx #492

Closed soumyasen1809 closed 1 month ago

soumyasen1809 commented 1 month ago

I am playing with Deku and having an issue with a small toy code.

use deku::{DekuRead, DekuWrite};
use pnet::datalink::Channel::Ethernet;
use pnet::datalink::{self};
use pnet::packet::ethernet::EthernetPacket;
use pnet::packet::Packet;

#[derive(Debug, DekuRead, DekuWrite)]
#[deku(endian = "big", ctx = "data_len: u8")]
pub struct EthernetFrame {
    #[deku(count = "6")]
    dst_mac: Vec<u8>,
    #[deku(count = "6")]
    src_mac: Vec<u8>,
    #[deku(count = "2")]
    ether_type: Vec<u8>,
    #[deku(count = "data_len")]
    payload: Vec<u8>,
}

pub fn deserialization(packet: &[u8]) {
    let data_length: u8 = 10;
    match EthernetFrame::from_bytes((&packet, 0), data_length) {
        Ok((_, frame_value)) => {
            println!("packet de-serialized: {:?}", frame_value);
        }
        Err(e) => eprintln!("Error in deserialization: {:?}", e),
    }
}

fn main() {
    let interfaces = datalink::interfaces();
    let interface = interfaces.into_iter().next().unwrap();

    let mut rx = match datalink::channel(&interface, Default::default()) {
        Ok(Ethernet(_, rx)) => rx,
        Ok(_) => panic!("Unhandled channel type"),
        Err(e) => panic!(
            "An error occurred when creating the datalink channel: {}",
            e
        ),
    };

    for _ in 1..5 {
        match rx.next() {
            Ok(packet) => {
                deserialization(EthernetPacket::new(packet).unwrap().packet());
            }
            Err(e) => eprintln!("Error occurred: {:?}", e),
        }
    }
}

I get the error: no function or associated item namedfrom_bytesfound for structEthernetFramein the current scope

Could you please help why do I get the error? I want to pass the data_len as an extra information and so I am using ctx. This is just a toy example which I am using to learn the crate.