aboutsummaryrefslogtreecommitdiffstats
path: root/libqpdf/BitStream.cc
blob: 3b8e7022a449aae325b411f9c790a9ec95dc82d6 (plain) (blame)
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
#include <qpdf/BitStream.hh>

#include <qpdf/QIntC.hh>

// See comments in bits_include.cc
#define BITS_READ 1
#include "bits_include.cc"

BitStream::BitStream(unsigned char const* p, size_t nbytes) :
    start(p),
    nbytes(nbytes)
{
    reset();
}

void
BitStream::reset()
{
    p = start;
    bit_offset = 7;
    if (QIntC::to_uint(nbytes) > static_cast<unsigned int>(-1) / 8)
    {
        throw std::runtime_error("array too large for bitstream");
    }
    bits_available = 8 * nbytes;
}

unsigned long long
BitStream::getBits(size_t nbits)
{
    return read_bits(this->p, this->bit_offset,
                     this->bits_available, nbits);
}

long long
BitStream::getBitsSigned(size_t nbits)
{
    unsigned long long bits = read_bits(this->p, this->bit_offset,
                                        this->bits_available, nbits);
    long long result = 0;
    if (static_cast<long long>(bits) > 1LL << (nbits - 1))
    {
        result = static_cast<long long>(bits -(1ULL << nbits));
    }
    else
    {
        result = static_cast<long long>(bits);
    }
    return result;
}

int
BitStream::getBitsInt(size_t nbits)
{
    return static_cast<int>(
        QIntC::to_uint(
            read_bits(this->p, this->bit_offset,
                      this->bits_available, nbits)));
}

void
BitStream::skipToNextByte()
{
    if (bit_offset != 7)
    {
        size_t bits_to_skip = bit_offset + 1;
        if (bits_available < bits_to_skip)
        {
            throw std::logic_error(
                "INTERNAL ERROR: overflow skipping to next byte in bitstream");
        }
        bit_offset = 7;
        ++p;
        bits_available -= bits_to_skip;
    }
}