aboutsummaryrefslogtreecommitdiffstats
path: root/libqpdf/Pl_Buffer.cc
blob: 3a41c579baa4f44c9370fbe424a2067b7ddeedf0 (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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
#include <qpdf/Pl_Buffer.hh>

#include <stdexcept>
#include <algorithm>
#include <assert.h>
#include <string.h>
#include <stdlib.h>

Pl_Buffer::Members::Members() :
    ready(true),
    total_size(0)
{
}

Pl_Buffer::Members::~Members()
{
}

Pl_Buffer::Pl_Buffer(char const* identifier, Pipeline* next) :
    Pipeline(identifier, next),
    m(new Members())
{
}

Pl_Buffer::~Pl_Buffer()
{
}

void
Pl_Buffer::write(unsigned char* buf, size_t len)
{
    if (this->m->data.get() == 0)
    {
        this->m->data = new Buffer(len);
    }
    size_t cur_size = this->m->data->getSize();
    size_t left = cur_size - this->m->total_size;
    if (left < len)
    {
        size_t new_size = std::max(this->m->total_size + len, 2 * cur_size);
        PointerHolder<Buffer> b = new Buffer(new_size);
        memcpy(b->getBuffer(), this->m->data->getBuffer(), this->m->total_size);
        this->m->data = b;
    }
    if (len)
    {
        memcpy(this->m->data->getBuffer() + this->m->total_size, buf, len);
        this->m->total_size += len;
    }
    this->m->ready = false;

    if (getNext(true))
    {
	getNext()->write(buf, len);
    }
}

void
Pl_Buffer::finish()
{
    this->m->ready = true;
    if (getNext(true))
    {
	getNext()->finish();
    }
}

Buffer*
Pl_Buffer::getBuffer()
{
    if (! this->m->ready)
    {
	throw std::logic_error("Pl_Buffer::getBuffer() called when not ready");
    }

    Buffer* b = new Buffer(this->m->total_size);
    if (this->m->total_size > 0)
    {
        unsigned char* p = b->getBuffer();
        memcpy(p, this->m->data->getBuffer(), this->m->total_size);
    }
    this->m = PointerHolder<Members>(new Members());
    return b;
}

PointerHolder<Buffer>
Pl_Buffer::getBufferSharedPointer()
{
    return PointerHolder<Buffer>(getBuffer());
}

void
Pl_Buffer::getMallocBuffer(unsigned char **buf, size_t* len)
{
    if (! this->m->ready)
    {
	throw std::logic_error(
            "Pl_Buffer::getMallocBuffer() called when not ready");
    }

    *len = this->m->total_size;
    if (this->m->total_size > 0)
    {
        *buf = reinterpret_cast<unsigned char*>(malloc(this->m->total_size));
        memcpy(*buf, this->m->data->getBuffer(), this->m->total_size);
    }
    else
    {
        *buf = nullptr;
    }
    this->m = new Members();
}