File indexing completed on 2024-05-12 04:42:53

0001 /*
0002     SPDX-FileCopyrightText: 2021 Volker Krause <vkrause@kde.org>
0003 
0004     SPDX-License-Identifier: LGPL-2.0-or-later
0005 */
0006 
0007 #include "uicstationcode.h"
0008 
0009 #include <QString>
0010 #include <QStringView>
0011 
0012 using namespace KPublicTransport;
0013 
0014 bool UicStationCode::isValid(QStringView id, const std::vector<uint8_t> &allowedCountryCodes)
0015 {
0016     // too short, or not a number
0017     if (id.size() < 7 || std::any_of(id.begin(), id.end(), [](QChar c) { return !c.isDigit() || c.row() > 0; })) {
0018         return false;
0019     }
0020 
0021     // too long, but just 0 prefixed
0022     if (id.size() > 7 && std::any_of(id.begin(), id.begin() + id.size() - 7, [](QChar c) { return c != QLatin1Char('0'); })) {
0023         return false;
0024     }
0025 
0026     // one of the explicitly allowed UIC country codes
0027     if (!allowedCountryCodes.empty()) {
0028         const uint8_t countryCode = id.mid(id.size() - 7, 2).toInt();
0029         return std::binary_search(allowedCountryCodes.begin(), allowedCountryCodes.end(), countryCode);
0030     }
0031 
0032     // if no UIC country codes are explicitly allowed, insist on the right length
0033     return id.size() == 7 && id.at(0) != QLatin1Char('0');
0034 }
0035 
0036 QStringView UicStationCode::country(QStringView id)
0037 {
0038     return id.mid(0, 2);
0039 }