1 /*
2  * Copyright (C) 2018 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #include "utils/checksum.h"
18 #include "utils/strings/numbers.h"
19 
20 namespace libtextclassifier3 {
21 
VerifyLuhnChecksum(const std::string & input,bool ignore_whitespace)22 bool VerifyLuhnChecksum(const std::string& input, bool ignore_whitespace) {
23   int sum = 0;
24   int num_digits = 0;
25   bool is_odd = true;
26 
27   // http://en.wikipedia.org/wiki/Luhn_algorithm
28   static const int kPrecomputedSumsOfDoubledDigits[] = {0, 2, 4, 6, 8,
29                                                         1, 3, 5, 7, 9};
30   for (int i = input.size() - 1; i >= 0; i--) {
31     const char c = input[i];
32     if (ignore_whitespace && c == ' ') {
33       continue;
34     }
35     if (!isdigit(c)) {
36       return false;
37     }
38     ++num_digits;
39     const int digit = c - '0';
40     if (is_odd) {
41       sum += digit;
42     } else {
43       sum += kPrecomputedSumsOfDoubledDigits[digit];
44     }
45     is_odd = !is_odd;
46   }
47   return (num_digits > 1 && sum % 10 == 0);
48 }
49 
50 }  // namespace libtextclassifier3
51