xref: /aosp_15_r20/external/pdfium/core/fxcodec/cfx_codec_memory.cpp (revision 3ac0a46f773bac49fa9476ec2b1cf3f8da5ec3a4)
1 // Copyright 2018 The PDFium Authors
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 
9 #include "core/fxcrt/span_util.h"
10 
CFX_CodecMemory(size_t buffer_size)11 CFX_CodecMemory::CFX_CodecMemory(size_t buffer_size)
12     : buffer_(FX_Alloc(uint8_t, buffer_size)), size_(buffer_size) {}
13 
14 CFX_CodecMemory::~CFX_CodecMemory() = default;
15 
Seek(size_t pos)16 bool CFX_CodecMemory::Seek(size_t pos) {
17   if (pos > size_)
18     return false;
19 
20   pos_ = pos;
21   return true;
22 }
23 
ReadBlock(pdfium::span<uint8_t> buffer)24 size_t CFX_CodecMemory::ReadBlock(pdfium::span<uint8_t> buffer) {
25   if (buffer.empty() || IsEOF())
26     return 0;
27 
28   size_t bytes_to_read = std::min(buffer.size(), size_ - pos_);
29   fxcrt::spancpy(buffer, GetBufferSpan().subspan(pos_, bytes_to_read));
30   pos_ += bytes_to_read;
31   return bytes_to_read;
32 }
33 
TryResize(size_t new_buffer_size)34 bool CFX_CodecMemory::TryResize(size_t new_buffer_size) {
35   uint8_t* pOldBuf = buffer_.release();
36   uint8_t* pNewBuf = FX_TryRealloc(uint8_t, pOldBuf, new_buffer_size);
37   if (new_buffer_size && !pNewBuf) {
38     buffer_.reset(pOldBuf);
39     return false;
40   }
41   buffer_.reset(pNewBuf);
42   size_ = new_buffer_size;
43   return true;
44 }
45 
Consume(size_t consumed)46 void CFX_CodecMemory::Consume(size_t consumed) {
47   fxcrt::spanmove(GetBufferSpan(), GetBufferSpan().subspan(consumed));
48 }
49