Coverage Report

Created: 2025-07-14 06:14

/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
141
    Pipeline(identifier, next)
11
141
{
12
141
    if (!next) {
13
0
        throw std::logic_error("Attempt to create Pl_ASCIIHexDecoder with nullptr as next");
14
0
    }
15
141
}
16
17
void
18
Pl_ASCIIHexDecoder::write(unsigned char const* buf, size_t len)
19
141
{
20
141
    if (eod) {
21
0
        return;
22
0
    }
23
16.4k
    for (size_t i = 0; i < len; ++i) {
24
16.3k
        char ch = static_cast<char>(toupper(buf[i]));
25
16.3k
        switch (ch) {
26
210
        case ' ':
27
440
        case '\f':
28
674
        case '\v':
29
885
        case '\t':
30
1.07k
        case '\r':
31
1.42k
        case '\n':
32
1.42k
            QTC::TC("libtests", "Pl_ASCIIHexDecoder ignore space");
33
            // ignore whitespace
34
1.42k
            break;
35
36
8
        case '>':
37
8
            eod = true;
38
8
            flush();
39
8
            break;
40
41
14.8k
        default:
42
14.8k
            if ((ch >= '0' && ch <= '9') || (ch >= 'A' && ch <= 'F')) {
43
14.8k
                inbuf[pos++] = ch;
44
14.8k
                if (pos == 2) {
45
7.41k
                    flush();
46
7.41k
                }
47
14.8k
            } else {
48
42
                char t[2];
49
42
                t[0] = ch;
50
42
                t[1] = 0;
51
42
                throw std::runtime_error("character out of range during base Hex decode: "s + t);
52
42
            }
53
14.8k
            break;
54
16.3k
        }
55
16.2k
        if (eod) {
56
8
            break;
57
8
        }
58
16.2k
    }
59
141
}
60
61
void
62
Pl_ASCIIHexDecoder::flush()
63
7.51k
{
64
7.51k
    if (pos == 0) {
65
82
        QTC::TC("libtests", "Pl_ASCIIHexDecoder no-op flush");
66
82
        return;
67
82
    }
68
7.43k
    int b[2];
69
22.3k
    for (int i = 0; i < 2; ++i) {
70
14.8k
        if (inbuf[i] >= 'A') {
71
14.3k
            b[i] = inbuf[i] - 'A' + 10;
72
14.3k
        } else {
73
569
            b[i] = inbuf[i] - '0';
74
569
        }
75
14.8k
    }
76
7.43k
    auto ch = static_cast<unsigned char>((b[0] << 4) + b[1]);
77
78
7.43k
    QTC::TC("libtests", "Pl_ASCIIHexDecoder partial flush", (pos == 2) ? 0 : 1);
79
    // Reset before calling getNext()->write in case that throws an exception.
80
7.43k
    pos = 0;
81
7.43k
    inbuf[0] = '0';
82
7.43k
    inbuf[1] = '0';
83
7.43k
    inbuf[2] = '\0';
84
85
7.43k
    next()->write(&ch, 1);
86
7.43k
}
87
88
void
89
Pl_ASCIIHexDecoder::finish()
90
99
{
91
99
    flush();
92
99
    next()->finish();
93
99
}