File: Pl_ASCIIHexDecoder.cc

package info (click to toggle)
qpdf 12.3.0-1
  • links: PTS
  • area: main
  • in suites: forky, sid
  • size: 72,644 kB
  • sloc: cpp: 59,031; perl: 12,172; ansic: 6,809; sh: 1,231; python: 1,041; xml: 43; makefile: 42
file content (94 lines) | stat: -rw-r--r-- 2,156 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
#include <qpdf/Pl_ASCIIHexDecoder.hh>

#include <qpdf/QTC.hh>
#include <qpdf/Util.hh>

#include <cctype>
#include <stdexcept>

using namespace qpdf;
using namespace std::literals;

Pl_ASCIIHexDecoder::Pl_ASCIIHexDecoder(char const* identifier, Pipeline* next) :
    Pipeline(identifier, next)
{
    util::assertion(next, "Attempt to create Pl_ASCIIHexDecoder with nullptr as next");
}

void
Pl_ASCIIHexDecoder::write(unsigned char const* buf, size_t len)
{
    if (eod) {
        return;
    }
    for (size_t i = 0; i < len; ++i) {
        char ch = static_cast<char>(toupper(buf[i]));
        switch (ch) {
        case ' ':
        case '\f':
        case '\v':
        case '\t':
        case '\r':
        case '\n':
            QTC::TC("libtests", "Pl_ASCIIHexDecoder ignore space");
            // ignore whitespace
            break;

        case '>':
            eod = true;
            flush();
            break;

        default:
            if ((ch >= '0' && ch <= '9') || (ch >= 'A' && ch <= 'F')) {
                inbuf[pos++] = ch;
                if (pos == 2) {
                    flush();
                }
            } else {
                char t[2];
                t[0] = ch;
                t[1] = 0;
                throw std::runtime_error("character out of range during base Hex decode: "s + t);
            }
            break;
        }
        if (eod) {
            break;
        }
    }
}

void
Pl_ASCIIHexDecoder::flush()
{
    if (pos == 0) {
        QTC::TC("libtests", "Pl_ASCIIHexDecoder no-op flush");
        return;
    }
    int b[2];
    for (int i = 0; i < 2; ++i) {
        if (inbuf[i] >= 'A') {
            b[i] = inbuf[i] - 'A' + 10;
        } else {
            b[i] = inbuf[i] - '0';
        }
    }
    auto ch = static_cast<unsigned char>((b[0] << 4) + b[1]);

    QTC::TC("libtests", "Pl_ASCIIHexDecoder partial flush", (pos == 2) ? 0 : 1);
    // Reset before calling getNext()->write in case that throws an exception.
    pos = 0;
    inbuf[0] = '0';
    inbuf[1] = '0';
    inbuf[2] = '\0';

    next()->write(&ch, 1);
}

void
Pl_ASCIIHexDecoder::finish()
{
    flush();
    next()->finish();
}