Crate const_addrs

source ·
Expand description

A set of macros for creating networking types from a string literal.

use std::net::Ipv4Addr;
use const_addrs::ip4;

let a = ip4!("192.168.1.1");
let b = Ipv4Addr::new(192,168,1,1);
assert_eq!(a, b);

Turning invalid strings into compile-time errors:

error: invalid IPv4 address syntax
  --> bad.rs:10:18
   |
10 |     let a = ip4!("192.1681.1");
   |                  ^^^^^^^^^^^^

These macros will parse the string passed to them using its type’s FromStr implementation. See the documentation for each type for formatting details. The macro generated code will use the const constructor(s) for stdlib and macaddr types, adding no runtime overhead.

For example:

let val = sock!("192.168.1.1:500");

expands to:

let val = ::std::net::SocketAddr::V4(::std::net::SocketAddrV4::new(
    ::std::net::Ipv4Addr::new(192u8, 168u8, 1u8, 1u8),
    500u16,
));

ipnetwork types do not provide a const constructor and return a Result. These are unwrapped in the generated code, since they are validated when the macro runs.

For example:

let val = net!("192.168.1.1/24");

expands to:

let val = ipnetwork::IpNetwork::V4(
    ipnetwork::Ipv4Network::new(::std::net::Ipv4Addr::new(192u8, 168u8, 1u8, 1u8), 24u8)
        .unwrap(),
);

§Features

The crate provides a set of optional features that can be enabled in your cargo.toml file.

  • default — By default, only generate stdlib types
  • ipnet — enables generation of ipnetwork types
  • mac — enables generation of macaddr types

Macros§