2023-06-20 04:33:09 +00:00
|
|
|
#ifndef STAR_LEXICAL_CAST_HPP
|
|
|
|
#define STAR_LEXICAL_CAST_HPP
|
|
|
|
|
|
|
|
#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 {};
|
|
|
|
|
2023-06-25 15:42:18 +00:00
|
|
|
return move(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-24 15:16:40 +00:00
|
|
|
throw BadLexicalCast(strf("Lexical cast failed on '%s'", s));
|
2023-06-20 04:33:09 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
template <class Type>
|
|
|
|
std::string toString(Type const& t, std::ios_base::fmtflags flags = std::ios_base::boolalpha) {
|
|
|
|
std::stringstream ss;
|
|
|
|
ss.flags(flags);
|
|
|
|
ss.imbue(std::locale::classic());
|
|
|
|
ss << t;
|
|
|
|
return ss.str();
|
|
|
|
}
|
|
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
#endif
|