工作中需要存储比较庞大的数据,需要通过压缩算法进行解压缩节约内存,存进去前压缩,读出后解压。
#include <QByteArray>
#include <zstd.h>
class ZstdHelper {
public:
static QByteArray compress(const QString& data) {
QByteArray input = data.toUtf8();
size_t compressedSize = ZSTD_compressBound(input.size());
QByteArray compressed(compressedSize, 0);
compressedSize = ZSTD_compress(compressed.data(), compressedSize, input.constData(), input.size(), 1);
if (ZSTD_isError(compressedSize)) {
return QByteArray();
}
compressed.resize(compressedSize);
return compressed;
}
static QString decompress(const QByteArray& compressedData) {
size_t decompressedSize = ZSTD_getDecompressedSize(compressedData.constData(), compressedData.size());
QByteArray decompressed(decompressedSize, 0);
decompressedSize = ZSTD_decompress(decompressed.data(), decompressedSize, compressedData.constData(), compressedData.size());
if (ZSTD_isError(decompressedSize)) {
return QString();
}
return QString::fromUtf8(decompressed);
}
};
int main() {
QString originalData = "Hello, World!";
// 压缩数据
QByteArray compressedData = ZstdHelper::compress(originalData);
// 解压数据
QString decompressedData = ZstdHelper::decompress(compressedData);
return 0;
}