Coverage Report

Created: 2025-07-14 06:17

/src/qpdf/libqpdf/Pl_ASCIIHexDecoder.cc
Line
Count
Source (jump to first uncovered line)
1
#include <qpdf/Pl_ASCIIHexDecoder.hh>
2
3
#include <qpdf/QTC.hh>
4
#include <cctype>
5
#include <stdexcept>
6
7
using namespace std::literals;
8
9
Pl_ASCIIHexDecoder::Pl_ASCIIHexDecoder(char const* identifier, Pipeline* next) :
10
2.74k
    Pipeline(identifier, next)
11
2.74k
{
12
2.74k
    if (!next) {
13
0
        throw std::logic_error("Attempt to create Pl_ASCIIHexDecoder with nullptr as next");
14
0
    }
15
2.74k
}
16
17
void
18
Pl_ASCIIHexDecoder::write(unsigned char const* buf, size_t len)
19
3.62k
{
20
3.62k
    if (eod) {
21
710
        return;
22
710
    }
23
281k
    for (size_t i = 0; i < len; ++i) {
24
279k
        char ch = static_cast<char>(toupper(buf[i]));
25
279k
        switch (ch) {
26
561
        case ' ':
27
810
        case '\f':
28
1.15k
        case '\v':
29
1.80k
        case '\t':
30
2.21k
        case '\r':
31
2.62k
        case '\n':
32
2.62k
            QTC::TC("libtests", "Pl_ASCIIHexDecoder ignore space");
33
            // ignore whitespace
34
2.62k
            break;
35
36
160
        case '>':
37
160
            eod = true;
38
160
            flush();
39
160
            break;
40
41
276k
        default:
42
276k
            if ((ch >= '0' && ch <= '9') || (ch >= 'A' && ch <= 'F')) {
43
275k
                inbuf[pos++] = ch;
44
275k
                if (pos == 2) {
45
137k
                    flush();
46
137k
                }
47
275k
            } else {
48
585
                char t[2];
49
585
                t[0] = ch;
50
585
                t[1] = 0;
51
585
                throw std::runtime_error("character out of range during base Hex decode: "s + t);
52
585
            }
53
275k
            break;
54
279k
        }
55
278k
        if (eod) {
56
159
            break;
57
159
        }
58
278k
    }
59
2.91k
}
60
61
void
62
Pl_ASCIIHexDecoder::flush()
63
140k
{
64
140k
    if (pos == 0) {
65
1.88k
        QTC::TC("libtests", "Pl_ASCIIHexDecoder no-op flush");
66
1.88k
        return;
67
1.88k
    }
68
138k
    int b[2];
69
414k
    for (int i = 0; i < 2; ++i) {
70
276k
        if (inbuf[i] >= 'A') {
71
57.1k
            b[i] = inbuf[i] - 'A' + 10;
72
219k
        } else {
73
219k
            b[i] = inbuf[i] - '0';
74
219k
        }
75
276k
    }
76
138k
    auto ch = static_cast<unsigned char>((b[0] << 4) + b[1]);
77
78
138k
    QTC::TC("libtests", "Pl_ASCIIHexDecoder partial flush", (pos == 2) ? 0 : 1);
79
    // Reset before calling getNext()->write in case that throws an exception.
80
138k
    pos = 0;
81
138k
    inbuf[0] = '0';
82
138k
    inbuf[1] = '0';
83
138k
    inbuf[2] = '\0';
84
85
138k
    next()->write(&ch, 1);
86
138k
}
87
88
void
89
Pl_ASCIIHexDecoder::finish()
90
2.37k
{
91
2.37k
    flush();
92
2.37k
    next()->finish();
93
2.37k
}