OpenMS  2.8.0
StringUtils.h
Go to the documentation of this file.
1 // --------------------------------------------------------------------------
2 // OpenMS -- Open-Source Mass Spectrometry
3 // --------------------------------------------------------------------------
4 // Copyright The OpenMS Team -- Eberhard Karls University Tuebingen,
5 // ETH Zurich, and Freie Universitaet Berlin 2002-2021.
6 //
7 // This software is released under a three-clause BSD license:
8 // * Redistributions of source code must retain the above copyright
9 // notice, this list of conditions and the following disclaimer.
10 // * Redistributions in binary form must reproduce the above copyright
11 // notice, this list of conditions and the following disclaimer in the
12 // documentation and/or other materials provided with the distribution.
13 // * Neither the name of any author or any participating institution
14 // may be used to endorse or promote products derived from this software
15 // without specific prior written permission.
16 // For a full list of authors, refer to the file AUTHORS.
17 // --------------------------------------------------------------------------
18 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
19 // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
20 // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
21 // ARE DISCLAIMED. IN NO EVENT SHALL ANY OF THE AUTHORS OR THE CONTRIBUTING
22 // INSTITUTIONS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
23 // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
24 // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
25 // OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
26 // WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
27 // OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
28 // ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29 //
30 // --------------------------------------------------------------------------
31 // $Maintainer: Timo Sachsenberg, Chris Bielow $
32 // $Authors: Marc Sturm, Stephan Aiche, Chris Bielow $
33 // --------------------------------------------------------------------------
34 
35 #pragma once
36 
37 #include <OpenMS/CONCEPT/Types.h>
43 
44 #include <QtCore/QString>
45 #include <boost/spirit/include/qi.hpp>
46 #include <boost/spirit/include/karma.hpp>
47 #include <boost/type_traits.hpp>
48 
49 #include <string>
50 #include <vector>
51 
52 
53 namespace OpenMS
54 {
55  class String;
56 
57  class OPENMS_DLLAPI StringUtilsHelper
58  {
59 
60 public:
61 
62  //
64  //
65  static Int toInt(const String & this_s)
66  {
67  Int ret;
68 
69  // boost::spirit::qi was found to be vastly superior to boost::lexical_cast or stringstream extraction (especially for VisualStudio),
70  // so don't change this unless you have benchmarks for all platforms!
71  String::ConstIterator it = this_s.begin();
72  if (!boost::spirit::qi::phrase_parse(it, this_s.end(), boost::spirit::qi::int_, boost::spirit::ascii::space, ret))
73  {
74  throw Exception::ConversionError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, String("Could not convert string '") + this_s + "' to an integer value");
75  }
76  // was the string parsed (white spaces are skipped automatically!) completely? If not, we have a problem because a previous split might have used the wrong split char
77  if (it != this_s.end())
78  {
79  throw Exception::ConversionError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, String("Prefix of string '") + this_s + "' successfully converted to an integer value. Additional characters found at position " + (int)(distance(this_s.begin(), it) + 1));
80  }
81  return ret;
82  }
83 
84  static float toFloat(const String& this_s)
85  {
86  float ret;
87 
88  // boost::spirit::qi was found to be vastly superior to boost::lexical_cast or stringstream extraction (especially for VisualStudio),
89  // so don't change this unless you have benchmarks for all platforms!
90  String::ConstIterator it = this_s.begin();
91  if (!boost::spirit::qi::phrase_parse(it, this_s.end(), parse_float_, boost::spirit::ascii::space, ret))
92  {
93  throw Exception::ConversionError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, String("Could not convert string '") + this_s + "' to a float value");
94  }
95  // was the string parsed (white spaces are skipped automatically!) completely? If not, we have a problem because a previous split might have used the wrong split char
96  if (it != this_s.end())
97  {
98  throw Exception::ConversionError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, String("Prefix of string '") + this_s + "' successfully converted to a float value. Additional characters found at position " + (int)(distance(this_s.begin(), it) + 1));
99  }
100  return ret;
101  }
102 
110  static double toDouble(const String& s)
111  {
112  double ret;
113  // boost::spirit::qi was found to be vastly superior to boost::lexical_cast or stringstream extraction (especially for VisualStudio),
114  // so don't change this unless you have benchmarks for all platforms!
115  String::ConstIterator it = s.begin();
116  if (!boost::spirit::qi::phrase_parse(it, s.end(), parse_double_, boost::spirit::ascii::space, ret))
117  {
118  throw Exception::ConversionError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, String("Could not convert string '") + s + "' to a double value");
119  }
120  // was the string parsed (white spaces are skipped automatically!) completely? If not, we have a problem because a previous split might have used the wrong split char
121  if (it != s.end())
122  {
123  throw Exception::ConversionError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, String("Prefix of string '") + s + "' successfully converted to a double value. Additional characters found at position " + (int)(distance(s.begin(), it) + 1));
124  }
125  return ret;
126  }
127 
132  template <typename IteratorT>
133  static bool extractDouble(IteratorT& begin, const IteratorT& end, double& target)
134  {
135  // boost::spirit::qi was found to be vastly superior to boost::lexical_cast or stringstream extraction (especially for VisualStudio),
136  // so don't change this unless you have benchmarks for all platforms!
137 
138  // qi::parse() does not consume whitespace before or after the double (qi::parse_phrase() would).
139  return boost::spirit::qi::parse(begin, end, parse_double_, target);
140  }
141 
142  private:
143 
144  /*
145  @brief A fixed Boost:pi real parser policy, capable of dealing with 'nan' without crashing
146 
147  The original Boost implementation has a bug, see https://svn.boost.org/trac/boost/ticket/6955.
148  Can be removed if Boost 1.60 or above is required
149 
150  */
151  template <typename T>
153  {
154  template <typename Iterator, typename Attribute>
155  static bool
156  parse_nan(Iterator& first, Iterator const& last, Attribute& attr_)
157  {
158  if (first == last)
159  return false; // end of input reached
160 
161  if (*first != 'n' && *first != 'N')
162  return false; // not "nan"
163 
164  // nan[(...)] ?
165  if (boost::spirit::qi::detail::string_parse("nan", "NAN", first, last, boost::spirit::qi::unused))
166  {
167  if (first != last && *first == '(') /* this check is broken in boost 1.49 - (at least) 1.54; fixed in 1.60 */
168  {
169  // skip trailing (...) part
170  Iterator i = first;
171 
172  while (++i != last && *i != ')')
173  ;
174  if (i == last)
175  return false; // no trailing ')' found, give up
176 
177  first = ++i;
178  }
179  attr_ = std::numeric_limits<T>::quiet_NaN();
180  return true;
181  }
182  return false;
183  }
184  };
185 
186  // Qi parsers using the 'real_policies_NANfixed_' template which allows for 'nan'
187  // (the original Boost implementation has a bug, see https://svn.boost.org/trac/boost/ticket/6955)
188  static boost::spirit::qi::real_parser<double, real_policies_NANfixed_<double> > parse_double_;
189  static boost::spirit::qi::real_parser<float, real_policies_NANfixed_<float> > parse_float_;
190 
191  };
192 
193  namespace StringUtils
194  {
195 
196  [[maybe_unused]] static String number(double d, UInt n)
197  {
198  return QString::number(d, 'f', n);
199  }
200 
201  [[maybe_unused]] static QString toQString(const String & this_s)
202  {
203  return QString(this_s.c_str());
204  }
205 
206  [[maybe_unused]] static Int toInt(const String & this_s)
207  {
208  return StringUtilsHelper::toInt(this_s);
209  }
210 
211  [[maybe_unused]] static float toFloat(const String & this_s)
212  {
213  return StringUtilsHelper::toFloat(this_s);
214  }
215 
216  [[maybe_unused]] static double toDouble(const String & this_s)
217  {
218  return StringUtilsHelper::toDouble(this_s);
219  }
220 
221  template <typename IteratorT>
222  static bool extractDouble(IteratorT& begin, const IteratorT& end, double& target)
223  {
224  return StringUtilsHelper::extractDouble(begin, end, target);
225  }
226 
227  }
228 } // namespace OPENMS
229 
Invalid conversion exception.
Definition: Exception.h:356
Definition: StringUtils.h:58
static double toDouble(const String &s)
convert String (leading and trailing whitespace allowed) to double
Definition: StringUtils.h:110
static bool extractDouble(IteratorT &begin, const IteratorT &end, double &target)
Definition: StringUtils.h:133
static Int toInt(const String &this_s)
Functions.
Definition: StringUtils.h:65
static float toFloat(const String &this_s)
Definition: StringUtils.h:84
static boost::spirit::qi::real_parser< double, real_policies_NANfixed_< double > > parse_double_
Definition: StringUtils.h:188
static boost::spirit::qi::real_parser< float, real_policies_NANfixed_< float > > parse_float_
Definition: StringUtils.h:189
A more convenient string class.
Definition: String.h:60
const_iterator ConstIterator
Const Iterator.
Definition: String.h:72
int Int
Signed integer type.
Definition: Types.h:102
unsigned int UInt
Unsigned integer type.
Definition: Types.h:94
static bool extractDouble(IteratorT &begin, const IteratorT &end, double &target)
Definition: StringUtils.h:222
static String number(double d, UInt n)
Definition: StringUtils.h:196
static Int toInt(const String &this_s)
Definition: StringUtils.h:206
static double toDouble(const String &this_s)
Definition: StringUtils.h:216
static float toFloat(const String &this_s)
Definition: StringUtils.h:211
static QString toQString(const String &this_s)
Definition: StringUtils.h:201
Main OpenMS namespace.
Definition: FeatureDeconvolution.h:47
static bool parse_nan(Iterator &first, Iterator const &last, Attribute &attr_)
Definition: StringUtils.h:156