osb/source/core/StarLexicalCast.hpp

53 lines
1.1 KiB
C++
Raw Normal View History

2023-06-20 04:33:09 +00:00
#ifndef STAR_LEXICAL_CAST_HPP
#define STAR_LEXICAL_CAST_HPP
#include "StarFormat.hpp"
2023-06-20 04:33:09 +00:00
#include "StarString.hpp"
#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>
Maybe<Type> maybeLexicalCast(StringView s, std::ios_base::fmtflags flags = std::ios_base::boolalpha) {
2023-06-20 04:33:09 +00:00
Type result;
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 {};
return move(result);
2023-06-20 04:33:09 +00:00
}
template <typename Type>
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
}
template <class Type>
std::string toString(Type const& t) {
return fmt::to_string(t);
2023-06-20 04:33:09 +00:00
}
}
#endif