Skip to content

Instantly share code, notes, and snippets.

@o0Ignition0o
Created July 31, 2018 12:14
Show Gist options
  • Save o0Ignition0o/f382c539ecea2d4690802618ca83095c to your computer and use it in GitHub Desktop.
Save o0Ignition0o/f382c539ecea2d4690802618ca83095c to your computer and use it in GitHub Desktop.
is_valid_ipv4
use std::slice;
pub fn is_valid_ipv4_addr<'a>(addr: &'a [u8]) -> bool {
let mut current_octet: Option<u8> = None;
let mut dots: u8 = 0;
for c in addr {
let c = *c as char;
match c {
'.' => {
match current_octet {
None => {
// starting an octet with a . is not allowed
return false;
}
Some(_) => {
dots = dots + 1;
current_octet = None;
}
}
}
maybe_digit => {
match current_octet {
None => {
if let Some(digit) = maybe_digit.to_digit(10) {
current_octet = Some(digit as u8);
} else {
// The caracter is not a digit
return false;
};
}
Some(octet) => {
if let Some(digit) = maybe_digit.to_digit(10) {
let digit = digit as u8;
if let Some(times_ten) = octet.checked_mul(10) {
if let Some(plus_digit) = times_ten.checked_add(digit) {
current_octet = Some(plus_digit);
} else {
// Addition overflowed
return false;
}
} else {
// Multiplication overflowed
return false;
}
} else {
// The character is not a digit
return false;
};
}
}
}
}
}
dots == 3 && current_octet.is_some()
}
#[no_mangle]
#[allow(non_snake_case)]
pub extern "C" fn rust_net_is_valid_ipv4_addr<'a>(addr: &'a u8, addrLen: i32) -> bool {
let address = unsafe { slice::from_raw_parts(addr, addrLen as usize) };
is_valid_ipv4_addr(address)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment