File indexing completed on 2024-04-28 16:06:18

0001 /* AUDEX CDDA EXTRACTOR
0002  * SPDX-FileCopyrightText: Copyright (C) 2007 Marco Nelles
0003  * <https://userbase.kde.org/Audex>
0004  *
0005  * SPDX-License-Identifier: GPL-3.0-or-later
0006  */
0007 
0008 #include "crc32hash.h"
0009 
0010 #include <QDebug>
0011 
0012 #define MASK1 0x00FFFFFF
0013 #define MASK2 0xFFFFFFFF
0014 #define POLYNOMIAL 0xEDB88320
0015 
0016 CRC32Hash::CRC32Hash(const quint32 initial_value)
0017 {
0018     p_initial_value = initial_value;
0019     init(initial_value);
0020 }
0021 
0022 CRC32Hash::CRC32Hash(const CRC32Hash &other)
0023 {
0024     crc32_accum = other.crc32_accum;
0025     memcpy(crc32_table, other.crc32_table, 256);
0026 }
0027 
0028 CRC32Hash &CRC32Hash::operator=(const CRC32Hash &other)
0029 {
0030     crc32_accum = other.crc32_accum;
0031     memcpy(crc32_table, other.crc32_table, 256);
0032     return *this;
0033 }
0034 
0035 bool CRC32Hash::operator==(const CRC32Hash &other) const
0036 {
0037     return result() == other.result();
0038 }
0039 
0040 bool CRC32Hash::operator!=(const CRC32Hash &other) const
0041 {
0042     return result() != other.result();
0043 }
0044 
0045 CRC32Hash::~CRC32Hash()
0046 {
0047 }
0048 
0049 void CRC32Hash::addData(const QByteArray &ba)
0050 {
0051     int length = ba.length();
0052     const unsigned char *buffer = reinterpret_cast<const unsigned char *>(ba.constData());
0053     while (length-- > 0)
0054         crc32_accum = ((crc32_accum >> 8) & MASK1) ^ crc32_table[(crc32_accum & 0xff) ^ *buffer++];
0055 }
0056 
0057 quint32 CRC32Hash::result() const
0058 {
0059     return (~crc32_accum) & MASK2;
0060 }
0061 
0062 void CRC32Hash::clear()
0063 {
0064     crc32_accum = p_initial_value;
0065 }
0066 
0067 void CRC32Hash::init(const quint32 initial_value)
0068 {
0069     crc32_accum = initial_value;
0070 
0071     for (int byte = 0; byte != 256; byte++) {
0072         quint32 data = byte;
0073 
0074         for (int i = 8; i > 0; --i)
0075             data = data & 1 ? (data >> 1) ^ POLYNOMIAL : data >> 1;
0076 
0077         crc32_table[byte] = data;
0078     }
0079 }