LCOV - code coverage report
Current view: top level - src/utils/common - StringUtils.cpp (source / functions) Coverage Total Hit
Test: lcov.info Lines: 78.5 % 302 237
Test Date: 2026-10-12 15:53:19 Functions: 75.0 % 40 30

            Line data    Source code
       1              : /****************************************************************************/
       2              : // Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.dev/sumo
       3              : // Copyright (C) 2001-2026 German Aerospace Center (DLR) and others.
       4              : // This program and the accompanying materials are made available under the
       5              : // terms of the Eclipse Public License 2.0 which is available at
       6              : // https://www.eclipse.org/legal/epl-2.0/
       7              : // This Source Code may also be made available under the following Secondary
       8              : // Licenses when the conditions for such availability set forth in the Eclipse
       9              : // Public License 2.0 are satisfied: GNU General Public License, version 2
      10              : // or later which is available at
      11              : // https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html
      12              : // SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later
      13              : /****************************************************************************/
      14              : /// @file    StringUtils.cpp
      15              : /// @author  Daniel Krajzewicz
      16              : /// @author  Laura Bieker
      17              : /// @author  Michael Behrisch
      18              : /// @author  Robert Hilbrich
      19              : /// @date    unknown
      20              : ///
      21              : // Some static methods for string processing
      22              : /****************************************************************************/
      23              : #include <config.h>
      24              : 
      25              : #include <string>
      26              : #include <iostream>
      27              : #include <cstdio>
      28              : #include <cstring>
      29              : #include <regex>
      30              : #ifdef WIN32
      31              : #define NOMINMAX
      32              : #include <windows.h>
      33              : #undef NOMINMAX
      34              : #else
      35              : #include <unistd.h>
      36              : #endif
      37              : #include <utils/common/UtilExceptions.h>
      38              : #include <utils/common/ToString.h>
      39              : #include <utils/common/StringTokenizer.h>
      40              : #include "StringUtils.h"
      41              : 
      42              : #define KM_PER_MILE 1.609344
      43              : 
      44              : 
      45              : // ===========================================================================
      46              : // static member definitions
      47              : // ===========================================================================
      48              : std::string StringUtils::emptyString;
      49              : 
      50              : 
      51              : // ===========================================================================
      52              : // method definitions
      53              : // ===========================================================================
      54              : std::string
      55      1600642 : StringUtils::prune(const std::string& str) {
      56              :     const std::string::size_type endpos = str.find_last_not_of(" \t\n\r");
      57      1600642 :     if (std::string::npos != endpos) {
      58      1597504 :         const int startpos = (int)str.find_first_not_of(" \t\n\r");
      59      1597504 :         return str.substr(startpos, endpos - startpos + 1);
      60              :     }
      61         3138 :     return "";
      62              : }
      63              : 
      64              : 
      65              : std::string
      66        58579 : StringUtils::pruneZeros(const std::string& str, int max) {
      67              :     const std::string::size_type endpos = str.find_last_not_of("0");
      68        58579 :     if (endpos != std::string::npos && str.back() == '0') {
      69        39353 :         std::string res = str.substr(0, MAX2((int)str.size() - max, (int)endpos + 1));
      70        39353 :         return res;
      71              :     }
      72              :     return str;
      73              : }
      74              : 
      75              : std::string
      76      8441573 : StringUtils::to_lower_case(const std::string& str) {
      77              :     std::string s = str;
      78              :     std::transform(s.begin(), s.end(), s.begin(), [](char c) {
      79     58305741 :         return (char)::tolower(c);
      80              :     });
      81      8441573 :     return s;
      82              : }
      83              : 
      84              : 
      85              : std::string
      86            0 : StringUtils::to_upper_case(const std::string& str) {
      87              :     std::string s = str;
      88              :     std::transform(s.begin(), s.end(), s.begin(), [](char c) {
      89            0 :         return (char)::toupper(c);
      90              :     });
      91            0 :     return s;
      92              : }
      93              : 
      94              : 
      95              : std::string
      96         1956 : StringUtils::latin1_to_utf8(std::string str) {
      97              :     // inspired by http://stackoverflow.com/questions/4059775/convert-iso-8859-1-strings-to-utf-8-in-c-c
      98              :     std::string result;
      99         8781 :     for (const auto& c : str) {
     100         6825 :         const unsigned char uc = (unsigned char)c;
     101         6825 :         if (uc < 128) {
     102              :             result += uc;
     103              :         } else {
     104          100 :             result += (char)(0xc2 + (uc > 0xbf));
     105          100 :             result += (char)((uc & 0x3f) + 0x80);
     106              :         }
     107              :     }
     108         1956 :     return result;
     109              : }
     110              : 
     111              : 
     112              : std::string
     113      1272481 : StringUtils::convertUmlaute(std::string str) {
     114      3817443 :     str = replace(str, "\xE4", "ae");
     115      3817443 :     str = replace(str, "\xC4", "Ae");
     116      3817443 :     str = replace(str, "\xF6", "oe");
     117      3817443 :     str = replace(str, "\xD6", "Oe");
     118      3817443 :     str = replace(str, "\xFC", "ue");
     119      3817443 :     str = replace(str, "\xDC", "Ue");
     120      3817443 :     str = replace(str, "\xDF", "ss");
     121      3817443 :     str = replace(str, "\xC9", "E");
     122      3817443 :     str = replace(str, "\xE9", "e");
     123      3817443 :     str = replace(str, "\xC8", "E");
     124      3817443 :     str = replace(str, "\xE8", "e");
     125      1272481 :     return str;
     126              : }
     127              : 
     128              : 
     129              : std::string
     130     72458704 : StringUtils::replace(std::string str, const std::string& what, const std::string& by) {
     131              :     std::string::size_type idx = str.find(what);
     132     72458704 :     const int what_len = (int)what.length();
     133     72458704 :     if (what_len > 0) {
     134     72458703 :         const int by_len = (int)by.length();
     135     72462701 :         while (idx != std::string::npos) {
     136         3998 :             str = str.replace(idx, what_len, by);
     137         3998 :             idx = str.find(what, idx + by_len);
     138              :         }
     139              :     }
     140     72458704 :     return str;
     141              : }
     142              : 
     143              : 
     144              : std::string
     145      1375797 : StringUtils::substituteEnvironment(const std::string& str, const std::chrono::time_point<std::chrono::system_clock>* const timeRef) {
     146              :     std::string s = str;
     147      1375797 :     if (timeRef != nullptr) {
     148              :         const std::string::size_type localTimeIndex = str.find("${LOCALTIME}");
     149              :         const std::string::size_type utcIndex = str.find("${UTC}");
     150              :         const bool isUTC = utcIndex != std::string::npos;
     151      1375791 :         if (localTimeIndex != std::string::npos || isUTC) {
     152            6 :             const time_t rawtime = std::chrono::system_clock::to_time_t(*timeRef);
     153              :             char buffer [80];
     154            6 :             struct tm* timeinfo = isUTC ? gmtime(&rawtime) : localtime(&rawtime);
     155            6 :             strftime(buffer, 80, "%Y-%m-%d-%H-%M-%S.", timeinfo);
     156              :             auto seconds = std::chrono::time_point_cast<std::chrono::seconds>(*timeRef);
     157              :             auto microseconds = std::chrono::duration_cast<std::chrono::microseconds>(*timeRef - seconds);
     158            6 :             const std::string micro = buffer + toString(microseconds.count());
     159            6 :             if (isUTC) {
     160              :                 s.replace(utcIndex, 6, micro);
     161              :             } else {
     162              :                 s.replace(localTimeIndex, 12, micro);
     163              :             }
     164              :         }
     165              :     }
     166              :     const std::string::size_type pidIndex = str.find("${PID}");
     167      1375797 :     if (pidIndex != std::string::npos) {
     168              : #ifdef WIN32
     169              :         s.replace(pidIndex, 6, toString(::GetCurrentProcessId()));
     170              : #else
     171            6 :         s.replace(pidIndex, 6, toString(::getpid()));
     172              : #endif
     173              :     }
     174      1375797 :     if (std::getenv("SUMO_LOGO") == nullptr) {
     175      4127391 :         s = replace(s, "${SUMO_LOGO}", "${SUMO_HOME}/data/logo/sumo-128x138.png");
     176              :     }
     177              :     const std::string::size_type tildeIndex = str.find("~");
     178      1375797 :     if (tildeIndex == 0) {
     179            3 :         s.replace(0, 1, "${HOME}");
     180              :     }
     181      4127391 :     s = replace(s, ",~", ",${HOME}");
     182              : #ifdef WIN32
     183              :     if (std::getenv("HOME") == nullptr) {
     184              :         s = replace(s, "${HOME}", "${USERPROFILE}");
     185              :     }
     186              : #endif
     187              : 
     188              :     // Expression for an environment variables, e.g. ${NAME}
     189              :     // Note: - R"(...)" is a raw string literal syntax to simplify a regex declaration
     190              :     //       - .+? looks for the shortest match (non-greedy)
     191              :     //       - (.+?) defines a "subgroup" which is already stripped of the $ and {, }
     192      1375797 :     std::regex envVarExpr(R"(\$\{(.+?)\})");
     193              : 
     194              :     // Are there any variables in this string?
     195              :     std::smatch match;
     196              :     std::string strIter = s;
     197              : 
     198              :     // Loop over the entire value string and look for variable names
     199      1375863 :     while (std::regex_search(strIter, match, envVarExpr)) {
     200              :         std::string varName = match[1];
     201              : 
     202              :         // Find the variable in the environment and its value
     203              :         std::string varValue;
     204           66 :         if (std::getenv(varName.c_str()) != nullptr) {
     205           65 :             varValue = std::getenv(varName.c_str());
     206              :         }
     207              : 
     208              :         // Replace the variable placeholder with its value in the original string
     209          264 :         s = std::regex_replace(s, std::regex("\\$\\{" + varName + "\\}"), varValue);
     210              : 
     211              :         // Continue the loop with the remainder of the string
     212          132 :         strIter = match.suffix();
     213              :     }
     214      1375797 :     return s;
     215      1375797 : }
     216              : 
     217              : 
     218              : std::string
     219        90176 : StringUtils::isoTimeString(const std::chrono::time_point<std::chrono::system_clock>* const timeRef) {
     220        90176 :     const std::chrono::system_clock::time_point now = timeRef == nullptr ? std::chrono::system_clock::now() : *timeRef;
     221              :     const auto now_seconds = std::chrono::time_point_cast<std::chrono::seconds>(now);
     222        90176 :     const std::time_t now_c = std::chrono::system_clock::to_time_t(now);
     223              :     const auto microseconds = std::chrono::duration_cast<std::chrono::microseconds>(now - now_seconds).count();
     224        90176 :     std::tm local_tm = *std::localtime(&now_c);
     225              : 
     226              :     // Get the time zone offset
     227        90176 :     std::time_t utc_time = std::time(nullptr);
     228        90176 :     std::tm utc_tm = *std::gmtime(&utc_time);
     229        90176 :     const double offset = std::difftime(std::mktime(&local_tm), std::mktime(&utc_tm)) / 3600.0;
     230        90176 :     const int hours_offset = static_cast<int>(offset);
     231        90176 :     const int minutes_offset = static_cast<int>((offset - hours_offset) * 60);
     232              : 
     233              :     // Format the time
     234        90176 :     std::ostringstream oss;
     235              :     char buf[32];
     236        90176 :     std::strftime(buf, sizeof(buf), "%Y-%m-%dT%H:%M:%S", &local_tm);
     237              :     oss << buf << "."
     238              :         << std::setw(6) << std::setfill('0') << std::abs(microseconds)
     239              :         << (hours_offset >= 0 ? "+" : "-")
     240        90176 :         << std::setw(2) << std::setfill('0') << std::abs(hours_offset) << ":"
     241       180352 :         << std::setw(2) << std::setfill('0') << std::abs(minutes_offset);
     242        90176 :     return oss.str();
     243        90176 : }
     244              : 
     245              : 
     246              : bool
     247      6732967 : StringUtils::startsWith(const std::string& str, const std::string prefix) {
     248      6732967 :     return str.compare(0, prefix.length(), prefix) == 0;
     249              : }
     250              : 
     251              : 
     252              : bool
     253       224257 : StringUtils::endsWith(const std::string& str, const std::string suffix) {
     254       224257 :     if (str.length() >= suffix.length()) {
     255       224234 :         return str.compare(str.length() - suffix.length(), suffix.length(), suffix) == 0;
     256              :     } else {
     257              :         return false;
     258              :     }
     259              : }
     260              : 
     261              : 
     262              : std::string
     263            0 : StringUtils::padFront(const std::string& str, int length, char padding) {
     264            0 :     return std::string(MAX2(0, length - (int)str.size()), padding) + str;
     265              : }
     266              : 
     267              : 
     268              : std::string
     269      1519225 : StringUtils::escapeXML(const std::string& orig, const bool maskDoubleHyphen) {
     270      4557675 :     std::string result = replace(orig, "&", "&amp;");
     271      4557675 :     result = replace(result, ">", "&gt;");
     272      4557675 :     result = replace(result, "<", "&lt;");
     273      4557675 :     result = replace(result, "\"", "&quot;");
     274      1519225 :     if (maskDoubleHyphen) {
     275      2396094 :         result = replace(result, "--", "&#45;&#45;");
     276              :     }
     277     48615200 :     for (char invalid = '\1'; invalid < ' '; invalid++) {
     278    235479875 :         result = replace(result, std::string(1, invalid).c_str(), "");
     279              :     }
     280      4557675 :     return replace(result, "'", "&apos;");
     281              : }
     282              : 
     283              : 
     284              : std::string
     285            0 : StringUtils::escapeShell(const std::string& orig) {
     286            0 :     return replace(orig, "\"", "\\\"");
     287              : }
     288              : 
     289              : 
     290              : std::string
     291         4072 : StringUtils::escapeCSV(const std::string& orig, const char separator, const char quote) {
     292         4072 :     const std::string chars{separator, quote};
     293         4072 :     if (orig.find_first_of(chars) == std::string::npos) {
     294              :         return orig;
     295              :     }
     296           36 :     const std::string quoteStr{quote};
     297          108 :     return quoteStr + replace(orig, quoteStr, {'\\', quote}) + quoteStr;
     298              : }
     299              : 
     300              : 
     301              : std::string
     302         5127 : StringUtils::urlEncode(const std::string& toEncode, const std::string encodeWhich) {
     303         5127 :     std::ostringstream out;
     304              : 
     305       131355 :     for (int i = 0; i < (int)toEncode.length(); ++i) {
     306       126228 :         const char t = toEncode.at(i);
     307              : 
     308       126228 :         if ((encodeWhich != "" && encodeWhich.find(t) == std::string::npos) ||
     309            1 :                 (encodeWhich == "" &&
     310            0 :                  ((t >= 45 && t <= 57) ||       // hyphen, period, slash, 0-9
     311            0 :                   (t >= 65 && t <= 90) ||        // A-Z
     312              :                   t == 95 ||                     // underscore
     313              :                   (t >= 97 && t <= 122) ||       // a-z
     314              :                   t == 126))                     // tilde
     315              :            ) {
     316       126227 :             out << toEncode.at(i);
     317              :         } else {
     318            2 :             out << charToHex(toEncode.at(i));
     319              :         }
     320              :     }
     321              : 
     322         5127 :     return out.str();
     323         5127 : }
     324              : 
     325              : 
     326              : std::string
     327        92807 : StringUtils::urlDecode(const std::string& toDecode) {
     328        92807 :     std::ostringstream out;
     329              : 
     330      1972638 :     for (int i = 0; i < (int)toDecode.length(); ++i) {
     331      1879833 :         if (toDecode.at(i) == '%') {
     332            2 :             std::string str(toDecode.substr(i + 1, 2));
     333            2 :             out << hexToChar(str);
     334            0 :             i += 2;
     335              :         } else {
     336      1879831 :             out << toDecode.at(i);
     337              :         }
     338              :     }
     339              : 
     340        92805 :     return out.str();
     341        92807 : }
     342              : 
     343              : std::string
     344            1 : StringUtils::charToHex(unsigned char c) {
     345              :     short i = c;
     346              : 
     347            1 :     std::stringstream s;
     348              : 
     349            1 :     s << "%" << std::setw(2) << std::setfill('0') << std::hex << i;
     350              : 
     351            1 :     return s.str();
     352            1 : }
     353              : 
     354              : 
     355              : unsigned char
     356            2 : StringUtils::hexToChar(const std::string& str) {
     357            2 :     short c = 0;
     358            2 :     if (!str.empty()) {
     359            2 :         std::istringstream in(str);
     360            2 :         in >> std::hex >> c;
     361            2 :         if (in.fail()) {
     362            4 :             throw NumberFormatException(str + " could not be interpreted as hex");
     363              :         }
     364            2 :     }
     365            0 :     return static_cast<unsigned char>(c);
     366              : }
     367              : 
     368              : 
     369              : int
     370     19362283 : StringUtils::toInt(const std::string& sData) {
     371     19362283 :     long long int result = toLong(sData);
     372     19344735 :     if (result > std::numeric_limits<int>::max() || result < std::numeric_limits<int>::min()) {
     373            3 :         throw NumberFormatException(toString(result) + " int overflow");
     374              :     }
     375     19344734 :     return (int)result;
     376              : }
     377              : 
     378              : 
     379              : bool
     380           92 : StringUtils::isInt(const std::string& sData) {
     381              :     // first check if can be converted to long int
     382           92 :     if (isLong(sData)) {
     383           84 :         const long long int result = toLong(sData);
     384              :         // now check if the result is in the range of an int
     385           84 :         return ((result <= std::numeric_limits<int>::max()) && (result >= std::numeric_limits<int>::min()));
     386              :     }
     387              :     return false;
     388              : }
     389              : 
     390              : 
     391              : int
     392            0 : StringUtils::toIntSecure(const std::string& sData, int def) {
     393            0 :     if (sData.length() == 0) {
     394              :         return def;
     395              :     }
     396            0 :     return toInt(sData);
     397              : }
     398              : 
     399              : 
     400              : long long int
     401     20806565 : StringUtils::toLong(const std::string& sData) {
     402              :     const char* const data = sData.c_str();
     403     20806565 :     if (data == 0 || data[0] == 0) {
     404           78 :         throw EmptyData();
     405              :     }
     406              :     char* end;
     407     20806487 :     errno = 0;
     408              : #ifdef _MSC_VER
     409              :     long long int ret = _strtoi64(data, &end, 10);
     410              : #else
     411     20806487 :     long long int ret = strtoll(data, &end, 10);
     412              : #endif
     413     20806487 :     if (errno == ERANGE) {
     414            0 :         errno = 0;
     415            0 :         throw NumberFormatException("(long long integer range) " + sData);
     416              :     }
     417     20806487 :     if ((int)(end - data) != (int)strlen(data)) {
     418        36186 :         throw NumberFormatException("(long long integer format) " + sData);
     419              :     }
     420     20788394 :     return ret;
     421              : }
     422              : 
     423              : 
     424              : bool
     425           92 : StringUtils::isLong(const std::string& sData) {
     426              :     const char* const data = sData.c_str();
     427           92 :     if (data == 0 || data[0] == 0) {
     428              :         return false;
     429              :     }
     430              :     char* end;
     431              :     // reset errno before parsing, to keep errors
     432           92 :     errno = 0;
     433              :     // continue depending of current plattform
     434              : #ifdef _MSC_VER
     435              :     _strtoi64(data, &end, 10);
     436              : #else
     437           92 :     strtoll(data, &end, 10);
     438              : #endif
     439              :     // check out of range
     440           92 :     if (errno == ERANGE) {
     441              :         return false;
     442              :     }
     443              :     // check length of converted data
     444           92 :     if ((int)(end - data) != (int)strlen(data)) {
     445              :         return false;
     446              :     }
     447              :     return true;
     448              : }
     449              : 
     450              : 
     451              : int
     452          968 : StringUtils::hexToInt(const std::string& sData) {
     453          968 :     if (sData.length() == 0) {
     454            0 :         throw EmptyData();
     455              :     }
     456          968 :     size_t idx = 0;
     457              :     int result;
     458              :     try {
     459          968 :         if (sData[0] == '#') { // for html color codes
     460          884 :             result = std::stoi(sData.substr(1), &idx, 16);
     461          884 :             idx++;
     462              :         } else {
     463              :             result = std::stoi(sData, &idx, 16);
     464              :         }
     465            0 :     } catch (...) {
     466            0 :         throw NumberFormatException("(hex integer format) " + sData);
     467            0 :     }
     468          968 :     if (idx != sData.length()) {
     469            0 :         throw NumberFormatException("(hex integer format) " + sData);
     470              :     }
     471          968 :     return result;
     472              : }
     473              : 
     474              : 
     475              : bool
     476            0 : StringUtils::isHex(std::string sData) {
     477            0 :     if (sData.length() == 0) {
     478              :         return false;
     479              :     }
     480              :     // remove the first character (for HTML color codes)
     481            0 :     if (sData[0] == '#') {
     482            0 :         sData = sData.substr(1);
     483              :     }
     484              :     const char* sDataPtr = sData.c_str();
     485              :     char* returnPtr;
     486              :     // reset errno
     487            0 :     errno = 0;
     488              :     // call string to long (size 16) from standard library
     489            0 :     strtol(sDataPtr, &returnPtr, 16);
     490              :     // check out of range
     491            0 :     if (errno == ERANGE) {
     492              :         return false;
     493              :     }
     494              :     // check if there was an error converting sDataPtr to double,
     495            0 :     if (sDataPtr == returnPtr) {
     496              :         return false;
     497              :     }
     498              :     // compare size of start and end points
     499            0 :     if (static_cast<size_t>(returnPtr - sDataPtr) != sData.size()) {
     500              :         return false;
     501              :     }
     502              :     return true;
     503              : }
     504              : 
     505              : 
     506              : double
     507     65872197 : StringUtils::toDouble(const std::string& sData) {
     508     65872197 :     if (sData.size() == 0) {
     509          219 :         throw EmptyData();
     510              :     }
     511              :     try {
     512     65871978 :         size_t idx = 0;
     513              :         const double result = std::stod(sData, &idx);
     514     65870363 :         if (idx != sData.size()) {
     515           34 :             throw NumberFormatException("(double format) " + sData);
     516              :         } else {
     517     65870346 :             return result;
     518              :         }
     519         1632 :     } catch (...) {
     520              :         // invalid_argument or out_of_range
     521         3264 :         throw NumberFormatException("(double) " + sData);
     522         1632 :     }
     523              : }
     524              : 
     525              : 
     526              : bool
     527            0 : StringUtils::isDouble(const std::string& sData) {
     528            0 :     if (sData.size() == 0) {
     529              :         return false;
     530              :     }
     531              :     const char* sDataPtr = sData.c_str();
     532              :     char* returnPtr;
     533              :     // reset errno
     534            0 :     errno = 0;
     535              :     // call string to double from standard library
     536            0 :     strtod(sDataPtr, &returnPtr);
     537              :     // check out of range
     538            0 :     if (errno == ERANGE) {
     539              :         return false;
     540              :     }
     541              :     // check if there was an error converting sDataPtr to double,
     542            0 :     if (sDataPtr == returnPtr) {
     543              :         return false;
     544              :     }
     545              :     // compare size of start and end points
     546            0 :     if (static_cast<size_t>(returnPtr - sDataPtr) != sData.size()) {
     547              :         return false;
     548              :     }
     549              :     return true;
     550              : }
     551              : 
     552              : 
     553              : double
     554          376 : StringUtils::toDoubleSecure(const std::string& sData, const double def) {
     555          376 :     if (sData.length() == 0) {
     556              :         return def;
     557              :     }
     558          376 :     return toDouble(sData);
     559              : }
     560              : 
     561              : 
     562              : double
     563      3109209 : StringUtils::toDoubleAllowTime(const std::string& sData) {
     564      3109209 :     if (sData.find(":") == std::string::npos) {
     565      3109181 :         return toDouble(sData);
     566           28 :     } else if (isTime(sData)) {
     567           28 :         return STEPS2TIME(string2time(sData));
     568              :     }
     569            0 :     throw NumberFormatException("(double) " + sData);
     570              : }
     571              : 
     572              : bool
     573      3408169 : StringUtils::toBool(const std::string& sData) {
     574      3408169 :     if (sData.length() == 0) {
     575            1 :         throw EmptyData();
     576              :     }
     577      3408168 :     const std::string s = to_lower_case(sData);
     578      3408168 :     if (s == "1" || s == "yes" || s == "true" || s == "on" || s == "x" || s == "t") {
     579              :         return true;
     580              :     }
     581      2744031 :     if (s == "0" || s == "no" || s == "false" || s == "off" || s == "-" || s == "f") {
     582              :         return false;
     583              :     }
     584          147 :     throw BoolFormatException(s);
     585              : }
     586              : 
     587              : 
     588              : bool
     589        75642 : StringUtils::isBool(const std::string& sData) {
     590        75642 :     if (sData.length() == 0) {
     591              :         return false;
     592              :     }
     593        17628 :     const std::string s = to_lower_case(sData);
     594              :     // check true values
     595        17628 :     if (s == "1" || s == "yes" || s == "true" || s == "on" || s == "x" || s == "t") {
     596              :         return true;
     597              :     }
     598              :     // check false values
     599         1064 :     if (s == "0" || s == "no" || s == "false" || s == "off" || s == "-" || s == "f") {
     600              :         return true;
     601              :     }
     602              :     // no valid true or false values
     603              :     return false;
     604              : }
     605              : 
     606              : 
     607              : MMVersion
     608        49280 : StringUtils::toVersion(const std::string& sData) {
     609       147840 :     std::vector<std::string> parts = StringTokenizer(sData, ".").getVector();
     610        98560 :     return MMVersion(toInt(parts.front()), toDouble(parts.back()));
     611        49280 : }
     612              : 
     613              : 
     614              : double
     615         2287 : StringUtils::parseDist(const std::string& sData) {
     616         2287 :     if (sData.size() == 0) {
     617            1 :         throw EmptyData();
     618              :     }
     619              :     try {
     620         2286 :         size_t idx = 0;
     621              :         const double result = std::stod(sData, &idx);
     622         2285 :         if (idx != sData.size()) {
     623            5 :             const std::string unit = prune(sData.substr(idx));
     624            5 :             if (unit == "m" || unit == "metre" || unit == "meter" || unit == "metres" || unit == "meters") {
     625              :                 return result;
     626              :             }
     627            2 :             if (unit == "km" || unit == "kilometre" || unit == "kilometer" || unit == "kilometres" || unit == "kilometers") {
     628            1 :                 return result * 1000.;
     629              :             }
     630            1 :             if (unit == "mi" || unit == "mile" || unit == "miles") {
     631            0 :                 return result * 1000. * KM_PER_MILE;
     632              :             }
     633            1 :             if (unit == "nmi") {
     634            0 :                 return result * 1852.;
     635              :             }
     636            1 :             if (unit == "ft" || unit == "foot" || unit == "feet") {
     637            0 :                 return result * 12. * 0.0254;
     638              :             }
     639            1 :             if (unit == "\"" || unit == "in" || unit == "inch" || unit == "inches") {
     640            0 :                 return result * 0.0254;
     641              :             }
     642            1 :             if (unit[0] == '\'') {
     643            0 :                 double inches = 12 * result;
     644            0 :                 if (unit.length() > 1) {
     645            0 :                     inches += std::stod(unit.substr(1), &idx);
     646            1 :                     if (unit.substr(idx) == "\"") {
     647            0 :                         return inches * 0.0254;
     648              :                     }
     649              :                 }
     650              :             }
     651            2 :             throw NumberFormatException("(distance format) " + sData);
     652              :         } else {
     653              :             return result;
     654              :         }
     655            2 :     } catch (...) {
     656              :         // invalid_argument or out_of_range
     657            4 :         throw NumberFormatException("(double) " + sData);
     658            2 :     }
     659              : }
     660              : 
     661              : 
     662              : double
     663         8129 : StringUtils::parseSpeed(const std::string& sData, const bool defaultKmph) {
     664         8129 :     if (sData.size() == 0) {
     665            1 :         throw EmptyData();
     666              :     }
     667              :     try {
     668         8128 :         size_t idx = 0;
     669              :         const double result = std::stod(sData, &idx);
     670         8124 :         if (idx != sData.size()) {
     671         1247 :             const std::string unit = prune(sData.substr(idx));
     672         1247 :             if (unit == "km/h" || unit == "kph" || unit == "kmh" || unit == "kmph") {
     673            3 :                 return result / 3.6;
     674              :             }
     675         1244 :             if (unit == "m/s") {
     676              :                 return result;
     677              :             }
     678         1242 :             if (unit == "mph") {
     679         1241 :                 return result * KM_PER_MILE / 3.6;
     680              :             }
     681            1 :             if (unit == "knots") {
     682            0 :                 return result * 1.852 / 3.6;
     683              :             }
     684            2 :             throw NumberFormatException("(speed format) " + sData);
     685              :         } else {
     686         6877 :             return defaultKmph ? result / 3.6 : result;
     687              :         }
     688            5 :     } catch (...) {
     689              :         // invalid_argument or out_of_range
     690           10 :         throw NumberFormatException("(double) " + sData);
     691            5 :     }
     692              : }
     693              : 
     694              : 
     695              : 
     696              : std::string
     697            0 : StringUtils::trim_left(const std::string s, const std::string& t) {
     698              :     std::string result = s;
     699            0 :     result.erase(0, s.find_first_not_of(t));
     700            0 :     return result;
     701              : }
     702              : 
     703              : std::string
     704            0 : StringUtils::trim_right(const std::string s, const std::string& t) {
     705              :     std::string result = s;
     706            0 :     result.erase(s.find_last_not_of(t) + 1);
     707            0 :     return result;
     708              : }
     709              : 
     710              : std::string
     711            0 : StringUtils::trim(const std::string s, const std::string& t) {
     712            0 :     return trim_right(trim_left(s, t), t);
     713              : }
     714              : 
     715              : 
     716              : std::string
     717            0 : StringUtils::wrapText(const std::string s, int width) {
     718            0 :     std::vector<std::string> parts = StringTokenizer(s).getVector();
     719              :     std::string result;
     720              :     std::string line;
     721              :     bool firstLine = true;
     722              :     bool firstWord = true;
     723            0 :     for (std::string p : parts) {
     724            0 :         if ((int)(line.size() + p.size()) < width || firstWord) {
     725            0 :             if (firstWord) {
     726              :                 firstWord = false;
     727              :             } else {
     728              :                 line += " ";
     729              :             }
     730              :             line += p;
     731              :         } else {
     732            0 :             if (firstLine) {
     733              :                 firstLine = false;
     734              :             } else {
     735              :                 result += "\n";
     736              :             }
     737              :             result += line;
     738              :             line.clear();
     739              :             line += p;
     740              :         }
     741              :     }
     742            0 :     if (line.size() > 0) {
     743            0 :         if (firstLine) {
     744              :             firstLine = false;
     745              :         } else {
     746              :             result += "\n";
     747              :         }
     748              :         result += line;
     749              :     }
     750            0 :     return result;
     751            0 : }
     752              : 
     753              : 
     754              : std::string
     755          969 : StringUtils::adjustDecimalValue(double value, int precision) {
     756              :     // obtain value in string format with 20 decimals precision
     757          969 :     auto valueStr = toString(value, precision);
     758              :     // now clear all zeros
     759        17033 :     while (valueStr.size() > 1) {
     760        17033 :         if (valueStr.back() == '0') {
     761              :             valueStr.pop_back();
     762          969 :         } else if (valueStr.back() == '.') {
     763              :             valueStr.pop_back();
     764              :             return valueStr;
     765              :         } else {
     766              :             return valueStr;
     767              :         }
     768              :     }
     769              :     return valueStr;
     770              : }
     771              : 
     772              : 
     773              : /****************************************************************************/
        

Generated by: LCOV version 2.0-1