Skip to content

Instantly share code, notes, and snippets.

@saskenuba
Last active May 20, 2022 16:38
Show Gist options
  • Save saskenuba/196f67a76d5de8ce28e5ff8b67b015b6 to your computer and use it in GitHub Desktop.
Save saskenuba/196f67a76d5de8ce28e5ff8b67b015b6 to your computer and use it in GitHub Desktop.
Validar CPF Rust lang
/// Valida CPF
/// Espera um `&str` no formato: "52998224725"
pub fn validate_cpf(cpf: &str) -> bool {
let all_digits_repeated = [cpf.chars().nth(0).unwrap()]
.repeat(11)
.into_iter()
.collect::<String>();
if cpf.len() != 11 || cpf == &*all_digits_repeated {
return false;
};
let mut first_sum = 0;
let mut second_sum = 0;
for (idx, number) in cpf.chars().map(|d| d.to_digit(10).unwrap()).enumerate() {
second_sum += number * (11 - idx as u32);
if idx == 9 {
break;
};
first_sum += number * (10 - idx as u32);
}
let first_validator = cpf.chars().nth(9).and_then(|d| d.to_digit(10)).unwrap();
let second_validator = cpf.chars().nth(10).and_then(|d| d.to_digit(10)).unwrap();
if first_sum * 10 % 11 != first_validator {
return false;
}
if second_sum * 10 % 11 != second_validator {
return false;
}
true
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn t_cpf_valid_validator() {
let res = validate_cpf("52998224725");
assert!(res);
}
#[test]
fn t_cpf_invalid_validator() {
let res = validate_cpf("11111111111");
assert!(!res);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment