Base: fix UnitsSchema::translate

Schema translation previously returned factor 0 and unit string
of input quantity if there was no translation match. Restore
that behaviour as well as returned factor and unit string of
imperial schemas.

Fixes: 1155f0d752 ("Base: simplify UnitsSchemas management")
This commit is contained in:
Ladislav Michl
2025-05-27 12:08:05 +02:00
parent e5e251df8f
commit bcd23743f4
2 changed files with 22 additions and 14 deletions

View File

@@ -53,22 +53,20 @@ std::string UnitsSchema::translate(const Quantity& quant) const
std::string
UnitsSchema::translate(const Quantity& quant, double& factor, std::string& unitString) const
{
// Use defaults without schema-level translation.
factor = 1.0;
unitString = quant.getUnit().getString();
if (spec.translationSpecs.empty()) {
return toLocale(quant, 1.0, unitString);
return toLocale(quant, factor, unitString);
}
const auto unitName = quant.getUnit().getTypeString();
if (spec.translationSpecs.count(unitName) == 0) {
// no schema-level translation. Use defaults.
factor = 1.0;
unitString = quant.getUnit().getString();
if (!spec.translationSpecs.contains(unitName)) {
return toLocale(quant, factor, unitString);
}
const auto value = quant.getValue();
auto isSuitable = [&](const UnitTranslationSpec& row) {
return row.threshold > value || row.threshold == 0; // zero indicates default
};
@@ -81,7 +79,7 @@ UnitsSchema::translate(const Quantity& quant, double& factor, std::string& unitS
}
if (unitSpec->factor == 0) {
return UnitsSchemasData::runSpecial(unitSpec->unitString, value);
return UnitsSchemasData::runSpecial(unitSpec->unitString, value, factor, unitString);
}
factor = unitSpec->factor;

View File

@@ -733,17 +733,27 @@ inline std::string toDms(const double value)
* Special functions caller
*/
inline const std::map<std::string, std::function<std::string(double)>> specials // clang-format off
// clang-format off
inline const std::map<std::string, std::function<std::string(double, double&, std::string&)>> specials
{
{
{ "toDMS" , [](const double val) { return toDms(val); }},
{ "toFractional" , [](const double val) { return toFractional(val); }}
{ "toDMS" , [](const double val, double& factor, std::string& unitString) {
factor = 1.0;
unitString = "deg";
return toDms(val);
}},
{ "toFractional" , [](const double val, double& factor, std::string& unitString) {
factor = 25.4;
unitString = "in";
return toFractional(val);
}}
}
}; // clang-format on
inline std::string runSpecial(const std::string& name, const double value)
inline std::string
runSpecial(const std::string& name, const double value, double& factor, std::string& unitString)
{
return specials.contains(name) ? specials.at(name)(value) : "";
return specials.contains(name) ? specials.at(name)(value, factor, unitString) : "";
}