[libcalamares] don't inherit InstanceKey from std::pair

While tempting, none of the STL containers are intended
for inheritance, and there's risks of slicing when used
as value types. Make InstanceKey a regular value type
data class and add the few operators that we actually
used from std::pair by hand.
This commit is contained in:
Adriaan de Groot 2024-02-19 22:17:54 +01:00
parent c945cca93a
commit 0c9b3b2f16

View File

@ -15,6 +15,7 @@
#include <QList> #include <QList>
#include <QString> #include <QString>
#include <tuple>
#include <utility> #include <utility>
namespace Calamares namespace Calamares
@ -35,14 +36,13 @@ namespace ModuleSystem
* This is supported by the *instances* configuration entry * This is supported by the *instances* configuration entry
* in `settings.conf`. * in `settings.conf`.
*/ */
class InstanceKey : public std::pair< QString, QString > class InstanceKey
{ {
public: public:
using Base = std::pair< QString, QString >;
/// @brief Create an instance key from explicit module and id. /// @brief Create an instance key from explicit module and id.
InstanceKey( const QString& module, const QString& id ) InstanceKey( const QString& module, const QString& id )
: Base( module, id ) : first( module )
, second( id )
{ {
if ( second.isEmpty() ) if ( second.isEmpty() )
{ {
@ -52,10 +52,7 @@ public:
} }
/// @brief Create unusual, invalid instance key /// @brief Create unusual, invalid instance key
InstanceKey() InstanceKey() = default;
: Base( QString(), QString() )
{
}
/// @brief A valid module has both name and id /// @brief A valid module has both name and id
bool isValid() const { return !first.isEmpty() && !second.isEmpty(); } bool isValid() const { return !first.isEmpty() && !second.isEmpty(); }
@ -78,6 +75,16 @@ public:
return QString(); return QString();
} }
friend bool operator==( const InstanceKey& lhs, const InstanceKey& rhs ) noexcept
{
return std::tie( lhs.first, lhs.second ) == std::tie( rhs.first, rhs.second );
}
friend bool operator<( const InstanceKey& lhs, const InstanceKey& rhs ) noexcept
{
return std::tie( lhs.first, lhs.second ) < std::tie( rhs.first, rhs.second );
}
private: private:
/** @brief Check validity and reset module and id if needed. */ /** @brief Check validity and reset module and id if needed. */
void validate() void validate()
@ -88,11 +95,19 @@ private:
second = QString(); second = QString();
} }
} }
QString first;
QString second;
}; };
using InstanceKeyList = QList< InstanceKey >; using InstanceKeyList = QList< InstanceKey >;
QDebug& operator<<( QDebug& s, const Calamares::ModuleSystem::InstanceKey& i ); QDebug& operator<<( QDebug& s, const Calamares::ModuleSystem::InstanceKey& i );
inline QDebug&
operator<<( QDebug&& s, const Calamares::ModuleSystem::InstanceKey& i )
{
return s << i;
}
} // namespace ModuleSystem } // namespace ModuleSystem
} // namespace Calamares } // namespace Calamares