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 "xfa/fde/css/cfde_csstextbuf.h"
8
9 #include <algorithm>
10
CFDE_CSSTextBuf()11 CFDE_CSSTextBuf::CFDE_CSSTextBuf()
12 : m_bExtBuf(false),
13 m_pBuffer(nullptr),
14 m_iBufLen(0),
15 m_iDatLen(0),
16 m_iDatPos(0) {}
17
~CFDE_CSSTextBuf()18 CFDE_CSSTextBuf::~CFDE_CSSTextBuf() {
19 Reset();
20 }
21
Reset()22 void CFDE_CSSTextBuf::Reset() {
23 if (!m_bExtBuf) {
24 FX_Free(m_pBuffer);
25 m_pBuffer = nullptr;
26 }
27 m_iDatPos = m_iDatLen = m_iBufLen;
28 }
29
AttachBuffer(const FX_WCHAR * pBuffer,int32_t iBufLen)30 bool CFDE_CSSTextBuf::AttachBuffer(const FX_WCHAR* pBuffer, int32_t iBufLen) {
31 Reset();
32 m_pBuffer = const_cast<FX_WCHAR*>(pBuffer);
33 m_iDatLen = m_iBufLen = iBufLen;
34 return m_bExtBuf = true;
35 }
36
EstimateSize(int32_t iAllocSize)37 bool CFDE_CSSTextBuf::EstimateSize(int32_t iAllocSize) {
38 ASSERT(iAllocSize > 0);
39 Clear();
40 m_bExtBuf = false;
41 return ExpandBuf(iAllocSize);
42 }
43
LoadFromStream(const CFX_RetainPtr<IFGAS_Stream> & pTxtStream,int32_t iStreamOffset,int32_t iMaxChars,bool & bEOS)44 int32_t CFDE_CSSTextBuf::LoadFromStream(
45 const CFX_RetainPtr<IFGAS_Stream>& pTxtStream,
46 int32_t iStreamOffset,
47 int32_t iMaxChars,
48 bool& bEOS) {
49 ASSERT(iStreamOffset >= 0 && iMaxChars > 0);
50 Clear();
51 m_bExtBuf = false;
52 if (!ExpandBuf(iMaxChars))
53 return 0;
54
55 if (pTxtStream->GetPosition() != iStreamOffset)
56 pTxtStream->Seek(FX_STREAMSEEK_Begin, iStreamOffset);
57
58 m_iDatLen = pTxtStream->ReadString(m_pBuffer, iMaxChars, bEOS);
59 return m_iDatLen;
60 }
61
ExpandBuf(int32_t iDesiredSize)62 bool CFDE_CSSTextBuf::ExpandBuf(int32_t iDesiredSize) {
63 if (m_bExtBuf)
64 return false;
65 if (!m_pBuffer)
66 m_pBuffer = FX_Alloc(FX_WCHAR, iDesiredSize);
67 else if (m_iBufLen != iDesiredSize)
68 m_pBuffer = FX_Realloc(FX_WCHAR, m_pBuffer, iDesiredSize);
69 else
70 return true;
71
72 if (!m_pBuffer) {
73 m_iBufLen = 0;
74 return false;
75 }
76 m_iBufLen = iDesiredSize;
77 return true;
78 }
79
Subtract(int32_t iStart,int32_t iLength)80 void CFDE_CSSTextBuf::Subtract(int32_t iStart, int32_t iLength) {
81 ASSERT(iStart >= 0 && iLength >= 0);
82
83 iLength = std::max(std::min(iLength, m_iDatLen - iStart), 0);
84 FXSYS_memmove(m_pBuffer, m_pBuffer + iStart, iLength * sizeof(FX_WCHAR));
85 m_iDatLen = iLength;
86 }
87