Add qHashBits(), a hash function for a memory block

The function arguments have been chosen to avoid caller-side casting of
argument types, when passing object addresses and type sizeof()s.

[ChangeLog][QtCore] Added qHashBits() to aid implementing qHash() overloads
for custom types.

Change-Id: I983a8560769bb27e489f23ebb6db51850ddd65f2
Reviewed-by: Thiago Macieira <thiago.macieira@intel.com>
This commit is contained in:
Marc Mutz 2014-02-12 14:10:35 +01:00 committed by The Qt Project
parent f4ffe2a243
commit 12372960f8
3 changed files with 36 additions and 0 deletions

View File

@ -297,3 +297,13 @@ while (i != hash.end() && i.key() == "plenty") {
++i;
}
//! [26]
//! [qhashbits]
inline uint qHash(const std::vector<int> &key, uint seed = 0)
{
if (key.empty())
return seed;
else
return qHashBits(&key.front(), key.size() * sizeof(int), seed);
}
//! [qhashbits]

View File

@ -163,6 +163,11 @@ static inline uint hash(const uchar *p, int len, uint seed) Q_DECL_NOTHROW
return h;
}
uint qHashBits(const void *p, size_t len, uint seed) Q_DECL_NOTHROW
{
return hash(static_cast<const uchar*>(p), int(len), seed);
}
static inline uint hash(const QChar *p, int len, uint seed) Q_DECL_NOTHROW
{
uint h = seed;
@ -669,6 +674,25 @@ void QHashData::checkSanity()
Types \c T1 and \c T2 must be supported by qHash().
*/
/*! \fn uint qHashBits(const void *p, size_t len, uint seed = 0)
\relates QHash
\since 5.4
Returns the hash value for the memory block of size \a len pointed
to by \a p, using \a seed to seed the calculation.
Use this function only to implement qHash() for your own custom
types. E.g., here's how you could implement a qHash() overload for
std::vector<int>:
\snippet code/src_corelib_tools_qhash.cpp qhashbits
It bears repeating that the implementation of qHashBits() - like
the qHash() overloads offered by Qt - may change at any time. You
\b{must not} rely on the fact that qHashBits() will give the same
results (for the same inputs) across different Qt versions.
*/
/*! \fn uint qHash(char key, uint seed = 0)
\relates QHash
\since 5.0

View File

@ -60,6 +60,8 @@ class QString;
class QStringRef;
class QLatin1String;
Q_CORE_EXPORT uint qHashBits(const void *p, size_t size, uint seed = 0) Q_DECL_NOTHROW;
inline uint qHash(char key, uint seed = 0) Q_DECL_NOTHROW { return uint(key) ^ seed; }
inline uint qHash(uchar key, uint seed = 0) Q_DECL_NOTHROW { return uint(key) ^ seed; }
inline uint qHash(signed char key, uint seed = 0) Q_DECL_NOTHROW { return uint(key) ^ seed; }