Skip to main content

rust_validador/
lib.rs

1pub fn validar_cpf(cpf: &str) -> bool {
2    // Remove caracteres que não são números
3    let cpf: String = cpf.chars().filter(|c| c.is_ascii_digit()).collect();
4
5    // CPF deve ter 11 dígitos
6    if cpf.len() != 11 {
7        return false;
8    }
9
10    let numeros: Vec<u32> = cpf
11        .chars()
12        .map(|c| c.to_digit(10).unwrap())
13        .collect();
14
15    // Rejeita CPFs com todos os dígitos iguais
16    if numeros.iter().all(|&n| n == numeros[0]) {
17        return false;
18    }
19
20    // Primeiro dígito verificador
21    let soma1: u32 = numeros[..9]
22        .iter()
23        .enumerate()
24        .map(|(i, &n)| n * (10 - i as u32))
25        .sum();
26
27    let resto1 = soma1 % 11;
28    let dv1 = if resto1 < 2 { 0 } else { 11 - resto1 };
29
30    if numeros[9] != dv1 {
31        return false;
32    }
33
34    // Segundo dígito verificador
35    let soma2: u32 = numeros[..10]
36        .iter()
37        .enumerate()
38        .map(|(i, &n)| n * (11 - i as u32))
39        .sum();
40
41    let resto2 = soma2 % 11;
42    let dv2 = if resto2 < 2 { 0 } else { 11 - resto2 };
43
44    numeros[10] == dv2
45}