1
2/*
3 SPDX-FileCopyrightText: 2021 Volker Krause <vkrause@kde.org>
4
5 SPDX-License-Identifier: LGPL-2.0-or-later
6*/
7
8#include "kcodecs.h"
9#include "kcodecs_debug.h"
10
11#include <QDebug>
12
13static constexpr const char base45Table[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ $%*+-./:";
14
15static uint8_t base45MapFromChar(char c)
16{
17 const auto it = std::find(first: std::begin(arr: base45Table), last: std::end(arr: base45Table), val: c);
18 if (it == std::end(arr: base45Table)) {
19 qCWarning(KCODECS_LOG) << "invalid base45 character:" << c;
20 return 0;
21 }
22 return std::distance(first: std::begin(arr: base45Table), last: it);
23}
24
25QByteArray KCodecs::base45Decode(QByteArrayView in)
26{
27 QByteArray out;
28 out.reserve(asize: ((in.size() / 3) + 1) * 2);
29
30 for (qsizetype i = 0; i + 1 < in.size(); i += 3) {
31 uint32_t n = base45MapFromChar(c: in[i]) + base45MapFromChar(c: in[i + 1]) * 45;
32 if (i + 2 < in.size()) {
33 n += 45 * 45 * base45MapFromChar(c: in[i + 2]);
34 out.push_back(c: n >> 8);
35 } else {
36 if (n >> 8) {
37 out.push_back(c: n >> 8);
38 }
39 }
40 out.push_back(c: n % 256);
41 }
42
43 return out;
44}
45

source code of kcodecs/src/kcodecsbase45.cpp