Skip to content

Commit

Permalink
Merge pull request #562 from Felix-El/no_std
Browse files Browse the repository at this point in the history
enable #[no_std] use by providing std feature
  • Loading branch information
mrmonday committed May 12, 2022
2 parents 44f17c8 + a1ba846 commit 9e06711
Show file tree
Hide file tree
Showing 31 changed files with 197 additions and 63 deletions.
40 changes: 35 additions & 5 deletions Cargo.toml
Expand Up @@ -18,16 +18,46 @@ netmap = ["pnet_datalink/netmap_sys", "pnet_datalink/netmap"]
pcap = ["pnet_datalink/pcap"]
appveyor = []
travis = []
serde = ["pnet_base/serde", "pnet_datalink/serde"]
serde = ["pnet_base/serde", "pnet_datalink?/serde"]
std = ["pnet_base/std", "pnet_sys", "pnet_datalink", "pnet_transport", "ipnetwork"]
default = ["std"]

[dependencies]
ipnetwork = "0.19.0"
ipnetwork = { version = "0.19.0", optional = true }

pnet_base = { path = "pnet_base", version = "0.29.0" }
pnet_sys = { path = "pnet_sys", version = "0.29.0" }
pnet_datalink = { path = "pnet_datalink", version = "0.29.0" }
pnet_transport = { path = "pnet_transport", version = "0.29.0" }
pnet_sys = { path = "pnet_sys", version = "0.29.0", optional = true }
pnet_datalink = { path = "pnet_datalink", version = "0.29.0", optional = true }
pnet_transport = { path = "pnet_transport", version = "0.29.0", optional = true }
pnet_packet = { path = "pnet_packet", version = "0.29.0" }

[dev-dependencies]
time = "0.3.5"

[[example]]
name = "arp_packet"
required-features = ["std"]

[[example]]
name = "fanout"
required-features = ["std"]

[[example]]
name = "list_interfaces"
required-features = ["std"]

[[example]]
name = "packetdump"
required-features = ["std"]

[[example]]
name = "transport_echo_server"
required-features = ["std"]

[[bench]]
name = "rs_sender"
required-features = ["std"]

[[bench]]
name = "rs_receiver"
required-features = ["std"]
5 changes: 5 additions & 0 deletions pnet_base/Cargo.toml
Expand Up @@ -12,11 +12,16 @@ categories = ["network-programming"]
edition = "2021"

[dependencies]
no-std-net = { version = "0.6.0", default-features = false }
serde = { version = "1.0.126", optional = true, default-features = false }

[dev-dependencies]
serde_test = "1.0.126"

[features]
std = ["no-std-net/std"]
default = ["std"]

[package.metadata.docs.rs]
# Enable the serde feature when generating docs on docs.rs, so the traits are visible
features = ["serde"]
4 changes: 4 additions & 0 deletions pnet_base/src/lib.rs
Expand Up @@ -6,8 +6,12 @@
// option. This file may not be copied, modified, or distributed
// except according to those terms.

#![cfg_attr(all(not(test), not(feature = "std")), no_std)]

#[cfg(feature = "serde")]
extern crate serde;

mod macaddr;
pub use crate::macaddr::*;

pub use no_std_net as core_net;
11 changes: 7 additions & 4 deletions pnet_base/src/macaddr.rs
Expand Up @@ -6,9 +6,11 @@
// option. This file may not be copied, modified, or distributed
// except according to those terms.

#[cfg(feature = "std")]
use std::error::Error;
use std::fmt;
use std::str::FromStr;

use core::fmt;
use core::str::FromStr;

