osb/source/core/StarLexicalCast.hpp

45 lines
1012 B
C++
Raw Normal View History

#pragma once
2023-06-20 04:33:09 +00:00
#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 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
}
}