File indexing completed on 2024-11-24 04:49:03

0001 /*
0002    SPDX-FileCopyrightText: 2017 Volker Krause <vkrause@kde.org>
0003 
0004    SPDX-License-Identifier: LGPL-2.0-or-later
0005 */
0006 
0007 #include "hash.h"
0008 
0009 #include <QHash>
0010 #include <QString>
0011 
0012 using namespace Gravatar;
0013 
0014 Hash::Hash()
0015     : m_type(Invalid)
0016 {
0017 }
0018 
0019 Hash::Hash(const QByteArray &data, Type type)
0020     : m_type(type)
0021 {
0022     switch (type) {
0023     case Invalid:
0024         break;
0025     case Md5:
0026         Q_ASSERT(sizeof(Hash128) == data.size());
0027         m_hash.md5 = *reinterpret_cast<const Hash128 *>(data.constData());
0028         break;
0029     case Sha256:
0030         Q_ASSERT(sizeof(Hash256) == data.size());
0031         m_hash.sha256 = *reinterpret_cast<const Hash256 *>(data.constData());
0032         break;
0033     }
0034 }
0035 
0036 bool Hash::operator==(const Hash &other) const
0037 {
0038     if (m_type != other.m_type) {
0039         return false;
0040     }
0041     switch (m_type) {
0042     case Invalid:
0043         return true;
0044     case Md5:
0045         return m_hash.md5 == other.m_hash.md5;
0046     case Sha256:
0047         return m_hash.sha256 == other.m_hash.sha256;
0048     }
0049     Q_UNREACHABLE();
0050 }
0051 
0052 bool Hash::isValid() const
0053 {
0054     return m_type != Invalid;
0055 }
0056 
0057 Hash::Type Hash::type() const
0058 {
0059     return m_type;
0060 }
0061 
0062 Hash128 Hash::md5() const
0063 {
0064     return m_hash.md5;
0065 }
0066 
0067 Hash256 Hash::sha256() const
0068 {
0069     return m_hash.sha256;
0070 }
0071 
0072 QString Hash::hexString() const
0073 {
0074     switch (m_type) {
0075     case Invalid:
0076         return {};
0077     case Md5:
0078         return QString::fromLatin1(QByteArray::fromRawData(reinterpret_cast<const char *>(&m_hash.md5), sizeof(Hash128)).toHex());
0079     case Sha256:
0080         return QString::fromLatin1(QByteArray::fromRawData(reinterpret_cast<const char *>(&m_hash.sha256), sizeof(Hash256)).toHex());
0081     }
0082     Q_UNREACHABLE();
0083 }
0084 
0085 size_t Gravatar::qHash(const Hash &h, size_t seed) noexcept
0086 {
0087     switch (h.type()) {
0088     case Hash::Invalid:
0089         return seed;
0090     case Hash::Md5:
0091         return qHashBits(&h.m_hash.md5, sizeof(Hash128), seed);
0092     case Hash::Sha256:
0093         return qHashBits(&h.m_hash.sha256, sizeof(Hash256), seed);
0094     }
0095     Q_UNREACHABLE();
0096 }