#[cfg(feature = "serde")]
use serde::{de, Deserialize, Deserializer, Serialize, Serializer};
Expand Down Expand Up @@ -114,7 +116,7 @@ impl Serialize for MacAddr {
/// prefers.
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
if serializer.is_human_readable() {
serializer.serialize_str(&format!("{}", self))
serializer.collect_str(self)
} else {
serializer.serialize_bytes(&[self.0, self.1, self.2, self.3, self.4, self.5])
}
Expand All @@ -134,7 +136,7 @@ impl<'de> Deserialize<'de> for MacAddr {
type Value = MacAddr;

fn visit_str<E: de::Error>(self, value: &str) -> Result<MacAddr, E> {
value.parse().map_err(|err| E::custom(&format!("{}", err)))
value.parse().map_err(|err| E::custom(err))
}

fn visit_bytes<E: de::Error>(self, v: &[u8]) -> Result<MacAddr, E> {
Expand Down Expand Up @@ -179,6 +181,7 @@ pub enum ParseMacAddrErr {
InvalidComponent,
}

#[cfg(feature = "std")]
impl Error for ParseMacAddrErr {}

impl ParseMacAddrErr {
Expand Down
4 changes: 3 additions & 1 deletion pnet_datalink/Cargo.toml
Expand Up @@ -13,11 +13,13 @@ edition = "2021"

[features]
netmap = []
std = ["pnet_base/std"]
default = ["std"]

[dependencies]
libc = "0.2.97"
ipnetwork = "0.18.0"
pnet_base = { path = "../pnet_base", version = "0.29.0" }
pnet_base = { path = "../pnet_base", version = "0.29.0", default-features = false }
pnet_sys = { path = "../pnet_sys", version = "0.29.0" }

pcap = { version = "0.8.1", optional = true }
Expand Down
20 changes: 10 additions & 10 deletions pnet_macros/src/decorator.rs
Expand Up @@ -15,7 +15,7 @@ use crate::util::{
use proc_macro2::{Group, Span};
use quote::{quote, ToTokens};
use regex::Regex;
use std::iter::FromIterator;
use core::iter::FromIterator;
use syn::{spanned::Spanned, Error};

#[derive(Debug, PartialEq, Eq)]
Expand Down Expand Up @@ -721,7 +721,7 @@ fn generate_packet_trait_impls(
if !payload_bounds.upper.is_empty() {
pre = pre
+ &format!(
"let end = ::std::cmp::min({}, _self.packet.len());",
"let end = ::core::cmp::min({}, _self.packet.len());",
payload_bounds.upper
)[..];
end = "end".to_owned();
Expand Down Expand Up @@ -778,7 +778,7 @@ fn generate_iterables(packet: &Packet) -> Result<proc_macro2::TokenStream, Error
fn next(&mut self) -> Option<{name}Packet<'a>> {{
use pnet_macros_support::packet::PacketSize;
use std::cmp::min;
use core::cmp::min;
if self.buf.len() > 0 {{
if let Some(ret) = {name}Packet::new(self.buf) {{
let start = min(ret.packet_size(), self.buf.len());
Expand Down Expand Up @@ -853,9 +853,9 @@ fn generate_debug_impls(packet: &Packet) -> Result<proc_macro2::TokenStream, Err
.map(|packet| {
let s = format!(
"
impl<'p> ::std::fmt::Debug for {packet}<'p> {{
impl<'p> ::core::fmt::Debug for {packet}<'p> {{
#[cfg_attr(feature = \"clippy\", allow(used_underscore_binding))]
fn fmt(&self, fmt: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {{
fn fmt(&self, fmt: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {{
let _self = self;
write!(fmt,
\"{packet} {{{{ {field_fmt_str} }}}}\"
Expand Down Expand Up @@ -1012,7 +1012,7 @@ fn handle_vec_primitive(
#[allow(trivial_numeric_casts, unused_parens, unused_braces)]
#[cfg_attr(feature = \"clippy\", allow(used_underscore_binding))]
pub fn get_{name}(&self) -> Vec<{inner_ty_str}> {{
use std::cmp::min;
use core::cmp::min;
let _self = self;
let current_offset = {co};
let pkt_len = self.packet.len();
Expand Down Expand Up @@ -1126,7 +1126,7 @@ fn handle_vector_field(
#[allow(trivial_numeric_casts)]
#[cfg_attr(feature = \"clippy\", allow(used_underscore_binding))]
pub fn get_{name}_raw(&self) -> &[u8] {{
use std::cmp::min;
use core::cmp::min;
let _self = self;
let current_offset = {co};
let end = min(current_offset + {packet_length}, _self.packet.len());
Expand All @@ -1144,7 +1144,7 @@ fn handle_vector_field(
#[allow(trivial_numeric_casts)]
#[cfg_attr(feature = \"clippy\", allow(used_underscore_binding))]
pub fn get_{name}_raw_mut(&mut self) -> &mut [u8] {{
use std::cmp::min;
use core::cmp::min;
let _self = self;
let current_offset = {co};
let end = min(current_offset + {packet_length}, _self.packet.len());
Expand Down Expand Up @@ -1301,7 +1301,7 @@ fn handle_vector_field(
#[cfg_attr(feature = \"clippy\", allow(used_underscore_binding))]
pub fn get_{name}(&self) -> Vec<{inner_ty_str}> {{
use pnet_macros_support::packet::FromPacket;
use std::cmp::min;
use core::cmp::min;
let _self = self;
let current_offset = {co};
let end = min(current_offset + {packet_length}, _self.packet.len());
Expand All @@ -1317,7 +1317,7 @@ fn handle_vector_field(
#[allow(trivial_numeric_casts)]
#[cfg_attr(feature = \"clippy\", allow(used_underscore_binding))]
pub fn get_{name}_iter(&self) -> {inner_ty_str}Iterable {{
use std::cmp::min;
use core::cmp::min;
let _self = self;
let current_offset = {co};
let end = min(current_offset + {packet_length}, _self.packet.len());
Expand Down
4 changes: 2 additions & 2 deletions pnet_macros/src/lib.rs
Expand Up @@ -73,10 +73,10 @@
//! structures. These include:
//! - `pnet::packet::Packet` (`ExamplePacket` and `MutableExamplePacket`)
//! - `pnet::packet::MutablePacket` (`MutableExamplePacket` only)
//! - `std::fmt::Debug` (`ExamplePacket` and `MutableExamplePacket`)
//! - `core::fmt::Debug` (`ExamplePacket` and `MutableExamplePacket`)
//! - `pnet::packet::FromPacket` (`ExamplePacket` and `MutableExamplePacket`)
//! - `pnet::packet::PacketSize` (`ExamplePacket` and `MutableExamplePacket`)
//! * An `ExampleIterator` structure, which implements `std::iter::Iterator`, to allow iterating
//! * An `ExampleIterator` structure, which implements `core::iter::Iterator`, to allow iterating
//! over vectors of `ExamplePacket` contained within another packet. Used internally.
//!
//! ## Attributes
Expand Down
2 changes: 1 addition & 1 deletion pnet_macros/src/util.rs
Expand Up @@ -9,7 +9,7 @@

//! Utility functions for bit manipulation operations

use std::fmt;
use core::fmt;

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Endianness {
Expand Down
4 changes: 4 additions & 0 deletions pnet_macros_support/Cargo.toml
Expand Up @@ -13,3 +13,7 @@ edition = "2021"

[dependencies]
pnet_base = { path = "../pnet_base", version = "0.29.0" }

[features]
std = ["pnet_base/std"]
default = ["std"]
1 change: 1 addition & 0 deletions pnet_macros_support/src/lib.rs
Expand Up @@ -11,6 +11,7 @@
//! This exists to remove the need for the plugin_as_library feature, and allow for static linking.

#![deny(missing_docs)]
#![no_std]

extern crate pnet_base;

Expand Down
15 changes: 9 additions & 6 deletions pnet_macros_support/src/packet.rs
Expand Up @@ -8,8 +8,11 @@

//! Packet helpers for `pnet_macros`.

extern crate alloc;
use alloc::vec;

use core::ops::{Deref, DerefMut, Index, IndexMut, Range, RangeFrom, RangeFull, RangeTo};
use pnet_base;
use std::ops::{Deref, DerefMut, Index, IndexMut, Range, RangeFrom, RangeFull, RangeTo};

/// Represents a generic network packet.
pub trait Packet {
Expand All @@ -30,7 +33,7 @@ pub trait MutablePacket: Packet {

/// Initialize this packet by cloning another.
fn clone_from<T: Packet>(&mut self, other: &T) {
use std::ptr;
use core::ptr;

assert!(self.packet().len() >= other.packet().len());
unsafe {
Expand Down Expand Up @@ -87,7 +90,7 @@ macro_rules! impl_index_mut {
#[derive(PartialEq)]
pub enum PacketData<'p> {
/// A packet owns its contents.
Owned(Vec<u8>),
Owned(vec::Vec<u8>),
/// A packet borrows its contents.
Borrowed(&'p [u8]),
}
Expand Down Expand Up @@ -125,7 +128,7 @@ impl_index!(PacketData, RangeFull, [u8]);
#[derive(PartialEq)]
pub enum MutPacketData<'p> {
/// Owned mutable packet data.
Owned(Vec<u8>),
Owned(vec::Vec<u8>),
/// Borrowed mutable packet data.
Borrowed(&'p mut [u8]),
}
Expand Down Expand Up @@ -194,7 +197,7 @@ impl PrimitiveValues for pnet_base::MacAddr {
}
}

impl PrimitiveValues for ::std::net::Ipv4Addr {
impl PrimitiveValues for ::pnet_base::core_net::Ipv4Addr {
type T = (u8, u8, u8, u8);
#[inline]
fn to_primitive_values(&self) -> (u8, u8, u8, u8) {
Expand All @@ -204,7 +207,7 @@ impl PrimitiveValues for ::std::net::Ipv4Addr {
}
}

impl PrimitiveValues for ::std::net::Ipv6Addr {
impl PrimitiveValues for ::pnet_base::core_net::Ipv6Addr {
type T = (u16, u16, u16, u16, u16, u16, u16, u16);
#[inline]
fn to_primitive_values(&self) -> (u16, u16, u16, u16, u16, u16, u16, u16) {
Expand Down
6 changes: 5 additions & 1 deletion pnet_packet/Cargo.toml
Expand Up @@ -12,10 +12,14 @@ categories = ["network-programming", "parser-implementations"]
edition = "2018"

[dependencies]
pnet_base = { path = "../pnet_base", version = "0.29.0" }
pnet_base = { path = "../pnet_base", version = "0.29.0", default-features = false }
pnet_macros_support = { path = "../pnet_macros_support", version = "0.29.0" }
pnet_macros = { path = "../pnet_macros", version = "0.29.0" }

[features]
std = ["pnet_base/std"]
default = ["std"]

[dev-dependencies]
hex = "0.4.3"
criterion = {version = "0.3.5", features = ["html_reports"]} #added HTML feature becuase of the annoying warnings when running the tests
Expand Down
4 changes: 3 additions & 1 deletion pnet_packet/src/arp.rs
Expand Up @@ -11,7 +11,9 @@
use crate::PrimitiveValues;
use crate::ethernet::EtherType;

use std::net::Ipv4Addr;
use alloc::vec::Vec;

use pnet_base::core_net::Ipv4Addr;
use pnet_base::MacAddr;
use pnet_macros::packet;

Expand Down
6 changes: 5 additions & 1 deletion pnet_packet/src/ethernet.rs
Expand Up @@ -10,7 +10,9 @@

use crate::PrimitiveValues;

use std::fmt;
use alloc::vec::Vec;
use core::fmt;

use pnet_base::MacAddr;
use pnet_macros::packet;

Expand Down Expand Up @@ -161,8 +163,10 @@ impl fmt::Display for EtherType {
}
}

#[cfg(feature = "std")]
#[test]
fn ether_type_to_str() {
use std::format;
let ipv4 = EtherType(0x0800);
assert_eq!(format!("{}", ipv4), "Ipv4");
let arp = EtherType(0x0806);
Expand Down
2 changes: 2 additions & 0 deletions pnet_packet/src/gre.rs
Expand Up @@ -12,6 +12,8 @@
#[cfg(test)]
use crate::Packet;

use alloc::vec::Vec;

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

Expand Down

0 comments on commit 9e06711

Please sign in to comment.