alexforster / pdu

Small, fast, and correct L2/L3/L4 packet parser.
https://crates.io/crates/pdu
Apache License 2.0
58 stars 9 forks source link

method self lifetimes should be &self instead of &'a self #8

Open tsheinen opened 1 year ago

tsheinen commented 1 year ago

pub fn buffer(&self) -> &'a [u8] instead of pub fn buffer(&'a self) -> &'a [u8]. &'a is the lifetime of the underlying buffer, not the Pdu struct. Borrowing self as &'a self does something funky (i do not understand lifetimes well enough to say exactly what) with the &'a lifetime and limits the lifetime of the return value to the lifetime of the struct. For example

fn extract_tcp<'a>(packet: &'a[u8]) -> Option<&'a[u8]> {
    const IP_PROTOCOL_TCP: u8 = 6;
    Some(match Ip::new(packet).ok()? {
        Ip::Ipv4(v4) if v4.protocol() == IP_PROTOCOL_TCP => {
            &v4.buffer()[v4.computed_ihl()..]
        },
        Ip::Ipv6(v6) if v6.computed_protocol() == IP_PROTOCOL_TCP => {
            &v6.buffer()[v6.computed_ihl()..]
        },
        _ => return None,
    })
}

gives the error "error[E0515]: cannot return value referencing local variable v4" with pdu 1.4.2, but it compiles when pointed at a fork (https://github.com/tsheinen/pdu) where i just find-and-replaced every &'a self with &self.