validation_CH_AHV.c (1956B)
1 /* 2 This file is part of Anastasis 3 Copyright (C) 2020, 2021 Anastasis SARL 4 5 Anastasis is free software; you can redistribute it and/or modify it under the 6 terms of the GNU General Public License as published by the Free Software 7 Foundation; either version 3, or (at your option) any later version. 8 9 Anastasis is distributed in the hope that it will be useful, but WITHOUT ANY 10 WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR 11 A PARTICULAR PURPOSE. See the GNU General Public License for more details. 12 13 You should have received a copy of the GNU General Public License along with 14 Anastasis; see the file COPYING.GPL. If not, see <http://www.gnu.org/licenses/> 15 */ 16 /** 17 * @file reducer/validation_CH_AHV.c 18 * @brief anastasis reducer api 19 * @author Christian Grothoff 20 * @author Dominik Meister 21 * @author Dennis Neufeld 22 */ 23 #include <string.h> 24 #include <stdbool.h> 25 26 /** 27 * Function to validate a Swiss AHV number. 28 * 29 * @param ahv_number ahv number to validate (input) 30 * @return true if validation passed, else false 31 */ 32 bool 33 CH_AHV_check (const char *ahv_number); 34 35 /* declaration to fix compiler warning */ 36 bool 37 CH_AHV_check (const char *ahv_number) 38 { 39 unsigned int checknum; 40 unsigned int next_ten; 41 size_t len = strlen (ahv_number); 42 const char *pos; 43 bool phase = true; 44 unsigned int calculation = 0; 45 46 /* Guard against empty input: strlen()-1 would wrap and read one byte 47 before the buffer. A valid AHV number is 13 digits (optionally dotted). */ 48 if (0 == len) 49 return false; 50 pos = &ahv_number[len - 1]; 51 checknum = *pos - 48; 52 while (pos > ahv_number) 53 { 54 pos--; 55 if ('.' == *pos) 56 continue; 57 if (phase) 58 calculation += ((*pos - 48) * 3); 59 else 60 calculation += *pos - 48; 61 phase = ! phase; 62 } 63 /* round up to the next ten */ 64 next_ten = ((calculation + 9) / 10) * 10; 65 calculation = next_ten - calculation; 66 return (checknum == calculation); 67 }