Веб-сайт самохостера Lotigara

summaryrefslogtreecommitdiff
path: root/source/core/StarLexicalCast.hpp
blob: 6e6c66ebcb045296a8635f311d2cebb793f6dca5 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
#ifndef STAR_LEXICAL_CAST_HPP
#define STAR_LEXICAL_CAST_HPP

#include "StarString.hpp"
#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(std::string const& s, std::ios_base::fmtflags flags = std::ios_base::boolalpha) {
  Type result;
  std::istringstream stream(s);
  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;
}

template <typename Type>
Maybe<Type> maybeLexicalCast(char const* s, std::ios_base::fmtflags flags = std::ios_base::boolalpha) {
  return maybeLexicalCast<Type>(std::string(s), flags);
}

template <typename Type>
Maybe<Type> maybeLexicalCast(String const& s, std::ios_base::fmtflags flags = std::ios_base::boolalpha) {
  return maybeLexicalCast<Type>(s.utf8(), flags);
}

template <typename Type>
Type lexicalCast(std::string const& s, std::ios_base::fmtflags flags = std::ios_base::boolalpha) {
  auto m = maybeLexicalCast<Type>(s, flags);
  if (m)
    return m.take();
  else
    throw BadLexicalCast(strf("Lexical cast failed on '%s'", s));
}

template <typename Type>
Type lexicalCast(char const* s, std::ios_base::fmtflags flags = std::ios_base::boolalpha) {
  return lexicalCast<Type>(std::string(s), flags);
}

template <typename Type>
Type lexicalCast(String const& s, std::ios_base::fmtflags flags = std::ios_base::boolalpha) {
  return lexicalCast<Type>(s.utf8(), flags);
}

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