2024-02-25 14:46:47 +00:00
|
|
|
#pragma once
|
2023-06-20 04:33:09 +00:00
|
|
|
|
2023-06-27 09:24:35 +00:00
|
|
|
#include "StarFormat.hpp"
|
2023-06-20 04:33:09 +00:00
|
|
|
#include "StarString.hpp"
|
2023-06-25 15:42:18 +00:00
|
|
|
#include "StarStringView.hpp"
|
2023-06-20 04:33:09 +00:00
|
|
|
#include "StarMaybe.hpp"
|
|
|
|
|
|
|
|
#include <sstream>
|
|
|
|
#include <locale>
|
|
|
|
|
|
|
|
namespace Star {
|
|
|
|
|
|
|
|
STAR_EXCEPTION(BadLexicalCast, StarException);
|
|
|
|
|
|
|
|
// Very simple basic lexical cast using stream input. Always operates in the
|
|
|
|
// "C" locale.
|
|
|
|
template <typename Type>
|
2023-06-25 15:42:18 +00:00
|
|
|
Maybe<Type> maybeLexicalCast(StringView s, std::ios_base::fmtflags flags = std::ios_base::boolalpha) {
|
2023-06-20 04:33:09 +00:00
|
|
|
Type result;
|
2023-06-25 15:42:18 +00:00
|
|
|
std::istringstream stream(std::string(s.utf8()));
|
2023-06-20 04:33:09 +00:00
|
|
|
stream.flags(flags);
|
|
|
|
stream.imbue(std::locale::classic());
|
|
|
|
|
|
|
|
if (!(stream >> result))
|
|
|
|
return {};
|
|
|
|
|
|
|
|
// Confirm that we read everything out of the stream
|
|
|
|
char ch;
|
|
|
|
if (stream >> ch)
|
|
|
|
return {};
|
|
|
|
|
2024-02-19 17:39:01 +00:00
|
|
|
return result;
|
2023-06-20 04:33:09 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
template <typename Type>
|
2023-06-25 15:42:18 +00:00
|
|
|
Type lexicalCast(StringView s, std::ios_base::fmtflags flags = std::ios_base::boolalpha) {
|
2023-06-20 04:33:09 +00:00
|
|
|
auto m = maybeLexicalCast<Type>(s, flags);
|
|
|
|
if (m)
|
|
|
|
return m.take();
|
|
|
|
else
|
2023-06-27 10:23:44 +00:00
|
|
|
throw BadLexicalCast(strf("Lexical cast failed on '{}'", s));
|
2023-06-20 04:33:09 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
}
|