File indexing completed on 2024-05-19 04:39:20

0001 /*
0002     SPDX-FileCopyrightText: 2012 Olivier de Gaalon <olivier.jg@gmail.com>
0003 
0004     SPDX-License-Identifier: LGPL-2.0-only
0005 */
0006 
0007 #ifndef KDEVPLATFORM_KDEVHASH_H
0008 #define KDEVPLATFORM_KDEVHASH_H
0009 
0010 #include <QHash>
0011 
0012 /**
0013  * A helper class to implement hashing for aggregate types.
0014  *
0015  * @code
0016  * class MyType {
0017  *     ...
0018  *     uint hash() const
0019  *     {
0020  *         KDevHash hash;
0021  *         return hash << m_1 << m_2 << ...;
0022  *     }
0023  * };
0024  * @endcode
0025  */
0026 class KDevHash
0027 {
0028 public:
0029     enum {
0030         DEFAULT_SEED = 2166136261u
0031     };
0032 
0033     explicit KDevHash(uint hash = DEFAULT_SEED)
0034         : m_hash(hash)
0035     {}
0036 
0037     KDevHash(const KDevHash&) = delete;
0038     KDevHash& operator=(const KDevHash&) = delete;
0039 
0040     inline operator uint() const
0041     {
0042         return m_hash;
0043     }
0044 
0045     template <typename T>
0046     inline KDevHash& operator<<(T value)
0047     {
0048         m_hash = hash_combine(m_hash, qHash(value));
0049         return *this;
0050     }
0051 
0052     static inline uint hash_combine(uint seed, uint hash)
0053     {
0054         // this is copied from boost::hash_combine
0055         return seed ^ (hash + 0x9e3779b9 + (seed << 6) + (seed >> 2));
0056     }
0057 
0058 private:
0059     uint m_hash;
0060 };
0061 
0062 #endif //KDEVPLATFORM_KDEVHASH_H