• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2017 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 // Original code copyright 2014 Foxit Software Inc. http://www.foxitsoftware.com
6 
7 #include "core/fxcrt/cfx_binarybuf.h"
8 
9 #include <algorithm>
10 #include <utility>
11 
CFX_BinaryBuf()12 CFX_BinaryBuf::CFX_BinaryBuf()
13     : m_AllocStep(0), m_AllocSize(0), m_DataSize(0) {}
14 
~CFX_BinaryBuf()15 CFX_BinaryBuf::~CFX_BinaryBuf() {}
16 
Delete(size_t start_index,size_t count)17 void CFX_BinaryBuf::Delete(size_t start_index, size_t count) {
18   if (!m_pBuffer || count > m_DataSize || start_index > m_DataSize - count)
19     return;
20 
21   memmove(m_pBuffer.get() + start_index, m_pBuffer.get() + start_index + count,
22           m_DataSize - start_index - count);
23   m_DataSize -= count;
24 }
25 
GetLength() const26 size_t CFX_BinaryBuf::GetLength() const {
27   return m_DataSize;
28 }
29 
Clear()30 void CFX_BinaryBuf::Clear() {
31   m_DataSize = 0;
32 }
33 
DetachBuffer()34 std::unique_ptr<uint8_t, FxFreeDeleter> CFX_BinaryBuf::DetachBuffer() {
35   m_DataSize = 0;
36   m_AllocSize = 0;
37   return std::move(m_pBuffer);
38 }
39 
EstimateSize(size_t size,size_t step)40 void CFX_BinaryBuf::EstimateSize(size_t size, size_t step) {
41   m_AllocStep = step;
42   if (m_AllocSize < size)
43     ExpandBuf(size - m_DataSize);
44 }
45 
ExpandBuf(size_t add_size)46 void CFX_BinaryBuf::ExpandBuf(size_t add_size) {
47   FX_SAFE_SIZE_T new_size = m_DataSize;
48   new_size += add_size;
49   if (m_AllocSize >= new_size.ValueOrDie())
50     return;
51 
52   size_t alloc_step = std::max(static_cast<size_t>(128),
53                                m_AllocStep ? m_AllocStep : m_AllocSize / 4);
54   new_size += alloc_step - 1;  // Quantize, don't combine these lines.
55   new_size /= alloc_step;
56   new_size *= alloc_step;
57   m_AllocSize = new_size.ValueOrDie();
58   m_pBuffer.reset(m_pBuffer
59                       ? FX_Realloc(uint8_t, m_pBuffer.release(), m_AllocSize)
60                       : FX_Alloc(uint8_t, m_AllocSize));
61 }
62 
AppendBlock(const void * pBuf,size_t size)63 void CFX_BinaryBuf::AppendBlock(const void* pBuf, size_t size) {
64   if (size == 0)
65     return;
66 
67   ExpandBuf(size);
68   if (pBuf) {
69     memcpy(m_pBuffer.get() + m_DataSize, pBuf, size);
70   } else {
71     memset(m_pBuffer.get() + m_DataSize, 0, size);
72   }
73   m_DataSize += size;
74 }
75