From 45dabbfe2b50d9afb0b9b64aa1bc04652b03dc17 Mon Sep 17 00:00:00 2001 From: Mark Olesen Date: Fri, 7 Jul 2017 12:33:41 +0200 Subject: [PATCH] ENH: provide Enum failsafe lookup - if the enum name is not found, then warn and return the default. --- src/OpenFOAM/primitives/enums/Enum.C | 31 ++++++++++++++++++++++++++-- src/OpenFOAM/primitives/enums/Enum.H | 12 +++++++++++ 2 files changed, 41 insertions(+), 2 deletions(-) diff --git a/src/OpenFOAM/primitives/enums/Enum.C b/src/OpenFOAM/primitives/enums/Enum.C index 8b4f2100f0..76f1323b8a 100644 --- a/src/OpenFOAM/primitives/enums/Enum.C +++ b/src/OpenFOAM/primitives/enums/Enum.C @@ -215,10 +215,37 @@ EnumType Foam::Enum::lookupOrDefault { return lookup(key, dict); } - else + + return deflt; +} + + +template +EnumType Foam::Enum::lookupOrFailsafe +( + const word& key, + const dictionary& dict, + const EnumType deflt +) const +{ + if (dict.found(key)) { - return deflt; + const word enumName(dict.lookup(key)); + const label idx = getIndex(enumName); + + if (idx < 0) + { + IOWarningInFunction(dict) + << "bad " << key <<" specifier " << enumName + << " using " << getName(deflt) << endl; + } + else + { + return EnumType(values_[idx]); + } } + + return deflt; } diff --git a/src/OpenFOAM/primitives/enums/Enum.H b/src/OpenFOAM/primitives/enums/Enum.H index dde620fb26..b57fc9891a 100644 --- a/src/OpenFOAM/primitives/enums/Enum.H +++ b/src/OpenFOAM/primitives/enums/Enum.H @@ -161,6 +161,18 @@ public: ) const; + //- Find the key in the dictionary and return the corresponding + // enumeration element based on its name. + // Return the default value if the key was not found in the dictionary + // or if the enumerated name was incorrect (emit warning) + EnumType lookupOrFailsafe + ( + const word& key, + const dictionary& dict, + const EnumType deflt + ) const; + + // IO //- Read a word from Istream and return the corresponding enumeration