38 {
39
40 if (duration.empty()) {
41 errmsg = "cannot parse empty string as a time duration";
42 return false;
43 }
44 if (duration == "0") {
45 result = std::chrono::steady_clock::duration(0);
46 return true;
47 }
48 std::chrono::steady_clock::duration dur(0);
49 auto strValue = duration;
50 while (!strValue.empty()) {
51 std::size_t pos;
52 double value;
53 try {
54 value = std::stod(strValue, &pos);
55 } catch (std::invalid_argument const &exc) {
56 errmsg = "Invalid number provided as timeout: " + strValue;
57 return false;
58 } catch (std::out_of_range const &exc) {
59 errmsg = "Provided timeout out of representable range: " + std::string(exc.what());
60 return false;
61 }
62 if (value < 0) {
63 errmsg = "Provided timeout was negative";
64 return false;
65 }
66 strValue = strValue.substr(pos);
67 char unit[3] = {'\0', '\0', '\0'};
68 if (!strValue.empty()) {
69 unit[0] = strValue[0];
70 if (unit[0] >= '0' && unit[0] <= '9') {unit[0] = '\0';}
71 }
72 if (strValue.size() > 1) {
73 unit[1] = strValue[1];
74 if (unit[1] >= '0' && unit[1] <= '9') {unit[1] = '\0';}
75 }
76 if (!strncmp(unit, "ns", 2)) {
77 dur += std::chrono::duration_cast<typeof(dur)>(std::chrono::duration<double, std::nano>(value));
78 } else if (!strncmp(unit, "us", 2)) {
79 dur += std::chrono::duration_cast<typeof(dur)>(std::chrono::duration<double, std::micro>(value));
80 } else if (!strncmp(unit, "ms", 2)) {
81 dur += std::chrono::duration_cast<typeof(dur)>(std::chrono::duration<double, std::milli>(value));
82 } else if (!strncmp(unit, "s", 1)) {
83 dur += std::chrono::duration_cast<typeof(dur)>(std::chrono::duration<double>(value));
84 } else if (!strncmp(unit, "m", 1)) {
85 dur += std::chrono::duration_cast<typeof(dur)>(std::chrono::duration<double, std::ratio<60>>(value));
86 } else if (!strncmp(unit, "h", 1)) {
87 dur += std::chrono::duration_cast<typeof(dur)>(std::chrono::duration<double, std::ratio<3600>>(value));
88 } else if (strlen(unit) > 0) {
89 errmsg = "Unknown unit in duration: " + std::string(unit);
90 return false;
91 } else {
92 errmsg = "Unit missing from duration: " + duration;
93 return false;
94 }
95 strValue = strValue.substr(strlen(unit));
96 }
97 result = dur;
98 return true;
99}