Gravatar

hash.cpp
1/*
2 SPDX-FileCopyrightText: 2017 Volker Krause <vkrause@kde.org>
3
4 SPDX-License-Identifier: LGPL-2.0-or-later
5*/
6
7#include "hash.h"
8
9#include <QHash>
10#include <QString>
11
12using namespace Gravatar;
13
14Hash::Hash()
15 : m_type(Invalid)
16{
17}
18
19Hash::Hash(const QByteArray &data, Type type)
20 : m_type(type)
21{
22 switch (type) {
23 case Invalid:
24 break;
25 case Md5:
26 Q_ASSERT(sizeof(Hash128) == data.size());
27 m_hash.md5 = *reinterpret_cast<const Hash128 *>(data.constData());
28 break;
29 case Sha256:
30 Q_ASSERT(sizeof(Hash256) == data.size());
31 m_hash.sha256 = *reinterpret_cast<const Hash256 *>(data.constData());
32 break;
33 }
34}
35
36bool Hash::operator==(const Hash &other) const
37{
38 if (m_type != other.m_type) {
39 return false;
40 }
41 switch (m_type) {
42 case Invalid:
43 return true;
44 case Md5:
45 return m_hash.md5 == other.m_hash.md5;
46 case Sha256:
47 return m_hash.sha256 == other.m_hash.sha256;
48 }
49 Q_UNREACHABLE();
50}
51
52bool Hash::isValid() const
53{
54 return m_type != Invalid;
55}
56
57Hash::Type Hash::type() const
58{
59 return m_type;
60}
61
62Hash128 Hash::md5() const
63{
64 return m_hash.md5;
65}
66
67Hash256 Hash::sha256() const
68{
69 return m_hash.sha256;
70}
71
72QString Hash::hexString() const
73{
74 switch (m_type) {
75 case Invalid:
76 return {};
77 case Md5:
78 return QString::fromLatin1(QByteArray::fromRawData(reinterpret_cast<const char *>(&m_hash.md5), sizeof(Hash128)).toHex());
79 case Sha256:
80 return QString::fromLatin1(QByteArray::fromRawData(reinterpret_cast<const char *>(&m_hash.sha256), sizeof(Hash256)).toHex());
81 }
82 Q_UNREACHABLE();
83}
84
85size_t Gravatar::qHash(const Hash &h, size_t seed) noexcept
86{
87 switch (h.type()) {
88 case Hash::Invalid:
89 return seed;
90 case Hash::Md5:
91 return qHashBits(&h.m_hash.md5, sizeof(Hash128), seed);
92 case Hash::Sha256:
93 return qHashBits(&h.m_hash.sha256, sizeof(Hash256), seed);
94 }
95 Q_UNREACHABLE();
96}
Type type(const QSqlDatabase &db)
const char * constData() const const
QByteArray fromRawData(const char *data, qsizetype size)
qsizetype size() const const
QByteArray toHex(char separator) const const
QString fromLatin1(QByteArrayView str)
This file is part of the KDE documentation.
Documentation copyright © 1996-2024 The KDE developers.
Generated on Mon Nov 18 2024 12:07:15 by doxygen 1.12.0 written by Dimitri van Heesch, © 1997-2006

KDE's Doxygen guidelines are available online.