DaZeus  2.0
 All Classes Namespaces Files Functions Variables Enumerations Enumerator Friends Macros
utils.h
Go to the documentation of this file.
1 /*
2  * Copyright (c) Sjors Gielen, 2010-2012
3  * See LICENSE for license.
4  */
5 
6 #ifndef LIBDAZEUS_UTILS_H
7 #define LIBDAZEUS_UTILS_H
8 
9 #include <string>
10 #include <vector>
11 #include <sstream>
12 #include <algorithm>
13 #include <map>
14 
15 std::string strToLower(const std::string &f);
16 std::string strToUpper(const std::string &f);
17 std::string strToIdentifier(const std::string &f);
18 std::string trim(const std::string &s);
19 std::vector<std::string> split(const std::string &s, const std::string &sep);
20 bool contains(std::string x, char v);
21 // does X start with Y?
22 bool startsWith(std::string x, std::string y, bool caseInsensitive);
23 std::vector<std::string>::iterator find_ci(std::vector<std::string> &v, const std::string &s);
24 
25 template <typename Container, typename Key>
26 bool contains(Container x, Key k) {
27  return x.count(k) != 0;
28 }
29 
30 template <typename Value>
31 bool contains(std::vector<Value> x, Value v) {
32  return find(x.begin(), x.end(), v) != x.end();
33 }
34 
35 template <typename Container, typename Value>
36 void erase(Container &x, Value v) {
37  x.erase(remove(x.begin(), x.end(), v), x.end());
38 }
39 
40 template <typename Container, typename Value>
41 Value takeFirst(Container c) {
42  Value v = c[0];
43  c.erase(c.begin());
44  return v;
45 }
46 
47 template <typename Value>
48 typename std::map<std::string,Value>::iterator find_ci(std::map<std::string,Value> &m, const std::string &s) {
49  std::string sl = strToLower(s);
50  typename std::map<std::string,Value>::iterator it;
51  for(it = m.begin(); it != m.end(); ++it) {
52  if(strToLower(it->first) == sl) {
53  return it;
54  }
55  }
56  return m.end();
57 }
58 
59 template <typename Container, typename Key>
60 bool contains_ci(Container x, Key s) {
61  return find_ci(x, s) != x.end();
62 }
63 
64 template <typename Container>
65 void erase_ci(Container &x, const std::string &s) {
66  std::string sl = strToLower(s);
67  typename Container::iterator it = find_ci(x, s);
68  // TODO: use erase-remove idiom
69  while(it != x.end()) {
70  x.erase(it);
71  it = find_ci(x, s);
72  }
73 }
74 
75 template <typename Container>
76 std::string join(Container c, std::string s) {
77  std::stringstream ss;
78  typename Container::const_iterator it;
79  bool first = true;
80  for(it = c.begin(); it != c.end(); ++it) {
81  if(!first)
82  ss << s;
83  ss << *it;
84  first = false;
85  }
86  return ss.str();
87 }
88 
89 std::vector<std::string> &operator<<(std::vector<std::string> &x, const char *v);
90 template <typename T>
91 std::vector<T> &operator<<(std::vector<T> &x, T v) {
92  x.push_back(v);
93  return x;
94 }
95 
96 template <typename T>
97 std::vector<T> &operator<<(std::vector<T> &x, const std::vector<T> &v) {
98  x.insert(x.end(), v.begin(), v.end());
99  return x;
100 }
101 
102 #endif