-
Notifications
You must be signed in to change notification settings - Fork 1
/
cpf.c
114 lines (91 loc) · 2.18 KB
/
cpf.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
#include "postgres.h"
#include "fmgr.h"
#include "utils/fmgrprotos.h"
#include "utils/palloc.h"
PG_MODULE_MAGIC;
PG_FUNCTION_INFO_V1(cpfout);
Datum
cpfout(PG_FUNCTION_ARGS)
{
int64 val = PG_GETARG_INT64(0);
int group[4];
char *result;
/* 000.000.000-00 */
group[0] = (val / 100000000) % 1000; /* first group of three digits */
group[1] = (val / 100000) % 1000; /* second group of three digits */
group[2] = (val / 100) % 1000; /* third group of three digits */
group[3] = (val % 100); /* check digits (last two digits) */
result = psprintf("%03d.%03d.%03d-%02d", group[0], group[1], group[2], group[3]);
PG_RETURN_CSTRING(result);
}
/* https://pt.wikipedia.org/wiki/Cadastro_de_Pessoas_F%C3%ADsicas */
static int
compute_cpf_check_digits(long int cpf)
{
int i = 0,
d = 0,
d1 = 0,
d2 = 0;
/* remove last two digits */
cpf = cpf / 100;
do
{
d = cpf % 10;
d1 = d1 + d * (9 - (i % 10));
d2 = d2 + d * (9 - ((i++ + 1) % 10));
cpf = cpf / 10;
} while (cpf > 0);
d1 = (d1 % 11) % 10;
d2 = d2 + d1 * 9;
d2 = (d2 % 11) % 10;
return (d1 * 10) + d2;
}
static void
validate_cpf(int64 cpf)
{
char *out;
int i;
/* Check sizes */
if (cpf < 100 || cpf > 99999999999)
{
ereport(ERROR,
(errcode(ERRCODE_WRONG_OBJECT_TYPE),
errmsg("invalid CPF"),
errdetail("CPF should not be less than 100 and greater than 99999999999.")));
}
/* Check if all digits are the same. */
out = psprintf("%011ld", cpf);
for (i = 1; i < 11 && out[i] == out[0]; i++)
{
if (i == 10)
{
ereport(ERROR,
(errcode(ERRCODE_WRONG_OBJECT_TYPE),
errmsg("invalid CPF"),
errdetail("All CPF digits should not be equal.")));
}
}
if (compute_cpf_check_digits(cpf) != (cpf % 100))
{
ereport(ERROR,
(errcode(ERRCODE_WRONG_OBJECT_TYPE),
errmsg("invalid CPF"),
errdetail("Invalid check digit for the CPF.")));
}
}
PG_FUNCTION_INFO_V1(cpfin);
Datum
cpfin(PG_FUNCTION_ARGS)
{
int64 value = DirectFunctionCall1(int8in, PG_GETARG_DATUM(0));
validate_cpf(value);
PG_RETURN_INT64(value);
}
PG_FUNCTION_INFO_V1(cpfbigint);
Datum
cpfbigint(PG_FUNCTION_ARGS)
{
int64 value = PG_GETARG_INT64(0);
validate_cpf(value);
PG_RETURN_INT64(value);
}