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
|
/* See LICENSE file for copyright and license details. */
#include <libsimple-arg.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
NUSAGE(2, "number ...");
static int
check_luhn(const char *s)
{
unsigned sum = 0;
switch (strlen(s) & 1U) {
for (;;) {
case 0:
if ('0' <= *s && *s <= '4')
sum += 2U * (unsigned)(*s - '0');
else if ('5' <= *s && *s <= '9')
sum += 2U * (unsigned)(*s - '0') - 9U;
else if (*s)
return 0;
else
break;
s++;
case 1:
if ('0' <= *s && *s <= '9')
sum += (unsigned)(*s - '0');
else if (*s)
return 0;
else
break;
s++;
sum %= 10U;
}
}
return (sum % 10U) == 0U;
}
int
main(int argc, char *argv[])
{
int use_colour;
int ret = 0;
int r, ok;
ARGBEGIN {
default:
usage();
} ARGEND;
if (!argc)
usage();
use_colour = isatty(STDOUT_FILENO);
for (; *argv; argv++) {
ok = check_luhn(*argv);
ret |= !ok;
r = printf("%s%s %s%s\n", use_colour ? ok ? "\033[1;32m" : "\033[1;31m" : "",
*argv, ok ? "is OK" : "is invalid", use_colour ? "\033[m" : "");
if (r < 0) {
fprintf(stderr, "%s: printf: %s\n", argv0, strerror(errno));
exit(2);
}
}
if (fflush(stdout) || fclose(stdout)) {
fprintf(stderr, "%s: printf: %s\n", argv0, strerror(errno));
exit(2);
}
return ret;
}
|