improve touchstone parsing robustness

This commit is contained in:
Jan Käberich 2023-02-10 11:41:53 +01:00
parent 8aec59f32b
commit ea4c637842

View File

@ -1,6 +1,7 @@
#include "touchstone.h" #include "touchstone.h"
#include "Util/util.h" #include "Util/util.h"
#include "unit.h"
#include <limits> #include <limits>
#include <algorithm> #include <algorithm>
@ -162,14 +163,16 @@ Touchstone Touchstone::fromFile(string filename)
Datapoint point; Datapoint point;
string line; string line;
unsigned int lineCnt = 0;
while(getline(file, line)) { while(getline(file, line)) {
lineCnt++;
// remove comments // remove comments
auto comment = line.find_first_of('!'); auto comment = line.find_first_of('!');
if(comment != string::npos) { if(comment != string::npos) {
line.erase(comment); line.erase(comment);
} }
// remove leading whitespace // remove leading whitespace
size_t first = line.find_first_not_of(" \t"); size_t first = line.find_first_not_of(" \t\r\n");
if (string::npos == first) { if (string::npos == first) {
// string does only contain whitespace, skip line // string does only contain whitespace, skip line
continue; continue;
@ -231,10 +234,11 @@ Touchstone Touchstone::fromFile(string filename)
if(!option_line_found) { if(!option_line_found) {
throw runtime_error("First dataline before option line"); throw runtime_error("First dataline before option line");
} }
auto parseDatapoint = [format](istream &in) -> complex<double> { auto parseDatapoint = [format, &point, &lineCnt](istream &in) -> complex<double> {
double part1, part2; double part1, part2;
in >> part1; if(!(in >> part1) || !(in >> part2)) {
in >> part2; throw runtime_error("Failed to parse parameters on line "+std::to_string(lineCnt)+" with frequency "+Unit::ToString(point.frequency,"Hz", " kMG", 10).toStdString());
}
complex<double> ret; complex<double> ret;
switch(format) { switch(format) {
case Format::MagnitudeAngle: case Format::MagnitudeAngle: