Eclipse SUMO - Simulation of Urban MObility
Loading...
Searching...
No Matches
StringUtils.cpp
Go to the documentation of this file.
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/****************************************************************************/
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#include <algorithm>
31#ifdef WIN32
32#include <windows.h>
33#else
34#include <unistd.h>
35#endif
39#include "StringUtils.h"
40
41#define KM_PER_MILE 1.609344
42
43
44// ===========================================================================
45// static member definitions
46// ===========================================================================
47std::string StringUtils::emptyString;
48
49
50// ===========================================================================
51// method definitions
52// ===========================================================================
53std::string
54StringUtils::prune(const std::string& str) {
55 const std::string::size_type endpos = str.find_last_not_of(" \t\n\r");
56 if (std::string::npos != endpos) {
57 const int startpos = (int)str.find_first_not_of(" \t\n\r");
58 return str.substr(startpos, endpos - startpos + 1);
59 }
60 return "";
61}
62
63
64std::string
65StringUtils::pruneZeros(const std::string& str, int max) {
66 const std::string::size_type endpos = str.find_last_not_of("0");
67 if (endpos != std::string::npos && str.back() == '0') {
68 std::string res = str.substr(0, MAX2((int)str.size() - max, (int)endpos + 1));
69 return res;
70 }
71 return str;
72}
73
74std::string
75StringUtils::to_lower_case(const std::string& str) {
76 std::string s = str;
77 std::transform(s.begin(), s.end(), s.begin(), [](char c) {
78 return (char)::tolower(c);
79 });
80 return s;
81}
82
83
84std::string
85StringUtils::to_upper_case(const std::string& str) {
86 std::string s = str;
87 std::transform(s.begin(), s.end(), s.begin(), [](char c) {
88 return (char)::toupper(c);
89 });
90 return s;
91}
92
93
94std::string
96 // inspired by http://stackoverflow.com/questions/4059775/convert-iso-8859-1-strings-to-utf-8-in-c-c
97 std::string result;
98 for (const auto& c : str) {
99 const unsigned char uc = (unsigned char)c;
100 if (uc < 128) {
101 result += uc;
102 } else {
103 result += (char)(0xc2 + (uc > 0xbf));
104 result += (char)((uc & 0x3f) + 0x80);
105 }
106 }
107 return result;
108}
109
110
111std::string
113 str = replace(str, "\xE4", "ae");
114 str = replace(str, "\xC4", "Ae");
115 str = replace(str, "\xF6", "oe");
116 str = replace(str, "\xD6", "Oe");
117 str = replace(str, "\xFC", "ue");
118 str = replace(str, "\xDC", "Ue");
119 str = replace(str, "\xDF", "ss");
120 str = replace(str, "\xC9", "E");
121 str = replace(str, "\xE9", "e");
122 str = replace(str, "\xC8", "E");
123 str = replace(str, "\xE8", "e");
124 return str;
125}
126
127
128std::string
129StringUtils::replace(std::string str, const std::string& what, const std::string& by) {
130 std::string::size_type idx = str.find(what);
131 const int what_len = (int)what.length();
132 if (what_len > 0) {
133 const int by_len = (int)by.length();
134 while (idx != std::string::npos) {
135 str = str.replace(idx, what_len, by);
136 idx = str.find(what, idx + by_len);
137 }
138 }
139 return str;
140}
141
142
143std::string
144StringUtils::substituteEnvironment(const std::string& str, const std::chrono::time_point<std::chrono::system_clock>* const timeRef) {
145 std::string s = str;
146 if (timeRef != nullptr) {
147 const std::string::size_type localTimeIndex = str.find("${LOCALTIME}");
148 const std::string::size_type utcIndex = str.find("${UTC}");
149 const bool isUTC = utcIndex != std::string::npos;
150 if (localTimeIndex != std::string::npos || isUTC) {
151 const time_t rawtime = std::chrono::system_clock::to_time_t(*timeRef);
152 char buffer [80];
153 struct tm* timeinfo = isUTC ? gmtime(&rawtime) : localtime(&rawtime);
154 strftime(buffer, 80, "%Y-%m-%d-%H-%M-%S.", timeinfo);
155 auto seconds = std::chrono::time_point_cast<std::chrono::seconds>(*timeRef);
156 auto microseconds = std::chrono::duration_cast<std::chrono::microseconds>(*timeRef - seconds);
157 const std::string micro = buffer + toString(microseconds.count());
158 if (isUTC) {
159 s.replace(utcIndex, 6, micro);
160 } else {
161 s.replace(localTimeIndex, 12, micro);
162 }
163 }
164 }
165 const std::string::size_type pidIndex = str.find("${PID}");
166 if (pidIndex != std::string::npos) {
167#ifdef WIN32
168 s.replace(pidIndex, 6, toString(::GetCurrentProcessId()));
169#else
170 s.replace(pidIndex, 6, toString(::getpid()));
171#endif
172 }
173 if (std::getenv("SUMO_LOGO") == nullptr) {
174 s = replace(s, "${SUMO_LOGO}", "${SUMO_HOME}/data/logo/sumo-128x138.png");
175 }
176 const std::string::size_type tildeIndex = str.find("~");
177 if (tildeIndex == 0) {
178 s.replace(0, 1, "${HOME}");
179 }
180 s = replace(s, ",~", ",${HOME}");
181#ifdef WIN32
182 if (std::getenv("HOME") == nullptr) {
183 s = replace(s, "${HOME}", "${USERPROFILE}");
184 }
185#endif
186
187 // Expression for an environment variables, e.g. ${NAME}
188 // Note: - R"(...)" is a raw string literal syntax to simplify a regex declaration
189 // - .+? looks for the shortest match (non-greedy)
190 // - (.+?) defines a "subgroup" which is already stripped of the $ and {, }
191 std::regex envVarExpr(R"(\$\{(.+?)\})");
192
193 // Are there any variables in this string?
194 std::smatch match;
195 std::string strIter = s;
196
197 // Loop over the entire value string and look for variable names
198 while (std::regex_search(strIter, match, envVarExpr)) {
199 std::string varName = match[1];
200
201 // Find the variable in the environment and its value
202 std::string varValue;
203 if (std::getenv(varName.c_str()) != nullptr) {
204 varValue = std::getenv(varName.c_str());
205 }
206
207 // Replace the variable placeholder with its value in the original string
208 s = std::regex_replace(s, std::regex("\\$\\{" + varName + "\\}"), varValue);
209
210 // Continue the loop with the remainder of the string
211 strIter = match.suffix();
212 }
213 return s;
214}
215
216
217std::string
218StringUtils::isoTimeString(const std::chrono::time_point<std::chrono::system_clock>* const timeRef) {
219 const std::chrono::system_clock::time_point now = timeRef == nullptr ? std::chrono::system_clock::now() : *timeRef;
220 const auto now_seconds = std::chrono::time_point_cast<std::chrono::seconds>(now);
221 const std::time_t now_c = std::chrono::system_clock::to_time_t(now);
222 const auto microseconds = std::chrono::duration_cast<std::chrono::microseconds>(now - now_seconds).count();
223 std::tm local_tm = *std::localtime(&now_c);
224
225 // Get the time zone offset
226 std::time_t utc_time = std::time(nullptr);
227 std::tm utc_tm = *std::gmtime(&utc_time);
228 const double offset = std::difftime(std::mktime(&local_tm), std::mktime(&utc_tm)) / 3600.0;
229 const int hours_offset = static_cast<int>(offset);
230 const int minutes_offset = static_cast<int>((offset - hours_offset) * 60);
231
232 // Format the time
233 std::ostringstream oss;
234 char buf[32];
235 std::strftime(buf, sizeof(buf), "%Y-%m-%dT%H:%M:%S", &local_tm);
236 oss << buf << "."
237 << std::setw(6) << std::setfill('0') << std::abs(microseconds)
238 << (hours_offset >= 0 ? "+" : "-")
239 << std::setw(2) << std::setfill('0') << std::abs(hours_offset) << ":"
240 << std::setw(2) << std::setfill('0') << std::abs(minutes_offset);
241 return oss.str();
242}
243
244
245bool
246StringUtils::startsWith(const std::string& str, const std::string prefix) {
247 return str.compare(0, prefix.length(), prefix) == 0;
248}
249
250
251bool
252StringUtils::endsWith(const std::string& str, const std::string suffix) {
253 if (str.length() >= suffix.length()) {
254 return str.compare(str.length() - suffix.length(), suffix.length(), suffix) == 0;
255 } else {
256 return false;
257 }
258}
259
260
261std::string
262StringUtils::padFront(const std::string& str, int length, char padding) {
263 return std::string(MAX2(0, length - (int)str.size()), padding) + str;
264}
265
266
267std::string
268StringUtils::escapeXML(const std::string& orig, const bool maskDoubleHyphen) {
269 std::string result = replace(orig, "&", "&amp;");
270 result = replace(result, ">", "&gt;");
271 result = replace(result, "<", "&lt;");
272 result = replace(result, "\"", "&quot;");
273 if (maskDoubleHyphen) {
274 result = replace(result, "--", "&#45;&#45;");
275 }
276 for (char invalid = '\1'; invalid < ' '; invalid++) {
277 result = replace(result, std::string(1, invalid).c_str(), "");
278 }
279 return replace(result, "'", "&apos;");
280}
281
282
283std::string
284StringUtils::escapeShell(const std::string& orig) {
285 return replace(orig, "\"", "\\\"");
286}
287
288
289std::string
290StringUtils::escapeCSV(const std::string& orig, const char separator, const char quote) {
291 const std::string chars{separator, quote};
292 if (orig.find_first_of(chars) == std::string::npos) {
293 return orig;
294 }
295 const std::string quoteStr{quote};
296 return quoteStr + replace(orig, quoteStr, {'\\', quote}) + quoteStr;
297}
298
299
300std::string
301StringUtils::urlEncode(const std::string& toEncode, const std::string encodeWhich) {
302 std::ostringstream out;
303
304 for (int i = 0; i < (int)toEncode.length(); ++i) {
305 const char t = toEncode.at(i);
306
307 if ((encodeWhich != "" && encodeWhich.find(t) == std::string::npos) ||
308 (encodeWhich == "" &&
309 ((t >= 45 && t <= 57) || // hyphen, period, slash, 0-9
310 (t >= 65 && t <= 90) || // A-Z
311 t == 95 || // underscore
312 (t >= 97 && t <= 122) || // a-z
313 t == 126)) // tilde
314 ) {
315 out << toEncode.at(i);
316 } else {
317 out << charToHex(toEncode.at(i));
318 }
319 }
320
321 return out.str();
322}
323
324
325std::string
326StringUtils::urlDecode(const std::string& toDecode) {
327 std::ostringstream out;
328
329 for (int i = 0; i < (int)toDecode.length(); ++i) {
330 if (toDecode.at(i) == '%') {
331 std::string str(toDecode.substr(i + 1, 2));
332 out << hexToChar(str);
333 i += 2;
334 } else {
335 out << toDecode.at(i);
336 }
337 }
338
339 return out.str();
340}
341
342std::string
343StringUtils::charToHex(unsigned char c) {
344 short i = c;
345
346 std::stringstream s;
347
348 s << "%" << std::setw(2) << std::setfill('0') << std::hex << i;
349
350 return s.str();
351}
352
353
354unsigned char
355StringUtils::hexToChar(const std::string& str) {
356 short c = 0;
357 if (!str.empty()) {
358 std::istringstream in(str);
359 in >> std::hex >> c;
360 if (in.fail()) {
361 throw NumberFormatException(str + " could not be interpreted as hex");
362 }
363 }
364 return static_cast<unsigned char>(c);
365}
366
367
368int
369StringUtils::toInt(const std::string& sData) {
370 long long int result = toLong(sData);
371 if (result > std::numeric_limits<int>::max() || result < std::numeric_limits<int>::min()) {
372 throw NumberFormatException(toString(result) + " int overflow");
373 }
374 return (int)result;
375}
376
377
378bool
379StringUtils::isInt(const std::string& sData) {
380 // first check if can be converted to long int
381 if (isLong(sData)) {
382 const long long int result = toLong(sData);
383 // now check if the result is in the range of an int
384 return ((result <= std::numeric_limits<int>::max()) && (result >= std::numeric_limits<int>::min()));
385 }
386 return false;
387}
388
389
390int
391StringUtils::toIntSecure(const std::string& sData, int def) {
392 if (sData.length() == 0) {
393 return def;
394 }
395 return toInt(sData);
396}
397
398
399long long int
400StringUtils::toLong(const std::string& sData) {
401 const char* const data = sData.c_str();
402 if (data == 0 || data[0] == 0) {
403 throw EmptyData();
404 }
405 char* end;
406 errno = 0;
407#ifdef _MSC_VER
408 long long int ret = _strtoi64(data, &end, 10);
409#else
410 long long int ret = strtoll(data, &end, 10);
411#endif
412 if (errno == ERANGE) {
413 errno = 0;
414 throw NumberFormatException("(long long integer range) " + sData);
415 }
416 if ((int)(end - data) != (int)strlen(data)) {
417 throw NumberFormatException("(long long integer format) " + sData);
418 }
419 return ret;
420}
421
422
423bool
424StringUtils::isLong(const std::string& sData) {
425 const char* const data = sData.c_str();
426 if (data == 0 || data[0] == 0) {
427 return false;
428 }
429 char* end;
430 // reset errno before parsing, to keep errors
431 errno = 0;
432 // continue depending of current plattform
433#ifdef _MSC_VER
434 _strtoi64(data, &end, 10);
435#else
436 strtoll(data, &end, 10);
437#endif
438 // check out of range
439 if (errno == ERANGE) {
440 return false;
441 }
442 // check length of converted data
443 if ((int)(end - data) != (int)strlen(data)) {
444 return false;
445 }
446 return true;
447}
448
449
450int
451StringUtils::hexToInt(const std::string& sData) {
452 if (sData.length() == 0) {
453 throw EmptyData();
454 }
455 size_t idx = 0;
456 int result;
457 try {
458 if (sData[0] == '#') { // for html color codes
459 result = std::stoi(sData.substr(1), &idx, 16);
460 idx++;
461 } else {
462 result = std::stoi(sData, &idx, 16);
463 }
464 } catch (...) {
465 throw NumberFormatException("(hex integer format) " + sData);
466 }
467 if (idx != sData.length()) {
468 throw NumberFormatException("(hex integer format) " + sData);
469 }
470 return result;
471}
472
473
474bool
475StringUtils::isHex(std::string sData) {
476 if (sData.length() == 0) {
477 return false;
478 }
479 // remove the first character (for HTML color codes)
480 if (sData[0] == '#') {
481 sData = sData.substr(1);
482 }
483 const char* sDataPtr = sData.c_str();
484 char* returnPtr;
485 // reset errno
486 errno = 0;
487 // call string to long (size 16) from standard library
488 strtol(sDataPtr, &returnPtr, 16);
489 // check out of range
490 if (errno == ERANGE) {
491 return false;
492 }
493 // check if there was an error converting sDataPtr to double,
494 if (sDataPtr == returnPtr) {
495 return false;
496 }
497 // compare size of start and end points
498 if (static_cast<size_t>(returnPtr - sDataPtr) != sData.size()) {
499 return false;
500 }
501 return true;
502}
503
504
505double
506StringUtils::toDouble(const std::string& sData) {
507 if (sData.size() == 0) {
508 throw EmptyData();
509 }
510 try {
511 size_t idx = 0;
512 const double result = std::stod(sData, &idx);
513 if (idx != sData.size()) {
514 throw NumberFormatException("(double format) " + sData);
515 } else {
516 return result;
517 }
518 } catch (...) {
519 // invalid_argument or out_of_range
520 throw NumberFormatException("(double) " + sData);
521 }
522}
523
524
525bool
526StringUtils::isDouble(const std::string& sData) {
527 if (sData.size() == 0) {
528 return false;
529 }
530 const char* sDataPtr = sData.c_str();
531 char* returnPtr;
532 // reset errno
533 errno = 0;
534 // call string to double from standard library
535 strtod(sDataPtr, &returnPtr);
536 // check out of range
537 if (errno == ERANGE) {
538 return false;
539 }
540 // check if there was an error converting sDataPtr to double,
541 if (sDataPtr == returnPtr) {
542 return false;
543 }
544 // compare size of start and end points
545 if (static_cast<size_t>(returnPtr - sDataPtr) != sData.size()) {
546 return false;
547 }
548 return true;
549}
550
551
552double
553StringUtils::toDoubleSecure(const std::string& sData, const double def) {
554 if (sData.length() == 0) {
555 return def;
556 }
557 return toDouble(sData);
558}
559
560
561double
562StringUtils::toDoubleAllowTime(const std::string& sData) {
563 if (sData.find(":") == std::string::npos) {
564 return toDouble(sData);
565 } else if (isTime(sData)) {
566 return STEPS2TIME(string2time(sData));
567 }
568 throw NumberFormatException("(double) " + sData);
569}
570
571bool
572StringUtils::toBool(const std::string& sData) {
573 if (sData.length() == 0) {
574 throw EmptyData();
575 }
576 const std::string s = to_lower_case(sData);
577 if (s == "1" || s == "yes" || s == "true" || s == "on" || s == "x" || s == "t") {
578 return true;
579 }
580 if (s == "0" || s == "no" || s == "false" || s == "off" || s == "-" || s == "f") {
581 return false;
582 }
583 throw BoolFormatException(s);
584}
585
586
587bool
588StringUtils::isBool(const std::string& sData) {
589 if (sData.length() == 0) {
590 return false;
591 }
592 const std::string s = to_lower_case(sData);
593 // check true values
594 if (s == "1" || s == "yes" || s == "true" || s == "on" || s == "x" || s == "t") {
595 return true;
596 }
597 // check false values
598 if (s == "0" || s == "no" || s == "false" || s == "off" || s == "-" || s == "f") {
599 return true;
600 }
601 // no valid true or false values
602 return false;
603}
604
605
607StringUtils::toVersion(const std::string& sData) {
608 std::vector<std::string> parts = StringTokenizer(sData, ".").getVector();
609 return MMVersion(toInt(parts.front()), toDouble(parts.back()));
610}
611
612
613double
614StringUtils::parseDist(const std::string& sData) {
615 if (sData.size() == 0) {
616 throw EmptyData();
617 }
618 try {
619 size_t idx = 0;
620 const double result = std::stod(sData, &idx);
621 if (idx != sData.size()) {
622 const std::string unit = prune(sData.substr(idx));
623 if (unit == "m" || unit == "metre" || unit == "meter" || unit == "metres" || unit == "meters") {
624 return result;
625 }
626 if (unit == "km" || unit == "kilometre" || unit == "kilometer" || unit == "kilometres" || unit == "kilometers") {
627 return result * 1000.;
628 }
629 if (unit == "mi" || unit == "mile" || unit == "miles") {
630 return result * 1000. * KM_PER_MILE;
631 }
632 if (unit == "nmi") {
633 return result * 1852.;
634 }
635 if (unit == "ft" || unit == "foot" || unit == "feet") {
636 return result * 12. * 0.0254;
637 }
638 if (unit == "\"" || unit == "in" || unit == "inch" || unit == "inches") {
639 return result * 0.0254;
640 }
641 if (unit[0] == '\'') {
642 double inches = 12 * result;
643 if (unit.length() > 1) {
644 inches += std::stod(unit.substr(1), &idx);
645 if (unit.substr(idx) == "\"") {
646 return inches * 0.0254;
647 }
648 }
649 }
650 throw NumberFormatException("(distance format) " + sData);
651 } else {
652 return result;
653 }
654 } catch (...) {
655 // invalid_argument or out_of_range
656 throw NumberFormatException("(double) " + sData);
657 }
658}
659
660
661double
662StringUtils::parseSpeed(const std::string& sData, const bool defaultKmph) {
663 if (sData.size() == 0) {
664 throw EmptyData();
665 }
666 try {
667 size_t idx = 0;
668 const double result = std::stod(sData, &idx);
669 if (idx != sData.size()) {
670 const std::string unit = to_lower_case(prune(sData.substr(idx)));
671 if (unit == "km/h" || unit == "kph" || unit == "kmh" || unit == "kmph") {
672 return result / 3.6;
673 }
674 if (unit == "m/s") {
675 return result;
676 }
677 if (unit == "mph") {
678 return result * KM_PER_MILE / 3.6;
679 }
680 if (unit == "knots" || unit == "knot" || unit == "kts" || unit == "kt") {
681 return result * 1.852 / 3.6;
682 }
683 throw NumberFormatException("(speed format) " + sData);
684 } else {
685 return defaultKmph ? result / 3.6 : result;
686 }
687 } catch (...) {
688 // invalid_argument or out_of_range
689 throw NumberFormatException("(double) " + sData);
690 }
691}
692
693
694
695std::string
696StringUtils::trim_left(const std::string s, const std::string& t) {
697 std::string result = s;
698 result.erase(0, s.find_first_not_of(t));
699 return result;
700}
701
702std::string
703StringUtils::trim_right(const std::string s, const std::string& t) {
704 std::string result = s;
705 result.erase(s.find_last_not_of(t) + 1);
706 return result;
707}
708
709std::string
710StringUtils::trim(const std::string s, const std::string& t) {
711 return trim_right(trim_left(s, t), t);
712}
713
714
715std::string
716StringUtils::wrapText(const std::string s, int width) {
717 std::vector<std::string> parts = StringTokenizer(s).getVector();
718 std::string result;
719 std::string line;
720 bool firstLine = true;
721 bool firstWord = true;
722 for (std::string p : parts) {
723 if ((int)(line.size() + p.size()) < width || firstWord) {
724 if (firstWord) {
725 firstWord = false;
726 } else {
727 line += " ";
728 }
729 line += p;
730 } else {
731 if (firstLine) {
732 firstLine = false;
733 } else {
734 result += "\n";
735 }
736 result += line;
737 line.clear();
738 line += p;
739 }
740 }
741 if (line.size() > 0) {
742 if (firstLine) {
743 firstLine = false;
744 } else {
745 result += "\n";
746 }
747 result += line;
748 }
749 return result;
750}
751
752
753std::string
754StringUtils::adjustDecimalValue(double value, int precision) {
755 // obtain value in string format with 20 decimals precision
756 auto valueStr = toString(value, precision);
757 // now clear all zeros
758 while (valueStr.size() > 1) {
759 if (valueStr.back() == '0') {
760 valueStr.pop_back();
761 } else if (valueStr.back() == '.') {
762 valueStr.pop_back();
763 return valueStr;
764 } else {
765 return valueStr;
766 }
767 }
768 return valueStr;
769}
770
771
772bool
773StringUtils::isValidNetID(const std::string& value) {
774 return (value.size() > 0) && value.find_first_of(" \t\n\r|\\'\";,<>&") == std::string::npos && value[0] != ':';
775}
776
777
778bool
779StringUtils::isValidVehicleID(const std::string& value) {
780 return (value.size() > 0) && value.find_first_of(" \t\n\r|\\'\";,<>&") == std::string::npos;
781}
782
783
784bool
785StringUtils::isValidTypeID(const std::string& value) {
786 return (value.size() > 0) && value.find_first_of(" \t\n\r|\\'\";,<>&") == std::string::npos;
787}
788
789
790bool
791StringUtils::isValidAdditionalID(const std::string& value) {
792 return (value.size() > 0) && value.find_first_of(" \t\n\r|\\'\";,<>&") == std::string::npos;
793}
794
795
796bool
797StringUtils::isValidDetectorID(const std::string& value) {
798 // special case: ' ' allowed
799 return (value.size() > 0) && value.find_first_of("\t\n\r|\\'\";,<>&") == std::string::npos;
800}
801
802
803bool
804StringUtils::isValidAttribute(const std::string& value) {
805 return value.find_first_of("\t\n\r&|\\'\"<>") == std::string::npos;
806}
807
808
809bool
810StringUtils::isValidFilename(const std::string& value) {
811 return (value.find_first_of("\t\n\r@$%^&|{}*'\";<>") == std::string::npos);
812}
813
814
815bool
816StringUtils::isValidListOfNetIDs(const std::string& value) {
817 const std::vector<std::string>& typeIDs = StringTokenizer(value).getVector();
818 if (typeIDs.empty()) {
819 return false;
820 } else {
821 // check that gives IDs are valid
822 for (auto i : typeIDs) {
823 if (!isValidNetID(i)) {
824 return false;
825 }
826 }
827 return true;
828 }
829}
830
831
832bool
833StringUtils::isValidListOfTypeID(const std::string& value) {
834 return isValidListOfTypeID(StringTokenizer(value).getVector());
835}
836
837
838bool
839StringUtils::isValidListOfTypeID(const std::vector<std::string>& typeIDs) {
840 if (typeIDs.empty()) {
841 return false;
842 } else {
843 // check that gives IDs are valid
844 for (const auto& typeID : typeIDs) {
845 if (!isValidTypeID(typeID)) {
846 return false;
847 }
848 }
849 return true;
850 }
851}
852
853
854bool
855StringUtils::isValidParameterKey(const std::string& value) {
856 // Generic parameters keys cannot be empty
857 if (value.empty()) {
858 return false;
859 } else {
860 return isValidAttribute(value);
861 }
862}
863
864
865std::string
866StringUtils::makeValidID(const std::string& value) {
867 if (value.empty()) {
868 return "_";
869 }
870 std::string result(value);
871 if (result[0] == ':') {
872 result[0] = '_';
873 }
874 for (const char c : " \t\n\r|\\'\";,<>&") {
875 std::replace(result.begin(), result.end(), c, '_');
876 }
877 return result;
878}
879
880
881std::string
882StringUtils::transcodeLocal(const std::string& str, bool toLocal) {
883#ifdef WIN32
884 if (str.empty()) {
885 return str;
886 }
887 const UINT fromCodepage = toLocal ? CP_UTF8 : CP_ACP;
888 const UINT toCodepage = toLocal ? CP_ACP : CP_UTF8;
889 const int wideSize = MultiByteToWideChar(fromCodepage, 0, str.c_str(), (int)str.size(), nullptr, 0);
890 if (wideSize <= 0) {
891 return str;
892 }
893 std::wstring wide(wideSize, L'\0');
894 MultiByteToWideChar(fromCodepage, 0, str.c_str(), (int)str.size(), &wide[0], wideSize);
895 const int resultSize = WideCharToMultiByte(toCodepage, 0, wide.c_str(), wideSize, nullptr, 0, nullptr, nullptr);
896 if (resultSize <= 0) {
897 return str;
898 }
899 std::string result(resultSize, '\0');
900 WideCharToMultiByte(toCodepage, 0, wide.c_str(), wideSize, &result[0], resultSize, nullptr, nullptr);
901 return result;
902#else
903 UNUSED_PARAMETER(toLocal);
904 return str;
905#endif
906}
907
908
909/****************************************************************************/
SUMOTime string2time(const std::string &r)
convert string to SUMOTime
Definition SUMOTime.cpp:47
bool isTime(const std::string &r)
check if the given string is a valid time
Definition SUMOTime.cpp:70
#define STEPS2TIME(x)
Definition SUMOTime.h:58
std::pair< int, double > MMVersion
(M)ajor/(M)inor version for written networks and default version for loading
Definition StdDefs.h:71
T MAX2(T a, T b)
Definition StdDefs.h:86
#define KM_PER_MILE
std::string toString(const T &t, std::streamsize accuracy=gPrecision)
Definition ToString.h:57
std::vector< std::string > getVector()
return vector of strings
static std::string pruneZeros(const std::string &str, int max)
Removes trailing zeros (at most 'max')
static std::string urlEncode(const std::string &url, const std::string encodeWhich="")
encode url (stem from http://bogomip.net/blog/cpp-url-encoding-and-decoding/)
static bool isDouble(const std::string &sData)
check if the given sData can be conveted to double
static MMVersion toVersion(const std::string &sData)
parse a (network) version string
static bool isBool(const std::string &sData)
check if the given value can be converted to bool
static std::string to_upper_case(const std::string &str)
Transfers the content to upper case.
static std::string transcodeLocal(const std::string &str, bool toLocal)
convert a string between UTF-8 and the local codepage (identity on non-Windows systems)
static std::string charToHex(unsigned char c)
char to hexadecimal
static std::string urlDecode(const std::string &encoded)
decode url (stem from http://bogomip.net/blog/cpp-url-encoding-and-decoding/)
static long long int toLong(const std::string &sData)
converts a string into the long value described by it by calling the char-type converter,...
static double toDoubleSecure(const std::string &sData, const double def)
converts a string into the integer value described by it
static std::string makeValidID(const std::string &value)
transform the given string into a valid id for a network element (or any other id)
static std::string trim(const std::string s, const std::string &t=" \t\n")
remove leading and trailing whitespace
static std::string to_lower_case(const std::string &str)
Transfers the content to lower case.
static bool isValidParameterKey(const std::string &value)
whether the given string is a valid key for a parameter
static std::string trim_right(const std::string s, const std::string &t=" \t\n")
remove trailing whitespace from string
static bool isValidNetID(const std::string &value)
whether the given string is a valid id for a network element
static std::string trim_left(const std::string s, const std::string &t=" \t\n")
remove leading whitespace from string
static bool isValidListOfTypeID(const std::string &value)
whether the given string is a valid list of ids for an edge or vehicle type (empty aren't allowed)
static std::string escapeShell(const std::string &orig)
Escape special characters with backslash.
static std::string replace(std::string str, const std::string &what, const std::string &by)
Replaces all occurrences of the second string by the third string within the first string.
static int hexToInt(const std::string &sData)
converts a string with a hex value into the integer value described by it by calling the char-type co...
static double toDouble(const std::string &sData)
converts a string into the double value described by it by calling the char-type converter
static bool isValidVehicleID(const std::string &value)
whether the given string is a valid id for a vehicle or flow
static std::string escapeXML(const std::string &orig, const bool maskDoubleHyphen=false)
Replaces the standard escapes by their XML entities.
static bool isValidDetectorID(const std::string &value)
whether the given string is a valid id for an detector
static bool isHex(std::string sData)
check if the given string can be converted to hex
static bool isValidAdditionalID(const std::string &value)
whether the given string is a valid id for an additional object
static std::string latin1_to_utf8(std::string str)
Transfers from Latin 1 (ISO-8859-1) to UTF-8.
static std::string prune(const std::string &str)
Removes trailing and leading whitechars.
static std::string padFront(const std::string &str, int length, char padding)
static std::string convertUmlaute(std::string str)
Converts german "Umlaute" to their latin-version.
static bool isValidFilename(const std::string &value)
whether the given string is a valid attribute for a filename (for example, a name)
static double parseDist(const std::string &sData)
parse a distance, length or width value with a unit
static std::string adjustDecimalValue(double value, int precision)
write with maximum precision if needed but remove trailing zeros
static unsigned char hexToChar(const std::string &str)
hexadecimal to char
static bool startsWith(const std::string &str, const std::string prefix)
Checks whether a given string starts with the prefix.
static std::string wrapText(const std::string s, int width)
remove leading and trailing whitespace
static double parseSpeed(const std::string &sData, const bool defaultKmph=true)
parse a speed value with a unit
static double toDoubleAllowTime(const std::string &sData)
converts a string into a double value. Values in human-readable-time format (see string2time) are per...
static std::string emptyString
An empty string.
static bool endsWith(const std::string &str, const std::string suffix)
Checks whether a given string ends with the suffix.
static std::string substituteEnvironment(const std::string &str, const std::chrono::time_point< std::chrono::system_clock > *const timeRef=nullptr)
Replaces an environment variable with its value (similar to bash); syntax for a variable is ${NAME}.
static bool isLong(const std::string &sData)
Check if the given sData can be converted to long.
static int toIntSecure(const std::string &sData, int def)
converts a string into the integer value described by it
static std::string isoTimeString(const std::chrono::time_point< std::chrono::system_clock > *const timeRef=nullptr)
Returns an ISO8601 formatted time string with microsecond precision.
static std::string escapeCSV(const std::string &orig, const char separator, const char quote='"')
Adds quotes to strings containing the separator or the quote char and escapes the quote char with a b...
static bool isValidListOfNetIDs(const std::string &value)
whether the given string is a valid list of id for a network (empty aren't allowed)
static bool isValidAttribute(const std::string &value)
whether the given string is a valid attribute for a certain key (for example, a name)
static int toInt(const std::string &sData)
converts a string into the integer value described by it by calling the char-type converter,...
static bool isValidTypeID(const std::string &value)
whether the given string is a valid id for an edge or vehicle type
static bool isInt(const std::string &sData)
check if the given sData can be converted to int
static bool toBool(const std::string &sData)
converts a string into the bool value described by it by calling the char-type converter
#define UNUSED_PARAMETER(x)