Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

pnet_macros: fix num_bytes calculation #547

Merged
merged 3 commits into from Apr 8, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
26 changes: 20 additions & 6 deletions pnet_macros/src/util.rs
Expand Up @@ -382,12 +382,10 @@ pub fn operations(offset: usize, size: usize) -> Option<Vec<GetOperation>> {
return None;
}

let num_full_bytes = size / 8;
let num_bytes = if offset > 0 || size % 8 != 0 {
num_full_bytes + 1
} else {
num_full_bytes
};

let start = offset / 8;
let end = (offset+size-1) / 8;
let num_bytes = (end - start) + 1;

let mut current_offset = offset;
let mut num_bits_remaining = size;
Expand Down Expand Up @@ -627,6 +625,22 @@ fn operations_test() {
}
]
);

assert_eq!(
operations(6, 6).unwrap(),
vec![
Op {
mask: 3,
shiftl: 4,
shiftr: 0,
},
Op {
mask: 240,
shiftl: 0,
shiftr: 4,
}
]
);
}

/// Mask `bits` bits of a byte. eg. mask_high_bits(2) == 0b00000011
Expand Down
40 changes: 40 additions & 0 deletions pnet_macros/tests/run-pass/weird_field_pos.rs
@@ -0,0 +1,40 @@
// Copyright (c) 2022 Yureka <yuka@yuka.dev>
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

extern crate pnet_macros;
extern crate pnet_macros_support;
use pnet_macros::packet;
use pnet_macros_support::types::*;

#[packet]
pub struct Test {
banana: u2,
apple: u4,
potato: u6,
the_rest: u20be,
#[payload]
payload: Vec<u8>,
}

fn main() {
let test = Test {
banana: 0b10,
apple: 0b1010,
potato: 0b101010,
the_rest: 0b10101010101010101010,
payload: vec![],
};

let mut buf = vec![0; TestPacket::packet_size(&test)];
let mut packet = MutableTestPacket::new(&mut buf).unwrap();
packet.populate(&test);
assert_eq!(packet.get_banana(), test.banana);
assert_eq!(packet.get_apple(), test.apple);
assert_eq!(packet.get_potato(), test.potato);
assert_eq!(packet.get_the_rest(), test.the_rest);
}