Coverage Report

Created: 2025-06-22 06:30

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