Loading...
Searching...
No Matches
StringMapper.h
1/*
2
3MIT License
4
5Copyright (c) 2017 FMI Open Development / Markus Peura, first.last@fmi.fi
6
7Permission is hereby granted, free of charge, to any person obtaining a copy
8of this software and associated documentation files (the "Software"), to deal
9in the Software without restriction, including without limitation the rights
10to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11copies of the Software, and to permit persons to whom the Software is
12furnished to do so, subject to the following conditions:
13
14The above copyright notice and this permission notice shall be included in all
15copies or substantial portions of the Software.
16
17THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
23SOFTWARE.
24
25*/
26/*
27Part of Rack development has been done in the BALTRAD projects part-financed
28by the European Union (European Regional Development Fund and European
29Neighbourhood Partnership Instrument, Baltic Sea Region Programme 2007-2013)
30*/
31
32#ifndef STRINGMAPPER_H_
33#define STRINGMAPPER_H_
34
35#include <map>
36#include <list>
37#include <sstream>
38
39#include <drain/Enum.h>
40#include <drain/RegExp.h>
41#include <drain/Sprinter.h>
42
43#include "IosFormat.h"
44#include "Time.h"
45#include "VariableFormatter.h"
46
47namespace drain {
48
50
55class Stringlet: public std::string {
56public:
57
58 inline
59 Stringlet(const std::string & s = "", bool isVariable = false) : std::string(s), isVar(isVariable) {
60 };
61
63 Stringlet(const Stringlet & s) : std::string(s), isVar(s.isVar) {
64 }
65
66 inline
67 bool isVariable() const { return isVar; };
68
69 inline
70 void setVariable(bool isVariable=true) { isVar = isVariable; };
71
72 inline
73 void setLiteral(const std::string &s) { assign(s); isVar = false; };
74
75 // Consider!
76 // But has to share variable syntax ${...} with string mapper(s), which recognizes it...
77 // std::ostream & toStream(std::ostream & ostr, std::map<std::string, T> & environment, bool clearMissing=true){}
78
79protected:
80
81 bool isVar;
82
83};
84
85
86inline
87std::ostream & operator<<(std::ostream & ostr, const Stringlet & s) {
88 if (s.isVariable())
89 return ostr << "${" << (const std::string &) s << "}";
90 else
91 return ostr << (const std::string &) s;
92}
93
94
95
96
97
98
100
114class StringMapper : public std::list<Stringlet> {
115
116public:
117
119
126 const std::string & format = "",
127 const std::string & validChars = "[a-zA-Z0-9_]+",
128 bool formatting=true
129 ): formatting(formatting)
130 {
131 setValidChars(validChars);
132 regExp.setFlags(REG_EXTENDED);
133 if (!format.empty())
134 parse(format);
135 //regExp.setFlags(REG_EXTENDED); // ORDER? Should be before parse!?
136 };
137
139 StringMapper(const RegExp & regexp, bool formatting=true) : formatting(formatting), regExp(regexp) { // fieldWidth(0),
140 // fillChar('0'),
141 // ((std::list<Stringlet> &)*this) = mapper;
142 }
143
145 StringMapper(const StringMapper & mapper) : std::list<Stringlet>(mapper), formatting(mapper.formatting), regExp(mapper.regExp) { // Buggy: regExp(mapper.regExp) {
146 }
147
148
149 inline
150 StringMapper & setValidChars(const std::string & chars){
151 this->validChars = chars;
152 /*
153 std::stringstream sstr;
154 sstr << "^(.*)\\$\\{(" << chars << ")\\}(.*)$";
155 regExp.setExpression(sstr.str());
156 */
157 updateRegExp();
158 return *this;
159 }
160
162
166 inline
167 StringMapper & enableFormatting(bool formatting){
168 if (this->formatting != formatting){
169 this->formatting = formatting;
170 updateRegExp();
171 }
172 else {
173 this->formatting = formatting;
174 }
175 return *this;
176 }
177
178
179
181
186 StringMapper & parse(const std::string &s, bool convertEscaped = false);
187
188 /*
190 static
191 std::string & convertEscaped(std::string &s);
192 */
193
195 bool isLiteral() const;
196
198
203 inline
204 std::ostream & toStream(std::ostream & ostr) const {
206 return ostr;
207 }
208
209 IosFormat iosFormat;
210
211 // static const int KEEP_MISSING_VARIABLE;
212 // static const int REMOVE_MISSING_VARIABLE;
213 enum handleMissing {
214 REMOVE_MISSING_VARIABLE, //=0,
215 KEEP_MISSING_VARIABLE // =1,
216 };
217
219
224 template <class T>
225 std::ostream & toStream(std::ostream & ostr, const std::map<std::string,T> & variables, int replace = REMOVE_MISSING_VARIABLE,
226 const VariableFormatter<T> &formatter = VariableFormatter<T>()) const {
227
228 for (const Stringlet & stringlet: *this){
229
230 if (stringlet.isVariable()){
231
232 if (formatter.handle(stringlet, variables, ostr)){
233 // std::cerr << __FILE__ << " ok stringlet variable: " << stringlet << std::endl;
234 // Variable found and assigned.
235 }
236 else if (replace == KEEP_MISSING_VARIABLE){ // (replace < 0)
237 ostr << stringlet; // is Variable -> use layout "${variable}";
238 }
239 else if (replace != REMOVE_MISSING_VARIABLE){
240 ostr << (char)replace;
241 }
242 // else: silently skip the variable.
243 }
244 else
245 ostr << stringlet;
246 };
247 return ostr;
248 }
249
251
255 template <class T>
256 std::string toStr(const std::map<std::string,T> &m, int replaceChar = -1, const VariableFormatter<T> & formatter = VariableFormatter<T>()) const {
257 std::stringstream s;
258 toStream(s, m, replaceChar, formatter);
259 return s.str();
260 }
261
263
267 template <class T>
268 void expand(const std::map<std::string,T> &m, const VariableFormatter<T> & formatter=VariableFormatter<T>(), bool clear=false) {
269 for (auto & entry: *this){
270 if (entry.isVariable()){
271 std::stringstream s;
272 if (formatter.handle(entry, m, s)){
273 entry.setLiteral(s.str());
274 }
275 else if (clear) {
276 entry.setLiteral("");
277 }
278 }
279 };
280 }
281
282
284 template <class T>
285 std::ostream & debug(std::ostream & ostr, const std::map<std::string,T> &m ) const {
286
287 const VariableFormatter<T> formatter;
288
289 ostr << "StringMapper '"<< "', RegExp='" << regExp << "', " << size() << " segments:\n";
290 //StringMapper::const_iterator it;
291 for (const auto & entry: *this){
292 ostr << " ";
293 if (entry.isVariable()){
294 ostr << entry << "=";
295 if (!formatter.handle(entry, m, ostr)){
296 ostr << "???";
297 }
298 }
299 else {
300 // Literal
301 ostr << "'" << entry << "'";
302 }
303 ostr << '\n';
304 };
305
306 return ostr;
307 }
308
309
310protected:
311
312 inline
313 void updateRegExp(){
314 std::stringstream sstr;
315 sstr << "^(.*)\\$\\{(" << validChars; // << ")\\}(.*)$";
316 if (formatting){
317 sstr << "(\\|[^}]*)?";
318 }
319 sstr << ")\\}(.*)$";
320 // std::cout << sstr.str() << '\n';
321 regExp.setExpression(sstr.str());
322 }
323
324 StringMapper & parse(const std::string &s, RegExp &r);
325
326 std::string validChars;
327 bool formatting;
328
329 RegExp regExp;
330 // | REG_NEWLINE | RE_DOT_NEWLINE); // | RE_DOT_NEWLINE); // | REG_NEWLINE | RE_DOT_NEWLINE
331
332};
333
334inline
335std::ostream & operator<<(std::ostream & ostr, const StringMapper & strmap){
336 return strmap.toStream(ostr);
337}
338
339// DRAIN_ENUM_DICT(StringMapper::KEEP_MISSING_VARIABLE);
340// template <> const drain::Enum<enumtype,owner>::dict_t drain::Enum<enumtype,owner>::dict
341// template <>
342// const drain::Enum<int,StringMapper>::dict_t drain::Enum<int,StringMapper>::dict;
343DRAIN_TYPENAME(StringMapper::handleMissing);
344
345DRAIN_ENUM_DICT(StringMapper::handleMissing);
346// DRAIN_ENUM_OSTREAM(StringMapper::handleMissing);
347
348
349} // NAMESPACE
350
351#endif /* STRINGMAPPER_H_ */
352
353// Drain
Stores precision, fillChar and fieldWidth applied by STD streams.
Definition IosFormat.h:45
Definition RegExp.h:58
static std::ostream & sequenceToStream(std::ostream &ostr, const T &x, const SprinterLayout &layout)
Convenience: if sequence type (array, list, set, map) not given, assume array.
Definition Sprinter.h:324
static const SprinterLayout emptyLayout
Simply concatenate values without punctuation.
Definition Sprinter.h:209
Definition StringMapper.h:114
bool isLiteral() const
Return true, if all the elements are literal.
Definition StringMapper.cpp:135
StringMapper(const StringMapper &mapper)
Copy constructor copies the parsed string and the regExp.
Definition StringMapper.h:145
StringMapper(const std::string &format="", const std::string &validChars="[a-zA-Z0-9_]+", bool formatting=true)
Default constructor.
Definition StringMapper.h:125
StringMapper & parse(const std::string &s, bool convertEscaped=false)
Converts a std::string containing variables like in "Hello, ${NAME}!" to a list of StringLet's.
Definition StringMapper.cpp:68
std::ostream & toStream(std::ostream &ostr, const std::map< std::string, T > &variables, int replace=REMOVE_MISSING_VARIABLE, const VariableFormatter< T > &formatter=VariableFormatter< T >()) const
Expands the variables in the last.
Definition StringMapper.h:225
void expand(const std::map< std::string, T > &m, const VariableFormatter< T > &formatter=VariableFormatter< T >(), bool clear=false)
Expands the variables in StringMapper, turning expanded variables to constants.
Definition StringMapper.h:268
std::ostream & debug(std::ostream &ostr, const std::map< std::string, T > &m) const
Dumps the list of StringLet's.
Definition StringMapper.h:285
StringMapper(const RegExp &regexp, bool formatting=true)
Initialize with the given RegExp // REMOVE!
Definition StringMapper.h:139
StringMapper & enableFormatting(bool formatting)
Enable variable formatting, followed by pipe '|'.
Definition StringMapper.h:167
std::ostream & toStream(std::ostream &ostr) const
Output a concatenated chain of stringlets: literals as such and variables surrounded with "${" and "}...
Definition StringMapper.h:204
std::string toStr(const std::map< std::string, T > &m, int replaceChar=-1, const VariableFormatter< T > &formatter=VariableFormatter< T >()) const
Expands the variables in the last parsed std::string to a std::string.
Definition StringMapper.h:256
A helper class for StringMapper.
Definition StringMapper.h:55
Stringlet(const Stringlet &s)
Copy constructor.
Definition StringMapper.h:63
Formats variables to output stream.
Definition VariableFormatter.h:71
virtual bool handle(const std::string &key, const map_t &variables, std::ostream &ostr) const
Searches given key in a map, and if found, processes (formats) the value to ostream....
Definition VariableFormatter.h:88
Definition DataSelector.cpp:1277