00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018
00019
00020 #ifndef PALUDIS_GUARD_PALUDIS_DESTRINGIFY_HH
00021 #define PALUDIS_GUARD_PALUDIS_DESTRINGIFY_HH 1
00022
00023 #include <paludis/util/exception.hh>
00024 #include <sstream>
00025 #include <string>
00026
00027
00028
00029
00030
00031
00032
00033
00034
00035
00036
00037 namespace paludis
00038 {
00039
00040
00041
00042
00043
00044
00045
00046 class PALUDIS_VISIBLE DestringifyError :
00047 public Exception
00048 {
00049 public:
00050
00051
00052
00053 DestringifyError(const std::string & str) throw ();
00054
00055
00056 };
00057
00058
00059
00060
00061
00062
00063 namespace destringify_internals
00064 {
00065
00066
00067
00068
00069
00070 template <typename Type_, typename Exception_>
00071 struct Destringifier
00072 {
00073
00074
00075
00076 static Type_ do_destringify(const std::string & s)
00077 {
00078 std::istringstream ss(s);
00079 Type_ t;
00080 ss >> t;
00081 if (! ss.eof() || ss.fail())
00082 throw Exception_(s);
00083 return t;
00084 }
00085 };
00086
00087
00088
00089
00090
00091
00092 template <typename Exception_>
00093 struct Destringifier<std::string, Exception_>
00094 {
00095
00096
00097
00098 static std::string do_destringify(const std::string & s)
00099 {
00100 return s;
00101 }
00102 };
00103
00104
00105
00106
00107
00108
00109 template <typename Exception_>
00110 struct Destringifier<bool, Exception_>
00111 {
00112
00113
00114
00115 static bool do_destringify(const std::string & s)
00116 {
00117
00118
00119 if (s == "true")
00120 return true;
00121 else if (s == "false")
00122 return false;
00123 else
00124 {
00125 std::istringstream ss(s);
00126 int i;
00127 ss >> i;
00128 if (ss.eof() && ! ss.bad())
00129 return i > 0;
00130 else
00131 throw Exception_(s);
00132 }
00133 }
00134 };
00135
00136
00137
00138
00139
00140
00141 template <typename Exception_>
00142 struct Destringifier<char, Exception_>
00143 {
00144
00145
00146
00147 static char do_destringify(const std::string & s)
00148 {
00149 if (s.length() == 1)
00150 return s[0];
00151 else
00152 throw Exception_(s);
00153 }
00154 };
00155 }
00156
00157
00158
00159
00160
00161
00162 template <typename Type_, typename Exception_>
00163 Type_ destringify(const std::string & s)
00164 {
00165 if (s == "")
00166 throw Exception_("");
00167
00168 return destringify_internals::Destringifier<Type_, Exception_>::do_destringify(s);
00169 }
00170
00171 template <typename Type_>
00172 Type_ destringify(const std::string & s)
00173 {
00174 return destringify<Type_, DestringifyError>(s);
00175 }
00176 }
00177
00178 #endif