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

Make wire/ipv4 functions const where easy. #420

Merged
merged 2 commits into from Feb 15, 2021
Merged

Make wire/ipv4 functions const where easy. #420

merged 2 commits into from Feb 15, 2021

Conversation

stabler
Copy link
Contributor

@stabler stabler commented Feb 12, 2021

This is a small PR that makes functions in src/wire/ipv4.rs const. Specifically targeting Address::new and Cidr::new, but also updating other functions where there is no impact to the function body.

const fn was stabilized in 1.31, so I believe this is zero impact to existing code (given current minimum required rust version of 1.40)

The motivation for this change is to simplify static initialization on embedded platforms. E.g. initialize an arbitrary IP address, or empty storage for a CIDR.

Let me know if this is misaligned with project goals/direction! It's useful to my projects, but I'm very open to feedback!

@stabler stabler changed the title Make wire/ipv4 functions const where possible. Make wire/ipv4 functions const where easy. Feb 12, 2021
pub const fn new(address: Address, prefix_len: u8) -> Cidr {
// Replace with const panic (or assert) when stabilized
// see: https://github.com/rust-lang/rust/issues/51999
["Prefix length should be <= 32"][(prefix_len > 32) as usize];
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is a bit sketchy--is this a generally accepted workaround?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

From what I've read, yes. There's a reference to this technique in this comment on the issue ticket referenced (in relation to the RustCrypto crate).

It's also the method used by 3rd party crates static_assertions and const_fn_assert. I considered bringing one of them in- static_assertions seems to be more popular- but for such a simple macro it didn't seem worth the overhead. Those crates use the simplified [()][bool_expr as usize] form, but I've seen people use ["debug message"][bool_expr as usize] to provide better feedback if the assert is triggered.

@whitequark whitequark merged commit 083792c into smoltcp-rs:master Feb 15, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Development

Successfully merging this pull request may close these issues.

None yet

2 participants