Fix clazy warnings regarding range-for references
[pulseview.git] / pv / util.cpp
index 7d711f197013e65dcccca8172e14b9b29239bca6..49b9467c1642737a1a995df5adcb622e2bbddfa1 100644 (file)
 
 #include <extdef.h>
 
-#include <cassert>
 #include <algorithm>
+#include <cassert>
 #include <sstream>
 
-#include <QTextStream>
 #include <QDebug>
+#include <QTextStream>
 
 using std::fixed;
 using std::max;
@@ -144,6 +144,41 @@ QString format_time_si(const Timestamp& v, SIPrefix prefix,
        return s;
 }
 
+QString format_value_si(double v, SIPrefix prefix, unsigned precision,
+       QString unit, bool sign)
+{
+       if (prefix == SIPrefix::unspecified) {
+               // No prefix given, calculate it
+
+               if (v == 0) {
+                       prefix = SIPrefix::none;
+               } else {
+                       int exp = exponent(SIPrefix::yotta);
+                       prefix = SIPrefix::yocto;
+                       while ((fabs(v) * pow(Timestamp(10), exp)) > 999 &&
+                                       prefix < SIPrefix::yotta) {
+                               prefix = successor(prefix);
+                               exp -= 3;
+                       }
+               }
+       }
+
+       assert(prefix >= SIPrefix::yocto);
+       assert(prefix <= SIPrefix::yotta);
+
+       const double multiplier = pow(10.0, -exponent(prefix));
+
+       QString s;
+       QTextStream ts(&s);
+       if (sign && (v != 0))
+               ts << forcesign;
+       ts.setRealNumberNotation(QTextStream::FixedNotation);
+       ts.setRealNumberPrecision(precision);
+       ts << (v * multiplier) << ' ' << prefix << unit;
+
+       return s;
+}
+
 QString format_time_si_adjusted(const Timestamp& t, SIPrefix prefix,
        unsigned precision, QString unit, bool sign)
 {
@@ -224,5 +259,27 @@ QString format_time_minutes(const Timestamp& t, signed precision, bool sign)
        return s;
 }
 
+/**
+ * Split a string into tokens at occurences of the separator.
+ *
+ * @param[in] text The input string to split.
+ * @param[in] separator The delimiter between tokens.
+ *
+ * @return A vector of broken down tokens.
+ */
+vector<string> split_string(string text, string separator)
+{
+       vector<string> result;
+       size_t pos;
+
+       while ((pos = text.find(separator)) != std::string::npos) {
+               result.push_back(text.substr(0, pos));
+               text = text.substr(pos + separator.length());
+       }
+       result.push_back(text);
+
+       return result;
+}
+
 } // namespace util
 } // namespace pv