Skip to main content

network_types/
lib.rs

1#![doc = include_str!("../README.md")]
2#![no_std]
3#![expect(unsafe_op_in_unsafe_fn)]
4
5pub mod arp;
6pub mod bitfield;
7pub mod ecn_codepoint;
8pub mod eth;
9pub mod geneve;
10pub mod icmp;
11pub mod igmp;
12pub mod ip;
13pub mod llc;
14pub mod mac;
15pub mod mpls;
16pub mod sctp;
17pub mod tcp;
18pub mod udp;
19pub mod vlan;
20pub mod vxlan;
21
22/// Gets the value of the given big-endian field using pointer arithmetic, raw
23/// pointer conversion and, if the target is little-endian, the `swap_bytes`
24/// method. That performs better than `from_be_bytes`.
25///
26/// # Safety
27///
28/// Caller needs to ensure that the provided field name is in bounds of the struct.
29#[cfg(target_endian = "big")]
30#[macro_export]
31macro_rules! getter_be {
32    ($self:expr, $field:ident, $ty:ty) => {
33        core::ptr::read_unaligned(core::ptr::addr_of!($self.$field).cast::<$ty>())
34    };
35}
36#[cfg(target_endian = "little")]
37#[macro_export]
38macro_rules! getter_be {
39    ($self:expr, $field:ident, $ty:ty) => {
40        core::ptr::read_unaligned(core::ptr::addr_of!($self.$field).cast::<$ty>()).swap_bytes()
41    };
42}
43
44/// Sets the value of the given big-endian field using pointer arithmetic, raw
45/// pointer conversion and, if the target is little-endian, the `swap_bytes`
46/// method. That performs better than `to_be_bytes`.
47///
48/// # Safety
49///
50/// Caller needs to ensure that the provided field name is in bounds of the struct.
51#[cfg(target_endian = "big")]
52#[macro_export]
53macro_rules! setter_be {
54    ($self:expr, $field:ident, $val:expr) => {
55        // SAFETY: Pointer arithmetics in bounds of the given struct.
56        $self.$field = *core::ptr::from_ref(&$val).cast()
57    };
58}
59#[cfg(target_endian = "little")]
60#[macro_export]
61macro_rules! setter_be {
62    ($self:expr, $field:ident, $val:expr) => {
63        // SAFETY: Pointer arithmetics in bounds of the given struct.
64        $self.$field = *core::ptr::from_ref(&$val.swap_bytes()).cast()
65    };
66}