string_utils.cc 10 KB
Newer Older
Martin Reinecke's avatar
Martin Reinecke committed
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
/*
 *  This file is part of libcxxsupport.
 *
 *  libcxxsupport is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  libcxxsupport is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with libcxxsupport; if not, write to the Free Software
 *  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 */

/*
 *  libcxxsupport is being developed at the Max-Planck-Institut fuer Astrophysik
 *  and financially supported by the Deutsches Zentrum fuer Luft- und Raumfahrt
 *  (DLR).
 */

/*
 *  This file contains the implementation of various convenience functions
 *  used by the Planck LevelS package.
 *
 *  Copyright (C) 2002-2014 Max-Planck-Society
 *  Author: Martin Reinecke
 */

#include <sstream>
#include <fstream>
#include <iostream>
#include <iomanip>
#include <string>
#include <cstring>
#include <cctype>
Martin Reinecke's avatar
Martin Reinecke committed
40
41
42
#include "mr_util/string_utils.h"
#include "mr_util/error_handling.h"
#include "mr_util/datatypes.h"
Martin Reinecke's avatar
Martin Reinecke committed
43
44
45

using namespace std;

Martin Reinecke's avatar
Martin Reinecke committed
46
47
48
49
50
51
namespace mr {

namespace string_utils {

using namespace mr::datatypes;

Martin Reinecke's avatar
Martin Reinecke committed
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
string trim (const string &orig)
  {
  string::size_type p1=orig.find_first_not_of(" \t");
  if (p1==string::npos) return "";
  string::size_type p2=orig.find_last_not_of(" \t");
  return orig.substr(p1,p2-p1+1);
  }

template<typename T> string dataToString (const T &x)
  {
  ostringstream strstrm;
  strstrm << x;
  return trim(strstrm.str());
  }

template<> string dataToString (const bool &x)
  { return x ? "T" : "F"; }
template<> string dataToString (const string &x)
  { return trim(x); }
template<> string dataToString (const float &x)
  {
  ostringstream strstrm;
  strstrm << setprecision(8) << x;
  return trim(strstrm.str());
  }
template<> string dataToString (const double &x)
  {
  ostringstream strstrm;
  strstrm << setprecision(16) << x;
  return trim(strstrm.str());
  }
template<> string dataToString (const long double &x)
  {
  ostringstream strstrm;
  strstrm << setprecision(25) << x;
  return trim(strstrm.str());
  }

template string dataToString (const signed char &x);
template string dataToString (const unsigned char &x);
template string dataToString (const short &x);
template string dataToString (const unsigned short &x);
template string dataToString (const int &x);
template string dataToString (const unsigned int &x);
template string dataToString (const long &x);
template string dataToString (const unsigned long &x);
template string dataToString (const long long &x);
template string dataToString (const unsigned long long &x);

Martin Reinecke's avatar
Martin Reinecke committed
101
string intToString(int64_t x, size_t width)
Martin Reinecke's avatar
Martin Reinecke committed
102
103
104
105
106
  {
  ostringstream strstrm;
  (x>=0) ? strstrm << setw(width) << setfill('0') << x
         : strstrm << "-" << setw(width-1) << setfill('0') << -x;
  string res = strstrm.str();
Martin Reinecke's avatar
Martin Reinecke committed
107
  MR_assert(res.size()==width,"number too large");
Martin Reinecke's avatar
Martin Reinecke committed
108
109
110
111
112
113
114
  return trim(res);
  }

namespace {

void end_stringToData (const string &x, const char *tn, istringstream &strstrm)
  {
Martin Reinecke's avatar
Martin Reinecke committed
115
  MR_assert (strstrm,
Martin Reinecke's avatar
Martin Reinecke committed
116
117
118
119
    "conversion error in stringToData<", tn, ">('", x, "')");
  string rest;
  strstrm >> rest;
//  rest=trim(rest);
Martin Reinecke's avatar
Martin Reinecke committed
120
  MR_assert (rest.length()==0,
Martin Reinecke's avatar
Martin Reinecke committed
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
    "conversion error in stringToData<", tn, ">('", x, "')");
  }

} // unnamed namespace

template<typename T> void stringToData (const string &x, T &value)
  {
  istringstream strstrm(x);
  strstrm >> value;
  end_stringToData (x,type2typename<T>(),strstrm);
  }

template<> void stringToData (const string &x, string &value)
  { value = trim(x); }

template<> void stringToData (const string &x, bool &value)
  {
  const char *fval[] = {"f","n","false",".false."};
  const char *tval[] = {"t","y","true",".true."};
Martin Reinecke's avatar
Martin Reinecke committed
140
  for (size_t i=0; i< sizeof(fval)/sizeof(fval[0]); ++i)
Martin Reinecke's avatar
Martin Reinecke committed
141
    if (equal_nocase(x,fval[i])) { value=false; return; }
Martin Reinecke's avatar
Martin Reinecke committed
142
  for (size_t i=0; i< sizeof(tval)/sizeof(tval[0]); ++i)
Martin Reinecke's avatar
Martin Reinecke committed
143
    if (equal_nocase(x,tval[i])) { value=true; return; }
Martin Reinecke's avatar
Martin Reinecke committed
144
  MR_fail("conversion error in stringToData<bool>(",x,")");
Martin Reinecke's avatar
Martin Reinecke committed
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
  }

template void stringToData (const string &x, signed char &value);
template void stringToData (const string &x, unsigned char &value);
template void stringToData (const string &x, short &value);
template void stringToData (const string &x, unsigned short &value);
template void stringToData (const string &x, int &value);
template void stringToData (const string &x, unsigned int &value);
template void stringToData (const string &x, long &value);
template void stringToData (const string &x, unsigned long &value);
template void stringToData (const string &x, long long &value);
template void stringToData (const string &x, unsigned long long &value);
template void stringToData (const string &x, float &value);
template void stringToData (const string &x, double &value);
template void stringToData (const string &x, long double &value);

bool equal_nocase (const string &a, const string &b)
  {
  if (a.size()!=b.size()) return false;
Martin Reinecke's avatar
Martin Reinecke committed
164
165
  for (size_t m=0; m<a.size(); ++m)
    if (std::tolower(a[m])!=std::tolower(b[m])) return false;
Martin Reinecke's avatar
Martin Reinecke committed
166
167
168
169
170
171
  return true;
  }

string tolower(const string &input)
  {
  string result=input;
Martin Reinecke's avatar
Martin Reinecke committed
172
173
  for (size_t m=0; m<result.size(); ++m)
    result[m]=char(std::tolower(result[m]));
Martin Reinecke's avatar
Martin Reinecke committed
174
175
176
177
178
179
180
181
  return result;
  }

void parse_file (const string &filename, map<string,string> &dict)
  {
  int lineno=0;
  dict.clear();
  ifstream inp(filename.c_str());
Martin Reinecke's avatar
Martin Reinecke committed
182
  MR_assert (inp, "Could not open parameter file '", filename, "'.");
Martin Reinecke's avatar
Martin Reinecke committed
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
  while (inp)
    {
    string line;
    getline(inp, line);
    ++lineno;
    // remove potential carriage returns at the end of the line
    line=line.substr(0,line.find("\r"));
    line=line.substr(0,line.find("#"));
    line=trim(line);
    if (line.size()>0)
      {
      string::size_type eqpos=line.find("=");
      if (eqpos!=string::npos)
        {
        string key=trim(line.substr(0,eqpos)),
               value=trim(line.substr(eqpos+1,string::npos));
        if (key=="")
          cerr << "Warning: empty key in '" << filename << "', line "
               << lineno << endl;
        else
          {
          if (dict.find(key)!=dict.end())
            cerr << "Warning: key '" << key << "' multiply defined in '"
                 << filename << "', line " << lineno << endl;
          dict[key]=value;
          }
        }
      else
        cerr << "Warning: unrecognized format in '" << filename << "', line "
             << lineno << ":\n" << line << endl;
      }
    }
  }

namespace {

bool isParam (const string &s)
  {
  if (s.size()<2) return false;
  if (s[0]!='-') return false;
  return !(isdigit(s[1]) || (s[1]=='.'));
  }

} // unnamed namespace

void parse_cmdline_classic (int argc, const char **argv,
  const vector<string> &leading_args, map<string,string> &dict)
  {
  dict.clear();
Martin Reinecke's avatar
Martin Reinecke committed
232
233
  MR_assert(size_t(argc)>leading_args.size(),"not enough arguments");
  for (size_t i=0; i<leading_args.size(); ++i)
Martin Reinecke's avatar
Martin Reinecke committed
234
235
236
237
238
    dict[leading_args[i]] = argv[i+1];
  int curarg=leading_args.size()+1;
  while (curarg<argc)
    {
    string param=argv[curarg];
Martin Reinecke's avatar
Martin Reinecke committed
239
    MR_assert(isParam(param),"unrecognized command line format");
Martin Reinecke's avatar
Martin Reinecke committed
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
    if ((curarg==argc-1) || isParam(argv[curarg+1]))
      {
      dict[param.substr(1)]="true";
      ++curarg;
      }
    else
      {
      dict[param.substr(1)]=argv[curarg+1];
      curarg+=2;
      }
    }
  }

void parse_cmdline_classic (int argc, const char **argv,
  map<string,string> &dict)
  { parse_cmdline_classic (argc, argv, vector<string>(), dict); }

void parse_cmdline_equalsign (int argc, const char **argv,
  const vector<string> &leading_args, map<string,string> &dict)
  {
  dict.clear();
Martin Reinecke's avatar
Martin Reinecke committed
261
262
  MR_assert(size_t(argc)>leading_args.size(),"not enough arguments");
  for (size_t i=0; i<leading_args.size(); ++i)
Martin Reinecke's avatar
Martin Reinecke committed
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
    dict[leading_args[i]] = argv[i+1];
  for (int i=leading_args.size()+1; i<argc; ++i)
    {
    string arg=trim(argv[i]);
    if (arg.size()>0)
      {
      string::size_type eqpos=arg.find("=");
      if (eqpos!=string::npos)
        {
        string key=trim(arg.substr(0,eqpos)),
               value=trim(arg.substr(eqpos+1,string::npos));
        if (key=="")
          cerr << "Warning: empty key in argument'" << arg << "'" << endl;
        else
          {
          if (dict.find(key)!=dict.end())
            cerr << "Warning: key '" << key << "' multiply defined" << endl;
          dict[key]=value;
          }
        }
      else
        cerr << "Warning: unrecognized format in argument '" << arg << "'"
             << endl;
      }
    }
  }

void parse_cmdline_equalsign (int argc, const char **argv,
  map<string,string> &dict)
  { parse_cmdline_equalsign (argc, argv, vector<string>(), dict); }

namespace {

template<typename T> void split (istream &stream, vector<T> &list)
  {
  list.clear();
  while (stream)
    {
    string word;
    stream >> word;
Martin Reinecke's avatar
Martin Reinecke committed
303
    MR_assert (stream||stream.eof(),
Martin Reinecke's avatar
Martin Reinecke committed
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
      "error while splitting stream into ", type2typename<T>(), " components");
    if (stream) list.push_back(stringToData<T>(word));
    }
  }

} // unnamed namespace

template<typename T> void split (const string &inp, vector<T> &list)
  {
  istringstream stream(inp);
  split (stream,list);
  }

template void split (const string &inp, vector<string> &list);
template void split (const string &inp, vector<float> &list);
template void split (const string &inp, vector<double> &list);
template void split (const string &inp, vector<int> &list);
template void split (const string &inp, vector<long> &list);

void tokenize (const string &inp, char delim, vector<string> &list)
  {
  istringstream stream(inp);
  string token;
  list.clear();
  while (getline(stream,token,delim))
    list.push_back(token);
  }

void parse_words_from_file (const string &filename, vector<string> &words)
  {
  words.clear();
  ifstream inp(filename.c_str());
Martin Reinecke's avatar
Martin Reinecke committed
336
  MR_assert (inp,"Could not open file '", filename, "'.");
Martin Reinecke's avatar
Martin Reinecke committed
337
338
339
340
341
342
343
344
  while (inp)
    {
    string word;
    inp>>word;
    word=trim(word);
    if (word!="") words.push_back(word);
    }
  }
Martin Reinecke's avatar
Martin Reinecke committed
345
346

}}