Make wrapper for boost::lexical_cast
[lsnes.git] / include / library / string.hpp
blob359b08c2ff95672d23555fb910c5921e5624368a
1 #ifndef _library__string__hpp__included__
2 #define _library__string__hpp__included__
4 #include <string>
5 #include <sstream>
6 #include <set>
7 #include <list>
8 #include <stdexcept>
9 #include <vector>
10 #include <boost/lexical_cast.hpp>
11 #include "utf8.hpp"
12 #include "int24.hpp"
14 /**
15 * Strip trailing CR if any.
17 std::string strip_CR(const std::string& str);
19 /**
20 * Strip trailing CR if any.
22 void istrip_CR(std::string& str);
24 /**
25 * Return first character or -1 if empty.
27 int firstchar(const std::string& str);
29 /**
30 * String formatter
32 class stringfmt
34 public:
35 stringfmt() {}
36 std::string str() { return x.str(); }
37 std::u32string str32() { return utf8::to32(x.str()); }
38 template<typename T> stringfmt& operator<<(const T& y) { x << y; return *this; }
39 void throwex() { throw std::runtime_error(x.str()); }
40 private:
41 std::ostringstream x;
44 /**
45 * Lambda iterator.
47 template<typename T> class lambda_output_iterator
49 public:
50 template<typename U> class helper
52 public:
53 helper(std::function<void(const U& val)> _fn)
54 : fn(_fn)
57 helper& operator=(const U& v)
59 fn(v);
60 return *this;
62 private:
63 std::function<void(const U& val)> fn;
65 typedef std::output_iterator_tag iterator_category;
66 typedef helper<T> value_type;
67 typedef int difference_type;
68 typedef helper<T>& reference;
69 typedef helper<T>* pointer;
70 /**
71 * Constructor.
73 lambda_output_iterator(std::function<void(const T& val)> _fn)
74 : h(_fn)
77 /**
78 * Dereference.
80 helper<T>& operator*() throw()
82 return h;
84 /**
85 * Increment.
87 lambda_output_iterator<T>& operator++() throw()
89 return *this;
91 /**
92 * Increment.
94 lambda_output_iterator<T> operator++(int) throw()
96 return *this;
98 private:
99 helper<T> h;
103 * Token iterator.
105 template<typename T> class token_iterator
107 public:
108 typedef std::forward_iterator_tag iterator_category;
109 typedef std::basic_string<T> value_type;
110 typedef int difference_type;
111 typedef const std::basic_string<T>& reference;
112 typedef const std::basic_string<T>* pointer;
114 * Create new end-of-sequence iterator.
116 token_iterator() : str(tmp) { ctor_eos(); }
118 * Create a new start-of-sequence iterator.
120 * Parameter s: The string to iterate. Must remain valid during lifetime of iterator.
121 * Parameter sep: The set of separators.
122 * Parameter whole_sequence: If true, after seeing one separator, throw away separators until none more are found.
124 token_iterator(const std::basic_string<T>& s, std::initializer_list<const T*> sep,
125 bool whole_sequence = false) throw(std::bad_alloc) : str(s) { ctor_itr(sep, whole_sequence); }
127 * Compare.
129 bool operator==(const token_iterator<T>& itr) const throw() { return equals_op(itr); }
131 * Compare.
133 bool operator!=(const token_iterator<T>& itr) const throw() { return !equals_op(itr); }
135 * Dereference.
137 const std::basic_string<T>& operator*() const throw() { return dereference(); }
139 * Increment.
141 token_iterator<T>& operator++() throw(std::bad_alloc) { return preincrement(); }
143 * Increment.
145 token_iterator<T> operator++(int) throw(std::bad_alloc) { return postincrement(); }
147 * Do nothing, pull everything.
149 static void pull_fn();
150 private:
152 * Foreach helper.
154 template<typename U> class _foreach
156 public:
158 * Create helper.
160 _foreach(const std::basic_string<U>& _s,
161 std::initializer_list<const U*> sep, bool whole_sequence = false)
162 : s(_s, sep, whole_sequence)
166 * Starting iterator.
168 token_iterator<U> begin() throw() { return s; }
170 * Ending iterator.
172 token_iterator<U> end() throw() { return e; }
173 private:
174 token_iterator<U> s;
175 token_iterator<U> e;
178 void ctor_eos();
179 void ctor_itr(std::initializer_list<const T*> sep, bool whole_sequence = false) throw(std::bad_alloc);
180 token_iterator<T> postincrement() throw(std::bad_alloc);
181 token_iterator<T>& preincrement() throw(std::bad_alloc);
182 const std::basic_string<T>& dereference() const throw();
183 bool equals_op(const token_iterator<T>& itr) const throw();
184 size_t is_sep(size_t pos);
185 void load_helper();
186 const std::basic_string<T>& str;
187 size_t bidx;
188 size_t eidx;
189 std::basic_string<T> tmp;
190 std::set<std::basic_string<T>> spliton;
191 bool is_end_iterator;
192 bool whole_seq;
193 public:
195 * Return an container referencing tokens of string.
197 static _foreach<T> foreach(const std::basic_string<T>& _s,
198 std::initializer_list<const T*> sep, bool whole_sequence = false)
200 return _foreach<T>(_s, sep, whole_sequence);
206 class regex_results
208 public:
209 regex_results();
210 regex_results(std::vector<std::string> res, std::vector<std::pair<size_t, size_t>> mch);
211 operator bool() const;
212 bool operator!() const;
213 size_t size() const;
214 const std::string& operator[](size_t i) const;
215 std::pair<size_t, size_t> match(size_t i) const;
216 private:
217 bool matched;
218 std::vector<std::string> results;
219 std::vector<std::pair<size_t, size_t>> matches;
223 * Regexp a string and return matches.
225 * Parameter regex: The regexp to apply.
226 * Parameter str: The string to apply the regexp to.
227 * Parameter ex: If non-null and string does not match, throw this as std::runtime_error.
228 * Returns: The captures.
230 regex_results regex(const std::string& regex, const std::string& str, const char* ex = NULL)
231 throw(std::bad_alloc, std::runtime_error);
233 enum regex_match_mode
235 REGEX_MATCH_REGEX = 0,
236 REGEX_MATCH_LITERIAL = 1,
237 REGEX_MATCH_IWILDCARDS = 2,
238 REGEX_MATCH_IREGEX = 3,
242 * Regexp a string and return match result.
244 * Parameter regex: The regexp to apply.
245 * Parameter str: The string to apply the regexp to.
246 * Parameter mode: Match mode.
247 * Returns: True if matches, false if not.
249 bool regex_match(const std::string& regex, const std::string& str, enum regex_match_mode mode = REGEX_MATCH_REGEX)
250 throw(std::bad_alloc, std::runtime_error);
253 * Try match a case-insensitive string fragment and return the result.
255 * \param pattern The pattern to match a
259 * Cast string to bool.
261 * The following is true: 'on', 'true', 'yes', '1', 'enable', 'enabled'.
262 * The following is false: 'off', 'false', 'no', '0', 'disable', 'disabled'.
263 * Parameter str: The string to cast.
264 * Returns: -1 if string is bad, 0 if false, 1 if true.
266 int string_to_bool(const std::string& cast_to_bool);
268 template<typename T> T raw_lexical_cast(const std::string& value)
270 return boost::lexical_cast<T>(value);
274 * \brief Typeconvert string.
276 template<typename T> inline T parse_value(const std::string& value) throw(std::bad_alloc, std::runtime_error)
278 //Floating-point case.
279 try {
280 if(std::numeric_limits<T>::is_integer) {
281 if(!std::numeric_limits<T>::is_signed && value.length() && value[0] == '-') {
282 throw std::runtime_error("Unsigned values can't be negative");
284 size_t idx = 0;
285 if(value[idx] == '-' || value[idx] == '+')
286 idx++;
287 bool sign = (value[0] == '-');
288 T bound = sign ? std::numeric_limits<T>::min() : std::numeric_limits<T>::max();
289 T val = 0;
290 if(value.length() > idx + 2 && value[idx] == '0' && value[idx + 1] == 'x') {
291 //Hexadecimal
292 for(size_t i = idx + 2; i < value.length(); i++) {
293 char ch = value[i];
294 T v = 0;
295 if(ch >= '0' && ch <= '9')
296 v = ch - '0';
297 else if(ch >= 'A' && ch <= 'F')
298 v = ch - 'A' + 10;
299 else if(ch >= 'a' && ch <= 'f')
300 v = ch - 'a' + 10;
301 else
302 throw std::runtime_error("Invalid character in number");
303 if((sign && (bound + v) / 16 > val) || (!sign && (bound - v) / 16 < val))
304 throw std::runtime_error("Value exceeds range");
305 val = 16 * val + (sign ? -v : v);
307 } else {
308 //Decimal.
309 for(size_t i = idx; i < value.length(); i++) {
310 char ch = value[i];
311 T v = 0;
312 if(ch >= '0' && ch <= '9')
313 v = ch - '0';
314 else
315 throw std::runtime_error("Invalid character in number");
316 if((sign && (bound + v) / 10 > val) || (!sign && (bound - v) / 10 < val))
317 throw std::runtime_error("Value exceeds range");
318 val = 10 * val + (sign ? -v : v);
321 return val;
323 return raw_lexical_cast<T>(value);
324 } catch(std::exception& e) {
325 throw std::runtime_error("Can't parse value '" + value + "': " + e.what());
329 template<> inline ss_int24_t parse_value(const std::string& value) throw(std::bad_alloc, std::runtime_error)
331 int32_t v = parse_value<int32_t>(value);
332 if(v < -8388608 || v > 8388607)
333 throw std::runtime_error("Can't parse value '" + value + "': Value out of valid range");
334 return v;
337 template<> inline ss_uint24_t parse_value(const std::string& value) throw(std::bad_alloc, std::runtime_error)
339 uint32_t v = parse_value<uint32_t>(value);
340 if(v > 0xFFFFFF)
341 throw std::runtime_error("Can't parse value '" + value + "': Value out of valid range");
342 return v;
345 template<> inline std::string parse_value(const std::string& value) throw(std::bad_alloc, std::runtime_error)
347 return value;
350 template<typename T>
351 class string_list
353 public:
354 string_list();
355 string_list(const std::list<std::basic_string<T>>& list);
356 bool empty();
357 string_list strip_one() const;
358 size_t size() const;
359 const std::basic_string<T>& operator[](size_t idx) const;
360 bool operator<(const string_list<T>& x) const;
361 bool operator==(const string_list<T>& x) const;
362 bool prefix_of(const string_list<T>& x) const;
363 std::basic_string<T> debug_name() const;
364 private:
365 string_list(const std::basic_string<T>* array, size_t arrsize);
366 std::vector<std::basic_string<T>> v;
370 * Split a string into substrings on some unicode codepoint.
372 string_list<char> split_on_codepoint(const std::string& s, char32_t cp);
374 * Split a string into substrings on some unicode codepoint.
376 string_list<char32_t> split_on_codepoint(const std::u32string& s, char32_t cp);
378 #endif