1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728
|
#ifndef CONVERSION_UTILITIES_STRINGCONVERSION_H
#define CONVERSION_UTILITIES_STRINGCONVERSION_H
#include "./binaryconversion.h"
#include "./conversionexception.h"
#include "../misc/traits.h"
#include <cstdlib>
#include <cstring>
#include <initializer_list>
#include <iomanip>
#include <list>
#include <memory>
#include <sstream>
#include <string>
#include <string_view>
#include <system_error>
#include <vector>
#if __cplusplus >= 201709 && !defined(REFLECTIVE_RAPIDJSON_GENERATOR)
#ifndef CPP_UTILITIES_USE_RANGES
#define CPP_UTILITIES_USE_RANGES
#endif
#include <ranges>
#endif
namespace CppUtilities {
// clang-format off
/*!
* \brief The StringDataDeleter struct deletes the data of a StringData instance.
*/
struct CPP_UTILITIES_EXPORT StringDataDeleter{ /*!
* \brief Deletes the specified \a stringData with std::free(), because the memory has been
* allocated using std::malloc()/std::realloc().
*/
void operator()(char *stringData){ std::free(stringData); }
};
// clang-format on
/*!
* \brief Type used to return string encoding conversion result.
*/
using StringData = std::pair<std::unique_ptr<char[], StringDataDeleter>, std::size_t>;
//using StringData = std::pair<std::unique_ptr<char>, std::size_t>; // might work too
#ifndef CPP_UTILITIES_NO_ICONV
CPP_UTILITIES_EXPORT StringData convertString(
const char *fromCharset, const char *toCharset, const char *inputBuffer, std::size_t inputBufferSize, float outputBufferSizeFactor = 1.0f);
CPP_UTILITIES_EXPORT StringData convertUtf8ToUtf16LE(const char *inputBuffer, std::size_t inputBufferSize);
CPP_UTILITIES_EXPORT StringData convertUtf16LEToUtf8(const char *inputBuffer, std::size_t inputBufferSize);
CPP_UTILITIES_EXPORT StringData convertUtf8ToUtf16BE(const char *inputBuffer, std::size_t inputBufferSize);
CPP_UTILITIES_EXPORT StringData convertUtf16BEToUtf8(const char *inputBuffer, std::size_t inputBufferSize);
CPP_UTILITIES_EXPORT StringData convertLatin1ToUtf8(const char *inputBuffer, std::size_t inputBufferSize);
CPP_UTILITIES_EXPORT StringData convertUtf8ToLatin1(const char *inputBuffer, std::size_t inputBufferSize);
#endif
#ifdef PLATFORM_WINDOWS
using WideStringData = std::pair<std::unique_ptr<wchar_t[]>, int>;
CPP_UTILITIES_EXPORT std::wstring convertMultiByteToWide(std::error_code &ec, std::string_view inputBuffer);
CPP_UTILITIES_EXPORT WideStringData convertMultiByteToWide(std::error_code &ec, const char *inputBuffer, int inputBufferSize = -1);
CPP_UTILITIES_EXPORT WideStringData convertMultiByteToWide(std::error_code &ec, const std::string &inputBuffer);
CPP_UTILITIES_EXPORT WideStringData convertMultiByteToWide(const char *inputBuffer, int inputBufferSize = -1);
CPP_UTILITIES_EXPORT WideStringData convertMultiByteToWide(const std::string &inputBuffer);
#endif
CPP_UTILITIES_EXPORT void truncateString(std::string &str, char terminationChar = '\0');
/// \cond
namespace Detail {
#ifdef CPP_UTILITIES_USE_RANGES
template <class Container>
using ContainerValueType = typename std::conditional_t<std::ranges::range<Container>,
std::iterator_traits<std::remove_cvref_t<std::ranges::iterator_t<Container>>>, Container>::value_type;
#else
template <class Container> using ContainerValueType = typename Container::value_type;
#endif
template <class Container> using DefaultReturnTypeForContainer = ContainerValueType<Container>;
template <class Container> using StringParamForContainer = std::basic_string_view<typename ContainerValueType<Container>::value_type>;
} // namespace Detail
/// \endcond
/*!
* \brief Joins the given \a strings using the specified \a delimiter.
*
* The strings will be enclosed using the provided closures \a leftClosure and \a rightClosure.
*
* \param strings The string parts to be joined.
* \param delimiter Specifies a delimiter to be used (empty string by default).
* \param omitEmpty Indicates whether empty part should be omitted.
* \param leftClosure Specifies a string to be inserted before each string (empty string by default).
* \param rightClosure Specifies a string to be appended after each string (empty string by default).
* \tparam Container Container The STL-container used to provide the \a strings.
* \tparam ReturnType Type to store the result; defaults to the container's element type.
* \returns Returns the joined string.
*/
template <class Container = std::initializer_list<std::string>, class ReturnType = Detail::DefaultReturnTypeForContainer<Container>>
ReturnType joinStrings(const Container &strings, Detail::StringParamForContainer<Container> delimiter = Detail::StringParamForContainer<Container>(),
bool omitEmpty = false, Detail::StringParamForContainer<Container> leftClosure = Detail::StringParamForContainer<Container>(),
Detail::StringParamForContainer<Container> rightClosure = Detail::StringParamForContainer<Container>())
{
ReturnType res;
if (!strings.size()) {
return res;
}
std::size_t entries = 0, size = 0;
for (const auto &str : strings) {
if (omitEmpty && str.empty()) {
continue;
}
size += str.size();
++entries;
}
if (!entries) {
return res;
}
size += (entries * leftClosure.size()) + (entries * rightClosure.size()) + ((entries - 1) * delimiter.size());
res.reserve(size);
for (const auto &str : strings) {
if (omitEmpty && str.empty()) {
continue;
}
if (!res.empty()) {
res.append(delimiter);
}
res.append(leftClosure);
res.append(str);
res.append(rightClosure);
}
return res;
}
/*!
* \brief Converts the specified \a arrayOfLines to a multiline string.
*/
template <class Container = std::initializer_list<std::string>> inline auto toMultiline(const Container &arrayOfLines)
{
return joinStrings(arrayOfLines, "\n", false);
}
/*!
* \brief Specifies the role of empty parts when splitting strings.
*/
enum class EmptyPartsTreat {
Keep, /**< empty parts are kept */
Omit, /**< empty parts are omitted */
Merge /**< empty parts are omitted but cause the adjacent parts being joined using the delimiter */
};
/*!
* \brief Splits the given \a string at the specified \a delimiter.
* \param string The string to be split.
* \param delimiter Specifies the delimiter which must not be empty.
* \param emptyPartsRole Specifies the treatment of empty parts.
* \param maxParts Specifies the maximal number of parts. Values less or equal zero indicate an unlimited number of parts.
* \tparam Container The STL-container used to return the parts.
* \returns Returns the parts.
*/
template <class Container = std::list<std::string>>
Container splitString(Detail::StringParamForContainer<Container> string, Detail::StringParamForContainer<Container> delimiter,
EmptyPartsTreat emptyPartsRole = EmptyPartsTreat::Keep, int maxParts = -1)
{
--maxParts;
Container res;
typename Container::value_type *last = nullptr;
bool merge = false;
typename Container::value_type::size_type i = 0, end = string.size();
for (typename Container::value_type::size_type delimPos; i < end; i = delimPos + delimiter.size()) {
delimPos = string.find(delimiter, i);
if (!merge && maxParts >= 0 && res.size() == static_cast<typename Container::value_type::size_type>(maxParts)) {
if (delimPos == i && emptyPartsRole == EmptyPartsTreat::Merge) {
if (last) {
merge = true;
continue;
}
}
delimPos = Container::value_type::npos;
}
if (delimPos == Container::value_type::npos) {
delimPos = string.size();
}
if (emptyPartsRole == EmptyPartsTreat::Keep || i != delimPos) {
if (merge) {
last->append(delimiter);
last->append(string, i, delimPos - i);
merge = false;
} else {
last = &res.emplace_back(string, i, delimPos - i);
}
} else if (emptyPartsRole == EmptyPartsTreat::Merge) {
if (last) {
merge = true;
}
}
}
if (i == end && emptyPartsRole == EmptyPartsTreat::Keep) {
res.emplace_back();
}
return res;
}
/*!
* \brief Splits the given \a string (which might also be a string view) at the specified \a delimiter.
* \param string The string to be split.
* \param delimiter Specifies the delimiter which must not be empty.
* \param maxParts Specifies the maximal number of parts. Values less or equal zero indicate an unlimited number of parts.
* \tparam Container The STL-container used to return the parts.
* \returns Returns the parts.
* \remarks This is a simplified version of splitString() where emptyPartsRole is always EmptyPartsTreat::Keep.
*/
template <class Container = std::list<std::string>>
Container splitStringSimple(
Detail::StringParamForContainer<Container> string, Detail::StringParamForContainer<Container> delimiter, int maxParts = -1)
{
--maxParts;
Container res;
typename Container::value_type::size_type i = 0, end = string.size();
for (typename Container::value_type::size_type delimPos; i < end; i = delimPos + delimiter.size()) {
delimPos = string.find(delimiter, i);
if (maxParts >= 0 && res.size() == static_cast<typename Container::value_type::size_type>(maxParts)) {
delimPos = Container::value_type::npos;
}
if (delimPos == Container::value_type::npos) {
delimPos = string.size();
}
#if __cplusplus >= 201709
if constexpr (requires { res.emplace_back(string); }) {
#endif
res.emplace_back(string.data() + i, delimPos - i);
#if __cplusplus >= 201709
} else {
res.emplace(string.data() + i, delimPos - i);
}
#endif
}
if (i == end) {
#if __cplusplus >= 201709
if constexpr (requires { res.emplace_back(); }) {
#endif
res.emplace_back();
#if __cplusplus >= 201709
} else {
res.emplace();
}
#endif
}
return res;
}
/*!
* \brief Converts the specified \a multilineString to an array of lines.
*/
template <class Container = std::vector<std::string>> inline auto toArrayOfLines(const std::string &multilineString)
{
return splitString<Container>(multilineString, "\n", EmptyPartsTreat::Keep);
}
/*!
* \brief Returns whether \a str starts with \a phrase.
*/
template <typename StringType> bool startsWith(const StringType &str, const StringType &phrase)
{
if (str.size() < phrase.size()) {
return false;
}
for (auto stri = str.cbegin(), strend = str.cend(), phrasei = phrase.cbegin(), phraseend = phrase.cend();; ++stri, ++phrasei) {
if (phrasei == phraseend) {
return true;
} else if (stri == strend) {
return false;
} else if (*stri != *phrasei) {
return false;
}
}
return false;
}
/*!
* \brief Returns whether \a str starts with \a phrase.
*/
template <typename StringType> bool startsWith(const StringType &str, const typename StringType::value_type *phrase)
{
for (auto stri = str.cbegin(), strend = str.cend();; ++stri, ++phrase) {
if (!*phrase) {
return true;
} else if (stri == strend) {
return false;
} else if (*stri != *phrase) {
return false;
}
}
return false;
}
/*!
* \brief Returns whether \a str ends with \a phrase.
*/
template <typename StringType> bool endsWith(const StringType &str, const StringType &phrase)
{
if (str.size() < phrase.size()) {
return false;
}
for (auto stri = str.cend() - static_cast<typename StringType::difference_type>(phrase.size()), strend = str.cend(), phrasei = phrase.cbegin();
stri != strend; ++stri, ++phrasei) {
if (*stri != *phrasei) {
return false;
}
}
return true;
}
/*!
* \brief Returns whether \a str ends with \a phrase.
*/
template <typename StringType> bool endsWith(const StringType &str, const typename StringType::value_type *phrase)
{
const auto phraseSize = std::strlen(phrase);
if (str.size() < phraseSize) {
return false;
}
for (auto stri = str.cend() - static_cast<typename StringType::difference_type>(phraseSize), strend = str.cend(); stri != strend;
++stri, ++phrase) {
if (*stri != *phrase) {
return false;
}
}
return true;
}
/*!
* \brief Returns whether \a str contains the specified \a substrings.
* \remarks The \a substrings must occur in the specified order.
*/
template <typename StringType> bool containsSubstrings(const StringType &str, std::initializer_list<StringType> substrings)
{
typename StringType::size_type currentPos = 0;
for (const auto &substr : substrings) {
if ((currentPos = str.find(substr, currentPos)) == StringType::npos) {
return false;
}
currentPos += substr.size();
}
return true;
}
/*!
* \brief Returns whether \a str contains the specified \a substrings.
* \remarks The \a substrings must occur in the specified order.
*/
template <typename StringType>
bool containsSubstrings(const StringType &str, std::initializer_list<const typename StringType::value_type *> substrings)
{
typename StringType::size_type currentPos = 0;
for (const auto *substr : substrings) {
if ((currentPos = str.find(substr, currentPos)) == StringType::npos) {
return false;
}
currentPos += std::strlen(substr);
}
return true;
}
/*!
* \brief Replaces all occurrences of \a find with \a relpace in the specified \a str.
*/
template <typename StringType1, typename StringType2, typename StringType3>
void findAndReplace(StringType1 &str, const StringType2 &find, const StringType3 &replace)
{
for (typename StringType1::size_type i = 0; (i = str.find(find, i)) != StringType1::npos; i += replace.size()) {
str.replace(i, find.size(), replace);
}
}
/*!
* \brief Replaces all occurrences of \a find with \a relpace in the specified \a str.
*/
template <typename StringType>
inline void findAndReplace(StringType &str, const typename StringType::value_type *find, const typename StringType::value_type *replace)
{
findAndReplace(
str, std::basic_string_view<typename StringType::value_type>(find), std::basic_string_view<typename StringType::value_type>(replace));
}
/*!
* \brief Replaces all occurrences of \a find with \a relpace in the specified \a str.
*/
template <typename StringType1, typename StringType2>
inline void findAndReplace(StringType1 &str, const StringType2 &find, const typename StringType1::value_type *replace)
{
findAndReplace(str, find, std::basic_string_view<typename StringType1::value_type>(replace));
}
/*!
* \brief Replaces all occurrences of \a find with \a relpace in the specified \a str.
*/
template <typename StringType1, typename StringType2>
inline void findAndReplace(StringType1 &str, const typename StringType1::value_type *find, const StringType2 &replace)
{
findAndReplace(str, std::basic_string_view<typename StringType1::value_type>(find), replace);
}
/*!
* \brief Returns the character representation of the specified \a digit.
* \remarks
* - Uses capital letters.
* - Valid values for \a digit: 0 <= \a digit <= 35
*/
template <typename CharType> constexpr CharType digitToChar(CharType digit)
{
return digit <= 9 ? (digit + '0') : (digit + 'A' - 10);
}
/*!
* \brief Converts the given \a number to its equivalent string representation using the specified \a base.
* \tparam IntegralType The data type of the given number.
* \tparam StringType The string type (should be an instantiation of the basic_string class template).
* \sa stringToNumber()
*/
template <typename IntegralType, class StringType = std::string, typename BaseType = IntegralType,
CppUtilities::Traits::EnableIf<std::is_integral<IntegralType>, std::is_unsigned<IntegralType>> * = nullptr>
StringType numberToString(IntegralType number, BaseType base = 10)
{
auto resSize = std::size_t();
auto n = number;
do {
n /= static_cast<IntegralType>(base), ++resSize;
} while (n);
auto res = StringType(resSize, typename StringType::value_type());
auto resIter = res.end();
do {
*(--resIter)
= digitToChar<typename StringType::value_type>(static_cast<typename StringType::value_type>(number % static_cast<IntegralType>(base)));
number /= static_cast<IntegralType>(base);
} while (number);
return res;
}
/*!
* \brief Converts the given \a number to its equivalent string representation using the specified \a base.
* \tparam IntegralType The data type of the given number.
* \tparam StringType The string type (should be an instantiation of the basic_string class template).
* \sa stringToNumber()
*/
template <typename IntegralType, class StringType = std::string, typename BaseType = IntegralType,
Traits::EnableIf<std::is_integral<IntegralType>, std::is_signed<IntegralType>> * = nullptr>
StringType numberToString(IntegralType number, BaseType base = 10)
{
const auto negative = number < 0;
auto resSize = std::size_t();
if (negative) {
number = -number, resSize = 1;
}
auto n = number;
do {
n /= static_cast<IntegralType>(base), ++resSize;
} while (n);
auto res = StringType(resSize, typename StringType::value_type());
auto resIter = res.end();
do {
*(--resIter)
= digitToChar<typename StringType::value_type>(static_cast<typename StringType::value_type>(number % static_cast<IntegralType>(base)));
number /= static_cast<IntegralType>(base);
} while (number);
if (negative) {
*(--resIter) = '-';
}
return res;
}
/*!
* \brief Converts the given \a number to its equivalent string representation using the specified \a base.
* \tparam FloatingType The data type of the given number.
* \tparam StringType The string type (should be an instantiation of the basic_string class template).
* \remarks This function is using std::basic_stringstream internally and hence also has its limitations (eg. regarding
* \a base and types).
* \sa stringToNumber(), bufferToNumber()
*/
template <typename FloatingType, class StringType = std::string, Traits::EnableIf<std::is_floating_point<FloatingType>> * = nullptr>
StringType numberToString(FloatingType number, int base = 10)
{
std::basic_stringstream<typename StringType::value_type> ss;
ss << std::setbase(base) << number;
return ss.str();
}
/*!
* \brief Returns number/digit of the specified \a character representation using the specified \a base.
* \throws A ConversionException will be thrown if the provided \a character does not represent a valid digit for the specified \a base.
*/
template <typename CharType> CharType charToDigit(CharType character, CharType base)
{
auto res = base;
if (character >= '0' && character <= '9') {
res = character - '0';
} else if (character >= 'a' && character <= 'z') {
res = character - 'a' + 10;
} else if (character >= 'A' && character <= 'Z') {
res = character - 'A' + 10;
}
if (res < base) {
return res;
}
constexpr auto msgBegin = std::string_view("The character \"");
constexpr auto msgEnd = std::string_view("\" is no valid digit.");
auto errorMsg = std::string();
errorMsg.reserve(msgBegin.size() + msgEnd.size() + 2);
errorMsg += msgBegin;
errorMsg += character >= ' ' && character <= '~' ? static_cast<std::string::value_type>(character) : '?';
errorMsg += msgEnd;
throw ConversionException(std::move(errorMsg));
}
/// \cond
namespace Detail {
template <typename IntegralType, typename CharType, typename BaseType = IntegralType>
void raiseAndAdd(IntegralType &result, BaseType base, CharType character)
{
if (character == ' ') {
return;
}
#ifdef __GNUC__ // overflow detection only supported on GCC and Clang
if (__builtin_mul_overflow(result, base, &result)
|| __builtin_add_overflow(result, charToDigit(character, static_cast<CharType>(base)), &result)) {
throw ConversionException("Number exceeds limit.");
}
#else
result *= static_cast<IntegralType>(base);
result += static_cast<IntegralType>(charToDigit<CharType>(character, static_cast<CharType>(base)));
#endif
}
} // namespace Detail
/// \endcond
/*!
* \brief Converts the given \a string of \a size characters to an unsigned numeric value using the specified \a base.
* \tparam IntegralType The data type used to store the converted value.
* \tparam CharType The character type.
* \throws A ConversionException will be thrown if the provided \a string is not a valid number.
* \sa numberToString(), stringToNumber()
*/
template <typename IntegralType, class CharType, typename BaseType = IntegralType,
Traits::EnableIf<std::is_integral<IntegralType>, std::is_unsigned<IntegralType>> * = nullptr>
IntegralType bufferToNumber(const CharType *string, std::size_t size, BaseType base = 10)
{
IntegralType result = 0;
for (const CharType *end = string + size; string != end; ++string) {
Detail::raiseAndAdd(result, base, *string);
}
return result;
}
/*!
* \brief Converts the given \a string of \a size characters to a signed numeric value using the specified \a base.
* \tparam IntegralType The data type used to store the converted value.
* \tparam CharType The character type.
* \throws A ConversionException will be thrown if the provided \a string is not a valid number.
* \sa numberToString(), stringToNumber()
*/
template <typename IntegralType, typename CharType, typename BaseType = IntegralType,
Traits::EnableIf<std::is_integral<IntegralType>, std::is_signed<IntegralType>> * = nullptr>
IntegralType bufferToNumber(const CharType *string, std::size_t size, BaseType base = 10)
{
if (!size) {
return 0;
}
const CharType *end = string + size;
for (; string != end && *string == ' '; ++string)
;
if (string == end) {
return 0;
}
const bool negative = (*string == '-');
if (negative) {
++string;
}
IntegralType result = 0;
for (; string != end; ++string) {
Detail::raiseAndAdd(result, base, *string);
}
return negative ? -result : result;
}
/*!
* \brief Converts the given \a string to an unsigned/signed number assuming \a string uses the specified \a base.
* \tparam IntegralType The data type used to store the converted value.
* \tparam StringType The string type (should be an instantiation of the basic_string class template).
* \throws A ConversionException will be thrown if the provided \a string is not a valid number.
* \sa numberToString(), bufferToNumber()
*/
template <typename IntegralType, class StringType, typename BaseType = IntegralType,
Traits::EnableIf<std::is_integral<IntegralType>, Traits::Not<std::is_scalar<std::decay_t<StringType>>>> * = nullptr>
IntegralType stringToNumber(const StringType &string, BaseType base = 10)
{
return bufferToNumber<IntegralType, typename StringType::value_type, BaseType>(string.data(), string.size(), base);
}
/*!
* \brief Converts the given \a stringView to a number assuming \a stringView uses the specified \a base.
* \tparam FloatingType The data type used to store the converted value.
* \tparam StringViewType The string view type (must be an instantiation of the basic_string_view class template).
* \throws A ConversionException will be thrown if the provided \a string is not a valid number.
* \remarks This function is using std::basic_stringstream internally and hence also has its limitations (eg. regarding
* \a base and types).
* \sa numberToString(), bufferToNumber()
*/
template <typename FloatingType, class StringViewType,
Traits::EnableIf<std::is_floating_point<FloatingType>, Traits::IsSpecializationOf<StringViewType, std::basic_string_view>> * = nullptr>
FloatingType stringToNumber(StringViewType stringView, int base = 10)
{
std::basic_stringstream<typename StringViewType::value_type> ss;
ss << std::setbase(base) << stringView;
FloatingType result;
if ((ss >> result) && ss.eof()) {
return result;
}
std::string errorMsg;
errorMsg.reserve(48 + stringView.size());
errorMsg += "The string \"";
errorMsg += stringView;
errorMsg += "\" is no valid floating point number.";
throw ConversionException(errorMsg);
}
/*!
* \brief Converts the given \a string to a number assuming \a string uses the specified \a base.
* \tparam FloatingType The data type used to store the converted value.
* \tparam StringType The string type (should be an instantiation of the basic_string class template).
* \throws A ConversionException will be thrown if the provided \a string is not a valid number.
* \remarks This function is using std::basic_stringstream internally and hence also has its limitations (eg. regarding
* \a base and types).
* \sa numberToString(), bufferToNumber()
*/
template <typename FloatingType, class StringType,
Traits::EnableIf<std::is_floating_point<FloatingType>, Traits::Not<std::is_scalar<std::decay_t<StringType>>>,
Traits::Not<Traits::IsSpecializationOf<StringType, std::basic_string_view>>> * = nullptr>
FloatingType stringToNumber(const StringType &string, int base = 10)
{
using StringViewType = std::basic_string_view<typename StringType::value_type>;
return stringToNumber<FloatingType, StringViewType>(StringViewType(string.data(), string.size()), base);
}
/*!
* \brief Converts the given null-terminated \a string to an unsigned numeric value using the specified \a base.
* \tparam IntegralType The data type used to store the converted value.
* \tparam CharType The character type.
* \throws A ConversionException will be thrown if the provided \a string is not a valid number.
* \sa numberToString(), bufferToNumber()
*/
template <typename IntegralType, typename CharType, typename BaseType = IntegralType,
Traits::EnableIf<std::is_integral<IntegralType>, std::is_unsigned<IntegralType>> * = nullptr>
IntegralType stringToNumber(const CharType *string, BaseType base = 10)
{
IntegralType result = 0;
for (; *string; ++string) {
Detail::raiseAndAdd(result, base, *string);
}
return result;
}
/*!
* \brief Converts the given null-terminated \a string to a number assuming \a string uses the specified \a base.
* \tparam FloatingType The data type used to store the converted value.
* \tparam CharType The character type.
* \throws A ConversionException will be thrown if the provided \a string is not a valid number.
* \remarks This function is using std::basic_stringstream internally and hence also has its limitations (eg. regarding
* \a base and types).
* \sa numberToString(), bufferToNumber()
*/
template <typename FloatingType, class CharType, Traits::EnableIf<std::is_floating_point<FloatingType>> * = nullptr>
FloatingType stringToNumber(const CharType *string, int base = 10)
{
return stringToNumber<FloatingType, std::basic_string_view<CharType>>(string, base);
}
/*!
* \brief Converts the given null-terminated \a string to a signed numeric value using the specified \a base.
* \tparam IntegralType The data type used to store the converted value.
* \tparam CharType The character type.
* \throws A ConversionException will be thrown if the provided \a string is not a valid number.
* \sa numberToString(), bufferToNumber()
*/
template <typename IntegralType, typename CharType, typename BaseType = IntegralType,
Traits::EnableIf<std::is_integral<IntegralType>, std::is_signed<IntegralType>> * = nullptr>
IntegralType stringToNumber(const CharType *string, IntegralType base = 10)
{
if (!*string) {
return 0;
}
for (; *string && *string == ' '; ++string)
;
if (!*string) {
return 0;
}
const bool negative = (*string == '-');
if (negative) {
++string;
}
IntegralType result = 0;
for (; *string; ++string) {
Detail::raiseAndAdd(result, base, *string);
}
return negative ? -result : result;
}
/*!
* \brief Interprets the given \a integer at the specified position as std::string using the specified byte order.
*
* Example: interpretation of ID3v2 frame IDs (stored as 32-bit integer) as string
* - 0x54495432/1414091826 will be interpreted as "TIT2".
* - 0x00545432/5526578 will be interpreted as "TT2" using start offset 1 to omit the first byte.
*
* \tparam T The data type of the integer to be interpreted.
*/
template <typename T> std::string interpretIntegerAsString(T integer, int startOffset = 0)
{
char buffer[sizeof(T)];
BE::getBytes(integer, buffer);
return std::string(buffer + startOffset, sizeof(T) - static_cast<std::size_t>(startOffset));
}
CPP_UTILITIES_EXPORT std::string dataSizeToString(std::uint64_t sizeInByte, bool includeByte = false);
CPP_UTILITIES_EXPORT std::string bitrateToString(double speedInKbitsPerSecond, bool useByteInsteadOfBits = false);
CPP_UTILITIES_EXPORT std::string encodeBase64(const std::uint8_t *data, std::uint32_t dataSize);
CPP_UTILITIES_EXPORT std::pair<std::unique_ptr<std::uint8_t[]>, std::uint32_t> decodeBase64(const char *encodedStr, const std::uint32_t strSize);
} // namespace CppUtilities
#endif // CONVERSION_UTILITIES_STRINGCONVERSION_H
|