1 // Copyright 2018 PDFium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 #include "core/fxcodec/cfx_codec_memory.h"
6
7 #include <algorithm>
8
CFX_CodecMemory(size_t buffer_size)9 CFX_CodecMemory::CFX_CodecMemory(size_t buffer_size)
10 : buffer_(FX_Alloc(uint8_t, buffer_size)), size_(buffer_size) {}
11
12 CFX_CodecMemory::~CFX_CodecMemory() = default;
13
Seek(size_t pos)14 bool CFX_CodecMemory::Seek(size_t pos) {
15 if (pos > size_)
16 return false;
17
18 pos_ = pos;
19 return true;
20 }
21
ReadBlock(void * buffer,size_t size)22 size_t CFX_CodecMemory::ReadBlock(void* buffer, size_t size) {
23 if (!buffer || !size || IsEOF())
24 return 0;
25
26 size_t bytes_to_read = std::min(size, size_ - pos_);
27 memcpy(buffer, buffer_.get() + pos_, bytes_to_read);
28 pos_ += bytes_to_read;
29 return bytes_to_read;
30 }
31
TryResize(size_t new_buffer_size)32 bool CFX_CodecMemory::TryResize(size_t new_buffer_size) {
33 uint8_t* pOldBuf = buffer_.release();
34 uint8_t* pNewBuf = FX_TryRealloc(uint8_t, pOldBuf, new_buffer_size);
35 if (new_buffer_size && !pNewBuf) {
36 buffer_.reset(pOldBuf);
37 return false;
38 }
39 buffer_.reset(pNewBuf);
40 size_ = new_buffer_size;
41 return true;
42 }
43
Consume(size_t consumed)44 void CFX_CodecMemory::Consume(size_t consumed) {
45 size_t unconsumed = size_ - consumed;
46 memmove(buffer_.get(), buffer_.get() + consumed, unconsumed);
47 }
48