2
1
mirror of https://github.com/qpdf/qpdf.git synced 2024-11-18 10:25:12 +00:00
qpdf/libqpdf/Pl_Buffer.cc

100 lines
2.3 KiB
C++
Raw Normal View History

#include <qpdf/Pl_Buffer.hh>
2018-08-16 15:52:59 +00:00
#include <algorithm>
#include <assert.h>
#include <stdexcept>
2021-12-17 12:33:42 +00:00
#include <stdlib.h>
#include <string.h>
Pl_Buffer::Members::Members() :
2018-03-06 16:24:30 +00:00
ready(true),
total_size(0)
{
}
Pl_Buffer::Pl_Buffer(char const* identifier, Pipeline* next) :
Pipeline(identifier, next),
m(new Members())
{
}
Pl_Buffer::~Pl_Buffer()
{
// Must be explicit and not inline -- see QPDF_DLL_CLASS in
// README-maintainer
}
void
Pl_Buffer::write(unsigned char* buf, size_t len)
{
if (this->m->data.get() == 0) {
this->m->data = std::make_shared<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);
auto b = std::make_shared<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 = std::shared_ptr<Members>(new Members());
return b;
}
2021-12-17 12:33:42 +00:00
std::shared_ptr<Buffer>
Pl_Buffer::getBufferSharedPointer()
{
return std::shared_ptr<Buffer>(getBuffer());
}
2021-12-17 12:33:42 +00:00
void
Pl_Buffer::getMallocBuffer(unsigned char** buf, size_t* len)
2021-12-17 12:33:42 +00:00
{
if (!this->m->ready) {
throw std::logic_error(
2021-12-17 12:33:42 +00:00
"Pl_Buffer::getMallocBuffer() called when not ready");
}
*len = this->m->total_size;
if (this->m->total_size > 0) {
2021-12-17 12:33:42 +00:00
*buf = reinterpret_cast<unsigned char*>(malloc(this->m->total_size));
memcpy(*buf, this->m->data->getBuffer(), this->m->total_size);
} else {
2021-12-17 12:33:42 +00:00
*buf = nullptr;
}
this->m = std::shared_ptr<Members>(new Members());
2021-12-17 12:33:42 +00:00
}