mirror of
https://github.com/MihailRis/voxelcore.git
synced 2026-10-12 06:21:50 +00:00
Перевел parse_double на from_chars
This commit is contained in:
parent
db53076c62
commit
7f408c11de
2 changed files with 32 additions and 17 deletions
|
|
@ -1,6 +1,8 @@
|
||||||
#include "stringutil.hpp"
|
#include "stringutil.hpp"
|
||||||
|
|
||||||
#include <algorithm>
|
#include <algorithm>
|
||||||
|
#include <charconv>
|
||||||
|
#include <cctype>
|
||||||
#include <cmath>
|
#include <cmath>
|
||||||
#include <iomanip>
|
#include <iomanip>
|
||||||
#include <locale>
|
#include <locale>
|
||||||
|
|
@ -509,13 +511,18 @@ int util::replaceAll(
|
||||||
return replace_all(str, from, to);
|
return replace_all(str, from, to);
|
||||||
}
|
}
|
||||||
|
|
||||||
// replace it with std::from_chars in the far far future
|
|
||||||
double util::parse_double(const std::string& str) {
|
double util::parse_double(const std::string& str) {
|
||||||
std::istringstream ss(str);
|
const char* begin = str.data();
|
||||||
ss.imbue(std::locale("C"));
|
const char* end = begin + str.size();
|
||||||
double d;
|
while (begin != end && std::isspace(static_cast<unsigned char>(*begin))) {
|
||||||
ss >> d;
|
begin++;
|
||||||
if (ss.fail()) {
|
}
|
||||||
|
if (begin != end && *begin == '+') {
|
||||||
|
begin++;
|
||||||
|
}
|
||||||
|
double d = 0.0;
|
||||||
|
const auto result = std::from_chars(begin, end, d);
|
||||||
|
if (result.ec != std::errc()) {
|
||||||
throw std::runtime_error("invalid number format");
|
throw std::runtime_error("invalid number format");
|
||||||
}
|
}
|
||||||
return d;
|
return d;
|
||||||
|
|
|
||||||
|
|
@ -68,6 +68,14 @@ TEST(stringutil, base64_urlsafe) {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
TEST(stringutil, parse_double) {
|
||||||
|
EXPECT_DOUBLE_EQ(util::parse_double("53.125"), 53.125);
|
||||||
|
EXPECT_DOUBLE_EQ(util::parse_double("-0.25"), -0.25);
|
||||||
|
EXPECT_DOUBLE_EQ(util::parse_double(" +12.5"), 12.5);
|
||||||
|
EXPECT_DOUBLE_EQ(util::parse_double("xx1.75yy", 2, 4), 1.75);
|
||||||
|
EXPECT_THROW(util::parse_double("not-a-number"), std::runtime_error);
|
||||||
|
}
|
||||||
|
|
||||||
class StringParser : BasicParser<char> {
|
class StringParser : BasicParser<char> {
|
||||||
public:
|
public:
|
||||||
StringParser(std::string_view source) : BasicParser("<string>", source) {}
|
StringParser(std::string_view source) : BasicParser("<string>", source) {}
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue